上周完成了回歸分析預測波士頓房價的工作,因數據太少,預測準確度波動很大??偨Y回歸分析的流程,整理放在這個文章里。
一個需要明確的點是回歸分析所研究的統計關系,是在進行大量的觀測或試驗后建立起的經驗關系,并非一定是因果關系。
基本概念
explanatory/independent/predictor variables, risk factor, feature都是自變量x。
explained/dependent/predicted/responding/responding/experimental/outcome variables, label都是對象y。
數據來源
Python的Sklearn?module中的boston?house?price數據,共506組房屋數據,每組數據13個features。對象y是房價中間值median?value。屬性信息如下:
- CRIM per capita crime rate by town
- ZN? ? ? proportion of residential land zoned for lots over 25,000 sq.ft.
- INDUS? ? proportion of non-retail business acres per town
- CHAS? ? Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
- NOX? ? ? nitric oxides concentration (parts per 10 million)
- RM? ? ? average number of rooms per dwelling
- AGE? ? ? proportion of owner-occupied units built prior to 1940
- DIS? ? ? weighted distances to five Boston employment centres
- RAD? ? ? index of accessibility to radial highways
- TAX? ? ? full-value property-tax rate per $10,000
- PTRATIO? pupil-teacher ratio by town
- B? ? ? ? 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
- LSTAT? ? % lower status of the population
回歸分析流程:
1?根據觀察、統計或者業務需求,確定自變量x和對象y之間的關系式,也就是回歸方程,并對方程的可信度進行統計檢驗;
2?對自變量x做顯著性檢驗,判斷哪些對于對象y是有影響的因子。
3?利用所建立的回歸方程來預測未來時刻的預報對象做出預測,并給出可信度區間。
Data preprocessing
Boston?house?price的數據比較規范,但各feature的數據各自尺度不同,需要做data?scaling。具體scaling需要哪些準備或者明確的標準,我還需要在以后的研究中深入研究下。這次的數據,用了sklearn里面的sklearn.preprocessing.scale指令,默認是做standardisation的,也就是某個feature的值減去期望再初standard?deviation。如果數據是right/left skewed,則可能需要做logarithmic transformation,但做log的前提是數據要大于0.
指令:
tra_data = pd.DataFrame(sklearn.preprocessing.scale(ori_data.data[tra_index]),columns=ori_data.feature_names)[features_selected]
X-validation
隨機選80%的數據作為training?set,剩余數據作為test?set。
回歸
回歸采用線性回歸,Lasso回歸和嶺回歸三種方法,對比效果。使用方式一樣
from sklearn.linear_model import LinearRegression,Lasso,Ridge
lasso = Lasso(alpha=alpha_for_lasso)
lasso.fit(tra_data,tra_label)
三步就訓練出了Lasso模型,再使用pred_label_lasso = lasso.predict(test_data)就會得到預測的label值。
性能檢測
不同于分類,回歸分析方法以MSE為主要measurement?metrics,
mse_lasso = sklearn.metrics.mean_squared_error(test_label,pred_label_lasso)
MSE表示均方誤差,越小越好。
另外R2指標展示的是模型(或回歸參數w)對數據的擬合程度,這個數值在0到1之間,越大越好。
from sklearn.metrics import r2_score as r2
r2_lasso = r2(test_label,pred_label_lasso)
feature對label的顯著性和feature間的multi collinearity
最簡單的方法是計算features和label的相關性和features間彼此的相關性。
可使用F檢驗計算各feature間的F值和p值。
可使用recursive?feature?elimination RFE遞歸特征消除來選擇feature。反復構建模型(SVM, Linear regression and etc.)選出最好/壞的特征(根據系數大小),并排除,再對剩余features重復這個過程。
Lasso回歸可自動使非重要feature的權重變為0,用于feature?selection和避免multi?collinearity都是可行的。
如何處理features比instance個數多的情況
feature多于instance的潛在風險是overfitting。在隨機森林中,feature可以隨機選取。Lasso回歸自動執行了feature?selection,可以用于處理這種情況。另外檢查feature間的相關性,剔除冗余feature也可行。
更多筆記見筆記本