为什么这条线性回归线是直线的?
我有X和Y坐标的积分,我想通过线性回归符合一条直线,但我得到了锯齿状的线条。
我正在使用Sklearn的线性重试。
为了创建点循环的点A,将一百个随机板条的循环插入100 x 2的阵列中。我将其左侧切成XS,并将其右侧切成YS。
我希望当我打印M.Predict
时,我希望有一条直线。
import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.linear_model import LinearRegression
X = []
adder = 0
for z in range(100):
r = random.random() * 20
r2 = random.random() * 15
X.append([r+adder-0.4, r2+adder])
adder += 0.6
X = np.array(X)
plt.scatter(X[:,0], X[:,1], s=10)
plt.show()
m = LinearRegression()
m.fit(X[:,0].reshape(1, -1), X[:,1].reshape(1, -1))
plt.plot(m.predict(X[:,0].reshape(1, -1))[0])
I have points with x and y coordinates I want to fit a straight line to with Linear Regression but I get a jagged looking line.
I am attemting to use LinearRegression from sklearn.
To create the points run a for loop that randomly crates one hundred points into an array that is 100 x 2 in shape. I slice the left side of it for the xs and the right side of it for the ys.
I expect to have a straight line when I print m.predict
.
import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.linear_model import LinearRegression
X = []
adder = 0
for z in range(100):
r = random.random() * 20
r2 = random.random() * 15
X.append([r+adder-0.4, r2+adder])
adder += 0.6
X = np.array(X)
plt.scatter(X[:,0], X[:,1], s=10)
plt.show()
m = LinearRegression()
m.fit(X[:,0].reshape(1, -1), X[:,1].reshape(1, -1))
plt.plot(m.predict(X[:,0].reshape(1, -1))[0])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对numpy不好,但是,我认为这是因为使用
reshape()
函数将x [:,0]
和x [:,, 1]
从1d到2D,结果2D数组仅包含一个元素,而不是创建len(x [:0])的2D数组
and code> len(x [:,1])。并导致不希望的回归器。我能够使用大熊猫重新创建该模型,并能够绘制所需的结果。代码如下
I am not good with numpy but, I think it is because the use of
reshape()
function to convertX[:,0]
andX[:,1]
from 1D to 2D, the resulting 2D array contains only one element, instead of creating a 2D array oflen(X[:,0])
andlen(X[:,1])
respectively. And resulting into an undesired regressor.I am able to recreate this model using pandas and able to plot the desired result. Code as follows