我在尝试运行下面的代码时出错:
def h(x):
global w
return sum(np.transpose(w)*x)
raise NotImplementedError()
def cost_func_linreg(X, y):
m = len(y)
for i in range(1, m+1):
X_i = np.power(X, i)
c= np.sum(np.square(h(X_i) - y))
return (1/(2*m))*c
raise NotImplementedError()
如果输入如下,则工作正常:
w, X, y = [-1, 0], [[1,1],[0,1]], [-1,0]
但是,当输入如下时,我得到了一个错误:
w, X, y = [1, 1, 2], [[1,1,1],[0,0,0]], [0,0]
cost_func_linreg(X,y)
它返回一个错误:
ValueError: operands could not be broadcast together with shapes (3,) (2,)
它指出错误在:
----> 9 c= np.sum(np.square(h(X_i) - y))
结果是什么还不完全清楚,但尝试用h(x(:中的np.sum
替换sum
def h(x):
global w
return np.sum(np.transpose(w)*x)
至少它没有给出错误:(