# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt ## 設置字符集,防止中文亂碼 import matplotlib matplotlib.rcParams['font.sans-serif']=[u'simHei'] matplotlib.rcParams['axes.unicode_minus']=False # X爲披薩的直徑 X = np.array([[6],[8],[10],[14],[18]]).reshape(-1,1) # y是披薩的價格 y = [7,9,13,17.5,18] plt.figure() plt.title('披薩直徑和價格的關係') plt.xlabel("直徑") plt.ylabel("價格") plt.plot(X,y,'ro') plt.axis([0,25,0,25]) plt.grid(True) # 創建線性迴歸模型 from sklearn.linear_model import LinearRegression LR = LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False) #參數介紹 #fit_intercept:是否有截據,若是沒有則直線過原點。 #normalize:是否將數據歸一化。 #copy_X:默認爲True,當爲True時,X會被copied,不然X將會被覆寫。(這一參數的具體做用沒明白,求大神指教了) #n_jobs:默認值爲1。計算時使用的CPU核數。 LR.fit(X,y) # 畫出圖 # 輸出斜率 print(LR.coef_) # 輸出截距 print(LR.intercept_) xx=range(0,25) yy = LR.coef_*xx+LR.intercept_ plt.plot(xx,yy,'g') # 輸出RSS殘差平方和 print("RSS:%.2f" % np.mean((LR.predict(X)-y)**2)) # 預測一個直徑以前從未見過的披薩價格 test_pizza = np.array([[12]]) predicted_price = LR.predict(test_pizza)[0] print("預測直徑爲%d的披薩價格爲 $%f" % (12,predicted_price)) # 評價模型 # score能夠直接輸出R方 X_test = np.array([8,9,11,16,12]).reshape(-1,1) y_test = [11,8.5,15,18,11] r_squared = LR.score(X_test,y_test) print(r_squared)
print(LR.coef_) [0.9762931] print(LR.intercept_) 1.965517241379315 print("RSS:%.2f" % np.mean((LR.predict(X)-y)**2)) RSS:1.75 print("預測直徑爲%d的披薩價格爲 $%f" % (12,predicted_price)) 預測直徑爲12的披薩價格爲 $13.681034 print(r_squared) 0.6620052929422553