当我使用 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”相同。
#read data
dataframe = pd.read_csv('challenge_dataset.txt')
dataframe.columns=['Brain','Body']
x_values=dataframe[['Brain']]
y_values=dataframe[['Body']]
为什么会这样?
提前致谢。
最佳答案
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()
关于python - 使用 matplotlib 绘制 sklearn LinearRegression 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46382550/