import numpy as np import matplotlib.pyplot as plt # カーブの次元 M = 6 def estimate(xlist, tlist) : """パラメータwの推定""" A = np.zeros((M+1, M+1)) for i in range(M+1) : for j in range(M+1) : A[i][j] = (xlist**(i+j)).sum() T = np.zeros(M+1) for i in range(M+1) : T[i] = ((xlist**i)*tlist).sum() wlist = np.linalg.solve(A, T) return wlist def fitting(xin, wlist) : fit = wlist[0] for i in range(1, M+1) : fit += wlist[i] * xin**i return fit def slut() : x = np.linspace(0, 1, 10) t = np.sin(2*np.pi*x) + np.random.normal(0, 0.3, x.size) plt.scatter(x, t, marker='o', c='white', edgecolor='limegreen') w = estimate(x, t) # ideal carve ideal = np.sin(2*np.pi*np.linspace(0, 1, 500)) plt.plot(np.linspace(0, 1, 500), ideal, markersize=6, color='black') # estimated model model = [fitting(xin, w) for xin in np.linspace(0, 1, 500)] plt.plot(np.linspace(0, 1, 500), model, markersize=6, color='darkorchid') plt.show() if __name__ == '__main__' : slut()