【问题标题】:Multivariate Regression Numpy for Math Homework数学作业的多元回归 Numpy
【发布时间】:2018-04-20 00:19:53
【问题描述】:

我希望使用具有最小二乘法的多元回归作为我的成本函数,以从 (-2,2) 中找到最适合 cos(x) 的 ax^2 +bx + c 的 a,b,c。我的成本不会减少,但高得离谱——我做错了什么?

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_hat的计算? y_hat.shape 返回(100, 1),而y.shape 返回(100,)

标签: python numpy machine-learning


【解决方案1】:

您对y_hat 的计算略有不正确。它目前是形状为(100,1) 的二维数组。

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

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

【讨论】:

  • 啊,我没有注意到两者之间的区别。我将其更改为一维数组(100),但我的成本仍未优化。我不太确定哪里有错误.....
猜你喜欢
  • 2020-10-09
  • 2014-02-20
  • 1970-01-01
  • 2020-09-12
  • 2016-04-28
  • 2016-04-19
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
相关资源
最近更新 更多