我发现最小二乘适合线性、二次和三次函数,并试图打印它们的错误。一切正常,但我不明白为什么如果我每次都变得更好,他们的错误会增加,我是否以错误的方式计算错误?这是情节,我的代码如下:
例如,这是让我获得立方图的代码。
import numpy as np
import matplotlib.pyplot as plt
A = np.array(((0,1),
(1,1),
(2,1),
(3,1)))
xfeature = A.T[0]
squaredfeature = A.T[0] ** 2
cubedfeature = A.T[0] ** 3
ones = np.ones(4)
b = np.array((1,2,0,3), ndmin=2 ).T
b = b.reshape(4)
order = 3
features = np.concatenate((np.vstack(ones), np.vstack(xfeature), np.vstack(squaredfeature), np.vstack(cubedfeature)), axis = 1)
xstar = np.matmul( np.matmul( np.linalg.inv( np.matmul(features.T, features) ), features.T), b)
plt.scatter(A.T[0],b, c = 'red')
u = np.linspace(0,3,1000)
plt.plot(u, u**3*xstar[3] + u**2*xstar[2] + u*xstar[1] + xstar[0], 'b-')
plt.show()
b = np.array((1,2,0,3), ndmin=2 ).T
y_prediction = u**3*xstar[3] + u**2*xstar[2] + u*xstar[1] + xstar[0]
SSE = np.sum(np.square(y_prediction - b))
MSE = np.mean(np.square(y_prediction - b))
print("Sum of squared errors:", SSE)
print("Mean squared error:", MSE)