簡介
線性迴歸:根據數據,確定兩種或兩種以上變量間相互依賴的定量關係
評價曲線的擬合效果使用均方誤差和R方值進行擬合質量評估
R方值 \(\left(R^{2}\right)\) :
MSE越接近0越好R方值越接近1越好。
對於離散數據點。
x | y |
---|---|
1 | 7 |
2 | 9 |
3 | 11 |
4 | 13 |
5 | 15 |
進行機器學習線性迴歸操作
code
import pandas as pd
data = pd.read_csv('generated_data.csv')
data.head()
x = data.loc[:,'x']
y = data.loc[:,'y']
print(x,y)
from matplotlib import pyplot as plt
plt.figure(figsize=(10,10))
plt.scatter(x,y)
plt.show()
from sklearn.linear_model import LinearRegression
lr_model = LinearRegression()
import numpy as np
x = np.array(x)
x = x.reshape(-1,1)
y = np.array(y)
y = y.reshape(-1,1)
print(x,y)
lr_model.fit(x,y)
y_predict = lr_model.predict(x)
print(y_predict)
y_3 = lr_model.predict([[3.5]])
print(y_3)
from sklearn.metrics import mean_squared_error,r2_score
MSE = mean_squared_error(y,y_predict)
R2 = r2_score(y,y_predict)
print(MSE,R2)
plt.figure()
plt.scatter(y,y_predict)
plt.show()