为什么数据更改不会更改绘图线?

时间:2019-04-21 12:07:27

标签: python machine-learning linear-regression

我是机器学习的新手,正在建立一个简单的线性回归模型。该模型的变量如下:

X_train = [3, 5, 3, 4, 8, 7, 1, 10, 3, 2, 6, 6, 4, 9, 2, 1, 7, 5, 4, 8]
X_test = [2, 10, 4, 4, 10, 9, 10, 4, 5, 8]
Y_train = [56642, 66029, 64445, 61111, 113812, 91738, 46205, 121872, 60150, 39891, 81363, 93940, 57189, 54445, 105582, 43525, 39343, 98273, 67938, 56957]
Y_test = [37731, 122391, 57081, 63218, 116969, 109431, 112635, 55794, 83088, 101302]

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)


#fitting simple linear regression on training sets
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

#predicting the test set results
y_pred = np.array(regressor.predict(X_test))

这是我绘制图形的代码:

#visualizing data for the test set
plt.scatter(X_test, y_test, color = 'red')

#Method 1: Using regressor.predict(X_train)
plt.plot(X_train,regressor.predict(X_train), color = 'green')

#Method 2: Using regressor.predict(X_test)
plt.plot(X_test, regressor.predict(X_test), color='yellow')

plt.title('Experience v/s Salary')
plt.xlabel('Experience')
plt.ylabel('Salary')
plt.show()

这是我的图表的图像:

Image for the question

为什么我在plt.plot(X_train,regressor.predict(X_train), color = 'green')plt.plot(X_test, regressor.predict(X_test), color='yellow')上得到不同的结果,但对于regressor.predict(X_train)regressor.predict(X_test)却得到相同的回归线?

2 个答案:

答案 0 :(得分:0)

LinearRegression模型实际上只是学习一条直线。对于任何输入,它将输出映射到该直线上的一个点。无论输入什么,您都会得到一条直线,您将始终在该直线上得到一个点!

拟合后看看jeevan<script>alert(“I won.”)</script>regressor.intercept_,这将显示y轴上的截距(该图可能在36000左右),以及直线的斜率(也许是10000)? )。

答案 1 :(得分:0)

因为我们通常train model来训练数据。和model learns中的train data only,我们假设test datasample,仅与train data非常相似。然后在其上应用predict

在您的情况下,只有一个模型regressor.fit(X_train, y_train),它有其interceptslope并且是固定的。 (简单地说,有一条线不会改变,它只能向其方向扩展,即使随机的未知样本也会形成一条与您的黄线和绿线重叠的线)