0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

最小二乗法で2次関数による近似と線形結合

Posted at

参考リンクまとめ


Pythonコード(最小二乗法で2次関数による近似)

# 必要なライブラリをインポート / Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt

# サンプルデータの生成 / Generate sample data
np.random.seed(0)  # 再現性のためのシード固定 / Set random seed for reproducibility
x = np.linspace(-3, 3, 50)
y_true = 2 + 0.5 * x - x**2           # 真の関数(2次関数) / True function
y = y_true + np.random.normal(0, 1, x.shape)  # ノイズを加えた観測値 / Noisy observations

# 最小二乗法のためのX行列の構築 / Design matrix for least squares
X = np.vstack([np.ones_like(x), x, x**2]).T  # [1, x, x^2] の列ベクトル

# 最小二乗法による係数ベクトルの計算 / Solve least squares: c = (X^T X)^(-1) X^T y
c_hat = np.linalg.inv(X.T @ X) @ X.T @ y

# 近似曲線の計算 / Predicted values using fitted coefficients
y_fit = X @ c_hat

# グラフの描画 / Plot the data and the approximation
plt.figure(figsize=(8, 6))
plt.scatter(x, y, label='Observed Data', color='blue')
plt.plot(x, y_true, label='True Function', linestyle='--', color='gray')
plt.plot(x, y_fit, label='Least Squares Fit (Quadratic)', color='red')
plt.title('Quadratic Approximation by Least Squares')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()

# 係数の表示 / Print coefficients
print("Fitted coefficients (c0, c1, c2):", c_hat)

結果

image.png

Pythonコード:関数データをベクトルとして扱い、内積・スカラー倍・基底展開の基本を実演

import numpy as np
import matplotlib.pyplot as plt

# -------------------------------
# データ準備:関数の離散化(ベクトル化)
# -------------------------------

x = np.linspace(0, 2 * np.pi, 100)

# 関数定義(ベクトル化)
vec_quad = x**2              # 2次関数 y = x^2
vec_sin = np.sin(x)          # 三角関数 y = sin(x)
vec_cos = np.cos(x)          # 三角関数 y = cos(x)

# -------------------------------
# 1. ベクトルとしての可視化
# -------------------------------
plt.plot(x, vec_quad, label='y = x^2')
plt.plot(x, vec_sin, label='y = sin(x)')
plt.plot(x, vec_cos, label='y = cos(x)')
plt.title('Function as Vectors')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()

# -------------------------------
# 2. ベクトル演算(内積・スカラー倍)
# -------------------------------

# 内積(関数同士の類似度)
dot_sin_cos = np.dot(vec_sin, vec_cos)
print(f"Inner product <sin, cos> = {dot_sin_cos:.4f}")

# スカラー倍(振幅を2倍に)
vec_sin_scaled = 2 * vec_sin

# -------------------------------
# 3. 基底展開の例(sinとcosの線形結合)
# -------------------------------

# sin(x) + 0.5 * cos(x) として関数を構成
combined = vec_sin + 0.5 * vec_cos

plt.plot(x, combined, label='sin(x) + 0.5cos(x)', color='purple')
plt.title('Linear Combination of sin and cos')
plt.grid()
plt.legend()
plt.show()

結果
image.png

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?