分析:女性身高與體重的關系
該數據集源自The World Almanac and Book of Facts(1975)
給出了年齡在30-39歲之間的15名女性的身高和體重信息
1.線性回歸
# packages import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import statsmodels.api as sm
1.1數據處理
data = pd.read_csv("women.csv",index_col = 0) X = data["height"] X = sm.add_constant(X) y = data["weight"] data.describe() #數據描述性分析
plt.scatter(data["height"],data["weight"]) plt.show()
1.2模型擬合
model1 = sm.OLS(y,X) #最小二成模型 result = model1.fit() #訓練模型 print(result.summary()) #輸出訓練結果
#單獨調用回歸結果的參數命令: result.params #回歸系數 result.rsquared #回歸擬合優度R result.f_pvalue #F統計量p值 sm.stats.stattools.durbin_watson(result.resid) #dw統計量,檢驗殘差自相關性 sm.stats.stattools.jarque_bera(result.resid) #jb統計量,檢驗殘差是否服從正態分布(JB,JBp值,偏度,峰度)
1.3模型預測
y_pre = result.predict() y_pre
1.4模型評價
#結果可視化 plt.rcParams['font.family']="simHei" #漢字顯示 plt.plot(data["height"], data["weight"],"o") plt.plot(data["height"], y_pre) plt.title('女性體重與身高的線性回歸分析')
從上圖來看,簡單線性回歸的效果並不好,我們采取多項式回歸
2.多項式回歸
2.1數據處理
data = pd.read_csv("women.csv",index_col = 0) X = data["height"] y = data["weight"] X = np.column_stack((X,np.power(X,2),np.power(X,3))) #構造三階多項式 X = sm.add_constant(X) #添加截距項 X
2.2模型擬合
model2 = sm.OLS(y,X) result = model2.fit() print(result.summary())
2.3模型預測
y_pre = result.predict() y_pre
2.4模型評價
#結果可視化 plt.rcParams['font.family']="simHei" #漢字顯示 plt.plot(data["height"], data["weight"],"o") plt.plot(data["height"], y_pre) plt.title('女性體重與身高的線性回歸分析')