正規方程式による線形回帰を最小二乗法によって行うテンプレートです。
import matplotlib.pyplot as plt
import numpy as np
#基底関数
def f(x) -> float:
return 2*np.sin(x) + 5
np.random.seed(0)
x = np.linspace(0, np.pi/3, 8)
y = [np.random.random() + f(x) for x in x]
plt.grid()
plt.scatter(x, y,s = 20)
plt.savefig("b.png", dpi=800, bbox_inches='tight')
#線形回帰
W = np.array([[np.sin(i),1] for i in x])
f = np.array(y)
Wt = W.T
WtW = np.dot(Wt,W)
WtW_inv = np.linalg.inv(WtW)
WtW_invWt = np.dot(WtW_inv,Wt)
theta = np.dot(WtW_invWt,f)
print(theta)
plt.plot(x, theta[0]*np.sin(x) + theta[1],color ="red")
plt.savefig("reuslt.png", dpi=800)実行結果


