第十三次作業——迴歸模型與房價預測
阿新 • • 發佈:2018-12-06
1. 匯入boston房價資料集
from sklearn.datasets import load_boston boston = load_boston() boston.keys()
print(boston.DESCR)
boston.data.shape #檢視資料個數 import pandas as pd #用pandas模型輸入資料 pd.DataFrame(boston.data)
2. 一元線性迴歸模型,建立一個變數與房價之間的預測模型,並圖形化顯示。
import matplotlib.pyplot as plt x= boston.data[:,5] #第五個因素與房價的關係 y = boston.target plt.figure(figsize=(10,6)) #圖形大小 plt.scatter(x,y) #散點圖 plt.plot(x,9*x-20,'r') #一元線性迴歸線,斜率 plt.show() x.shape
3. 多元線性迴歸模型,建立13個變數與房價之間的預測模型,並檢測模型好壞,並圖形化顯示檢查結果。
import matplotlib.pyplot as plt x = boston.data[:,12].reshape(-1,1) y= boston.target plt.figure(figsize=(10,6)) plt.scatter(x,y) from sklearn.linear_model import LinearRegression lineR = LinearRegression() lineR.fit(x,y) y_pred = lineR.predict(x) plt.plot(x,y_pred,'r') print(lineR.coef_,lineR.intercept_) plt.show() #多元線性迴歸 from sklearn.linear_model import LinearRegression lr= LinearRegression() lr.fit(boston.data,y) w = lr.coef_ print(w)
4. 一元多項式迴歸模型,建立一個變數與房價之間的預測模型,並圖形化顯示。
from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=2) poly.fit_transform(x) lrp = LinearRegression() lineR.fit(x,y) y_pred = lineR.predict(x) plt.plot(x,y_pred) from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=2) x_poly = poly.fit_transform(x) lrp = LinearRegression() lrp.fit(x_poly,y) y_pred = lineR.predict(x) plt.plot(x,y_pred) x_poly from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=2) x_poly = poly.fit_transform(x) lrp = LinearRegression() lrp.fit(x_poly,y) y_poly_pred = lrp.predict(x_poly) plt.scatter(x,y) plt.scatter(x,y_pred) plt.scatter(x,y_poly_pred) plt.show() from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=2) x_poly = poly.fit_transform(x) lp = LinearRegression() lp.fit(x_poly,y) y_poly_pred = lp.predict(x_poly) plt.scatter(x,y) plt.plot(x,y_pred,'r') plt.scatter(x,y_poly_pred,c='b') plt.show()