【发布时间】:2018-05-25 10:56:44
【问题描述】:
下面的代码基于http://www.johnwittenauer.net/machine-learning-exercises-in-python-part-1/工作
theta = np.matrix(np.array([0, 0]))
def computeCost(X, y, theta, iterations, alpha):
temp = np.matrix(np.zeros(theta.shape))
m = len(X)
theta_trans = theta.T
for j in range(iterations):
hyp = np.dot(X, theta_trans)-y
term = np.multiply(hyp, X[:,0])
temp[0,0] = theta[0,0] - ((alpha / len(X)) * np.sum(term))
term = np.multiply(hyp, X[:,1])
temp[0,1] = theta[0,1] - ((alpha / len(X)) * np.sum(term))
theta = temp
theta_trans = theta.T
return theta
但是,当我直接使用 theta 而不是 temp 时,例如theta[0,0] = theta[0,0] - ((alpha / len(X)) * np.sum(term))) 并注释掉 theta = temp 我总是得到 0 和 0 的 theta。
当我在函数之外进行类似操作时,theta 会改变。例如,
theta = np.matrix(np.array([0,0]))
theta[0,0] = theta[0,0] - 1
print(theta)
theta 显示为 [-1 , 0]。
为什么这种类型的赋值在函数内部不起作用?
【问题讨论】:
-
我不明白你的代码:你有一个循环,但没有使用迭代变量
j。 -
能否也越过调用函数的行,以便我们在与我们相同的条件下对其进行测试。
标签: python numpy machine-learning