我试图从头开始使用渐变下降方法进行线性回归以用于学习目的。 我的代码的一部分真的让我烦恼。 出于某种原因,变量x在我运行一行代码后被更改,我不知道为什么。
变量如下。 x和y是numpy数组,我给出了这个例子的随机数。
x = np.array([1, 2, 3, 4, ...., n]) y = np.array([1, 2, 3, , ...., n]) theta = [0, 0] alpha = .01 m = len(x)代码是:
theta[0] = theta[0] - alpha*1/m*sum([((theta[0]+theta[1]*x) - y)**2 for (x,y) in zip(x,y)])一旦我运行上面的代码x不再是一个列表。 它只成为变量n或列表中的最后一个元素。
I'm trying to implement linear regression using the gradient descent method from scratch for learning purposes. One part of my code is really bugging me. For some reason the variable x is being altered after I run a line of code and I'm not sure why.
The variables are as follow. x and y are numpy arrays and I've given them random numbers for this example.
x = np.array([1, 2, 3, 4, ...., n]) y = np.array([1, 2, 3, , ...., n]) theta = [0, 0] alpha = .01 m = len(x)The code is:
theta[0] = theta[0] - alpha*1/m*sum([((theta[0]+theta[1]*x) - y)**2 for (x,y) in zip(x,y)])Once I run the above code x is no longer a list. It becomes only the variable n or the last element in the list.
最满意答案
发生了什么是Python正在计算列表zip(x,y) ,然后for循环的每次迭代都用zip(x,y)的相应元素覆盖zip(x,y) 。 当for循环终止时(x,y)包含zip(x,y)[-1] 。
尝试
theta[0] = theta[0] - alpha*1/m*sum([((theta[0]+theta[1]*xi) - yi)**2 for (xi,yi) in zip(x,y)])What is happening is that python is computing the list zip(x,y), then each iteration of your for loop is overwriting (x,y) with the corresponding element of zip(x,y). When your for loop terminates (x,y) contains zip(x,y)[-1].
Try
theta[0] = theta[0] - alpha*1/m*sum([((theta[0]+theta[1]*xi) - yi)**2 for (xi,yi) in zip(x,y)])更多推荐
发布评论