1. 程式人生 > >Day_2 簡單線性迴歸模型

Day_2 簡單線性迴歸模型

 

第一步:資料預處理

In [2]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
​
dataset = pd.read_csv('studentscores.csv')
X = dataset.iloc[:, : 1].values
Y = dataset.iloc[:, 1].values
​
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 1/4, random_state = 0)

第二步:訓練集使用簡單線性迴歸模型來訓練

In [3]:
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor = regressor.fit(X_train, Y_train)

第三步:預測結果

In [4]:
Y_pred = regressor.predict(X_test)
第四步:視覺化

訓練集結果視覺化

In [5]:

plt.scatter(X_train, Y_train, color = 'red')
plt.plot(X_train, regressor.predict(X_train),color = 'blue')
plt.show()

plt.scatter(X_test, Y_test, color = 'red')
plt.plot(X_test, regressor.predict(X_test),color = 'green')
plt.show()