线性回归\渐变下降python实现(Linear Regression\Gradient Descent python implementation)

编程入门 行业动态 更新时间:2024-10-18 10:14:32
线性回归\渐变下降python实现(Linear Regression\Gradient Descent python implementation)

我试图从头开始使用渐变下降方法进行线性回归以用于学习目的。 我的代码的一部分真的让我烦恼。 出于某种原因,变量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)])

更多推荐

本文发布于:2023-08-01 15:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1359228.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线性   Linear   python   Regression   Descent

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!