【发布时间】: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