python - 为什么数据的变化不会改变情节线?

标签 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) 的不同结果>?

最佳答案

线性回归模型实际上只是学习一条直线。对于任何输入,它会将输出映射到该直线上的一个点。你得到的是同一条线,无论输入如何,你总是会在那条线上得到一个点!

在拟合后查看 regressor.intercept_regressor.coef,这将显示 y 轴上的截距(从该图中可能约为 36000),并且直线的梯度(大概是 10000?)。

关于python - 为什么数据的变化不会改变情节线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55782573/

相关文章:

python - "LookupError: Function ` __class__ ` does not exist."使用 tf.function 时

python - 在 scikit learn 中训练具有不同特征维度的逻辑回归模型

r - ANOVA类型错误

python - 为什么 BeautifulSoup (在 Python 脚本中)只返回 HTML 中的一些数字

python - 如何判断一个方法是否在父类中实现,如果是则使用该方法?

python - 将 bincount 应用于二维 numpy 数组的每一行

python - Tensorflow:从大于 2 GB 的 numpy 数组创建小批量

python - 使用二元分类器模型将数据分为 3 类

python - 二维点的最小二乘拟合不通过对称轴

python - 具有多项式特征和线性回归的管道 - 意外的结果