線性迴歸算法

以sklearn.datasets模塊中的經典數據load_boston(波士頓房價)爲例,實現線性迴歸算法

代碼:

from sklearn.datasets import load_boston  # 經典數據
from sklearn.linear_model import LinearRegression # 線性模塊,迴歸線性模型
from sklearn.model_selection import train_test_split # 訓練集與測試集分割模型
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 記載數據
boston = load_boston()
print(type(boston))
print(list(boston))
x = boston['data']  # 數據的特徵值
y = boston['target'] # 標籤值
names = boston['feature_names'] # 特徵名稱
print(names)
print(type(names))


df = pd.DataFrame(x,columns=names,index=range(len(y)))
pf = pd.DataFrame(y,columns=['label'],index=range(len(y)))
print(df.shape)
print(pd.concat((df, pf), axis=1).shape)
data = pd.concat((df, pf), axis=1)
# data.to_excel('boston.xls')
# 分割數據
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2)
# 構建迴歸模型
clf = LinearRegression().fit(x_train,y_train)
print('截距是',clf.intercept_)
print('迴歸係數是',clf.coef_)

# 預測
y_pred = clf.predict(x_test)
print('預測值是',y_pred[:20])
print('實際值是',y_test[:20])
# 將預測標籤與真實標籤拼接到一起,稱爲一個達標
print(np.concatenate((y_pred.reshape(-1,1), y_test.reshape(-1,1)),axis=1).shape)
result = np.concatenate((y_pred.reshape(-1,1), y_test.reshape(-1,1)),axis=1)
print(result)

x = range(1,103)
plt.figure()
plt.rcParams['font.sans-serif'] = 'SimHei' # 仿宋字體
plt.rcParams['axes.unicode_minus'] = False # 設置正常顯示符號
plt.plot(x,result[:,0],marker='*')
plt.plot(x,result[:,1],marker='o')
plt.legend(['房價預測值','房價真實值'])
plt.show()

實現效果:

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章