lsq_polynomial.py ダウンロード/コピー

lsq_polynomial.py をダウンロード

lsq_polynomial.py
lsq_polynomial.py
  1#!/usr/bin/env python3
  2"""
  3概要:
  4    Excelファイルからデータを読み込み、多項式最小二乗法でフィッティングを行うスクリプトです。
  5
  6詳細説明:
  7    コマンドライン引数で入力Excelファイルと多項式の次数を受け取ります。
  8    pandasを使ってデータを読み込み、numpy.polyfitで多項式近似を行います。
  9    結果はCSVファイルとして出力され、グラフが表示されます。
 10
 11関連リンク:
 12    lsq_polynomial_usage
 13"""
 14
 15import sys
 16from pathlib import Path
 17
 18import numpy as np
 19import pandas as pd
 20import matplotlib.pyplot as plt
 21
 22
 23def main():
 24    """
 25    概要:
 26        多項式最小二乗法フィッティングのメイン処理を実行します。
 27
 28    詳細説明:
 29        コマンドライン引数を解析し、データの読み込み、numpy.polyfitによる
 30        フィッティング、決定係数の計算、CSV出力、グラフ描画を行います。
 31        引数が足りない場合は使用方法を表示してスクリプトを終了します。
 32    """
 33
 34    if len(sys.argv) < 3:
 35        print("Usage:")
 36        print("  python lsq_polynomial.py data.xlsx order")
 37        sys.exit(1)
 38
 39    infile = sys.argv[1]
 40    degree = int(sys.argv[2])
 41
 42    outfile = Path(infile).stem + "_fit.csv"
 43
 44    # Excel読込み
 45    df = pd.read_excel(infile)
 46
 47    x = df.iloc[:, 0].to_numpy()
 48    y = df.iloc[:, 1].to_numpy()
 49
 50    # 多項式最小二乗法
 51    coeffs = np.polyfit(x, y, degree)
 52
 53    # Polynomialオブジェクト作成
 54    poly = np.poly1d(coeffs)
 55
 56    # 近似値計算
 57    y_fit = poly(x)
 58
 59    # 決定係数 R²
 60    ss_res = np.sum((y - y_fit) ** 2)
 61    ss_tot = np.sum((y - np.mean(y)) ** 2)
 62    r2 = 1.0 - ss_res / ss_tot
 63
 64    # 結果表示
 65    print()
 66    print(f"Input file : {infile}")
 67    print(f"Order      : {degree}")
 68    print()
 69    print("Polynomial:")
 70    print(poly)
 71    print()
 72    print(f"R² = {r2:.6f}")
 73    print()
 74
 75    # CSV出力
 76    result = pd.DataFrame({
 77        "x": x,
 78        "y": y,
 79        "y_fit": y_fit
 80    })
 81
 82    result.to_csv(outfile, index=False)
 83
 84    print(f"Saved : {outfile}")
 85
 86    # 滑らかな曲線描画用
 87    x_plot = np.linspace(x.min(), x.max(), 1000)
 88    y_plot = poly(x_plot)
 89
 90    # Plot
 91    plt.figure(figsize=(8, 6))
 92
 93    plt.scatter(
 94        x,
 95        y,
 96        label="Data",
 97        color="tab:blue"
 98    )
 99
100    plt.plot(
101        x_plot,
102        y_plot,
103        label=f"Polynomial (n={degree})",
104        color="tab:red"
105    )
106
107    plt.xlabel("x")
108    plt.ylabel("y")
109    plt.title("Polynomial Least-Squares Fit")
110    plt.legend()
111    plt.grid(True)
112
113    plt.tight_layout()
114    plt.show()
115
116
117if __name__ == "__main__":
118    main()