Python 数学作业的多元回归法

Python 数学作业的多元回归法,python,numpy,machine-learning,Python,Numpy,Machine Learning,我想用多元回归和最小二乘法作为我的代价函数来寻找a,b,c,对于ax^2+bx+c,它最适合cos(x)从(-2,2)。我的成本不会降低,但高得离谱——我做错了什么 x = np.linspace(-2,2,100) y = np.cos(x) theta = np.random.random((3,1)) m = len(y) for i in range(10000): #Calculate my y_hat y_hat = np.array([(theta[0]*(a*

我想用多元回归和最小二乘法作为我的代价函数来寻找a,b,c,对于ax^2+bx+c,它最适合cos(x)从(-2,2)。我的成本不会降低,但高得离谱——我做错了什么

x = np.linspace(-2,2,100)
y = np.cos(x)

theta = np.random.random((3,1))
m = len(y)

for i in range(10000):
    #Calculate my y_hat
    y_hat = np.array([(theta[0]*(a**2) + theta[1]*a + theta[2]) for a in x])

    #Calculate my cost based off y_hat and y
    cost = np.sum((y_hat - y) ** 2) * (1/m)

    #Calculate my derivatives based off y_hat and x
    da = (2 / m) * np.sum((y_hat - y) * (x**2))
    db = (2 / m) * np.sum((y_hat - y) * (x))
    dc  = (2 / m) * np.sum((y_hat - y))

    #update step
    theta[0] = theta[0] - 0.0001*(da)
    theta[1] = theta[1] - 0.0001*(db)
    theta[2] = theta[2] - 0.0001*(dc)

    print("Epoch Num: {} Cost: {}".format(i, cost))

print(theta)

您计算的
y\u hat
有点不正确。它目前是一个二维形状数组
(100,1)

这应该会有所帮助。它从每行中提取“zeroith”元素:

theta_ = [(theta[0]*(a**2) + theta[1]*a + theta[2]) for a in x]
y_hat = np.array([t[0] for t in theta_])

你犯了一个错误。也许是通过计算
y_hat
y_hat.shape
返回
(100,1)
,而
y.shape
返回
(100,)
啊,我没有注意到两者之间的区别。我把它改成了一维阵列(100),但我的成本仍然没有得到优化。我不太确定哪里有错误。。。。。