简体   繁体   English

显示带有线性回归 sklearn 的图

[英]display a plot with linear regression sklearn

I have a dataset with X = ['x', 'y'] the two first columns of my dataset and in target the data['class'].我有一个数据集,其中 X = ['x', 'y'] 我的数据集的前两列和目标数据 ['class']。 But i doesn't how display a plot of linear regression in this case.但我不知道在这种情况下如何显示线性回归图。 Because I have the error "x and y must be the same size".因为我有错误“x 和 y 必须是相同的大小”。 So how i can plot a linear regression and predict with a dataset or i take X as the first two column of my dataset and in target the last column ?那么我如何绘制线性回归并使用数据集进行预测,或者我将 X 作为数据集的前两列并在目标最后一列? Thanks so much for the help, here my code below :非常感谢您的帮助,下面是我的代码:

data = pd.read_csv('data.csv')
X = data[['x', 'y']]
data['class'] = np.where(data['class']=='P', 1, 0)
Y = data['class']

plt.scatter(X, Y,  color='blue')
plt.xlabel('x')  
plt.ylabel('y')
plt.plot(X, Y, color='red', linewidth=2)
plt.show()

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=0)
regressor = LinearRegression()  
regressor.fit(X_train, y_train)

Based on the offical documentation :根据官方文档

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=0)
regressor = LinearRegression()  
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test) #adding your prediction, this was missing

import matplotlib.pyplot as plt
import numpy as np


# Plot outputs
plt.scatter(X_test, y_test,  color='black') #plot scatters
plt.plot(X_test, y_pred, color='red', linewidth=2) #plot line

plt.xticks(())
plt.yticks(())

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM