python - 使用 matplotlib 绘制 sklearn LinearRegression 输出

标签 python pandas numpy matplotlib

当我使用 numpy 分隔 x_values 和 y_values 时导入文件后:

import pandas as pd
from sklearn import linear_model
from  matplotlib import pyplot 
import numpy as np

#read data
dataframe = pd.read_csv('challenge_dataset.txt')
dataframe.columns=['Brain','Body']
x_values=np.array(dataframe['Brain'],dtype=np.float64).reshape(1,-1)
y_values=np.array(dataframe['Body'],dtype=np.float64).reshape(1,-1)

#train model on data
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)
prediction=body_reg.predict(x_values)

print(prediction)
#visualize results
pyplot.scatter(x_values, y_values)
pyplot.plot(x_values,prediction)
pyplot.show()

我得到的图如下图所示,它没有显示最佳拟合线,而且当我打印“预测”的值时,它显示的值与“y_values”相同。

enter image description here 相反,当我使用以下代码时。我得到了回归线。

#read data
dataframe = pd.read_csv('challenge_dataset.txt')
dataframe.columns=['Brain','Body']
x_values=dataframe[['Brain']]
y_values=dataframe[['Body']]

enter image description here

为什么会这样?

提前致谢。

最佳答案

linear_model.LinearRegression().fit(X,y)期望它的参数

X : numpy array or sparse matrix of shape [n_samples,n_features]
y : numpy array of shape [n_samples, n_targets]

这里有 1 个“特征”和 1 个“目标”,因此输入的预期形状为 (n_samples,1)

虽然是这样

x_values=dataframe[['Brain']]
y_values=dataframe[['Body']]

np.array(dataframe['Brain'],dtype=np.float64).reshape(1,-1) 的形状是 (n_samples,) .

从数据框列中获取所需形状的另一种选择是将它们广播到具有新轴的二维数组

x_values=dataframe['Brain'].values[:,np.newaxis]
y_values=dataframe['Body'].values[:,np.newaxis]

请注意,为了显示一条漂亮的线,您可能需要对 x 值进行排序。

import pandas as pd
from sklearn import linear_model
from  matplotlib import pyplot 
import numpy as np

#read data
x = np.random.rand(25,2)
x[:,1] = 2*x[:,0]+np.random.rand(25)
dataframe = pd.DataFrame(x,columns=['Brain','Body'])


x_values=dataframe['Brain'].values[:,np.newaxis]
y_values=dataframe['Body'].values[:,np.newaxis]

body_reg = linear_model.LinearRegression()
body_reg.fit(x_values, y_values)
prediction=body_reg.predict(np.sort(x_values, axis=0))

pyplot.scatter(x_values, y_values)
pyplot.plot(np.sort(x_values, axis=0),prediction)
pyplot.show()

enter image description here

关于python - 使用 matplotlib 绘制 sklearn LinearRegression 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46382550/

相关文章:

Python 二十一点 UnboundLocalError

python - 更快地读取 CSV 文件

python - 对称矩阵的逆

python 稀疏 gmres 与输入参数混淆

python - 使用 numpy 和 mencoder 直接绘制到电影中

python - 如何使用python将稀疏矩阵转换为密集形式

python - 什么是 [ :, :-1] in python?

python - 函数名称中的 <locals> 是什么意思?

python - 在 pandas 中使用 sumproduct 或 dot 函数

python - Pandas 数据框 : slicing column values using second column for slice index