kaggle資料探勘——以Titanic為例介紹處理資料大致步驟
阿新 • • 發佈:2019-01-02
Titanic是kaggle上的一道just for fun的題,沒有獎金,但是資料整潔,拿來練手最好不過。
本文以 Titanic 的資料,使用較為簡單的決策樹,介紹處理資料大致過程、步驟
注意,本文的目的,在於幫助你入門資料探勘,熟悉處理資料步驟、流程
決策樹模型是一種簡單易用的非引數分類器。它不需要對資料有任何的先驗假設,計算速度較快,結果容易解釋,而且穩健性強,對噪聲資料和缺失資料不敏感。下面示範用kaggle競賽titanic中的資料集為做決策樹分類,目標變數為survive
讀取資料
import numpy as np
import pandas as pd
df = pd.read_csv('train.csv' , header=0)
資料整理
- 只取出三個自變數
- 將Age(年齡)缺失的資料補全
- 將Pclass變數轉變為三個 Summy 變數
- 將sex轉為0-1變數
subdf = df[['Pclass','Sex','Age']]
y = df.Survived
# sklearn中的Imputer也可以
age = subdf['Age'].fillna(value=subdf.Age.mean())
# sklearn OneHotEncoder也可以
pclass = pd.get_dummies(subdf['Pclass'],prefix='Pclass')
sex = (subdf['Sex' ]=='male').astype('int')
X = pd.concat([pclass,age,sex],axis=1)
X.head()
輸出下圖結果
建立模型
- 將資料切分為 train 和 test
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=33)
- 在測試集(test)上觀察決策樹表現
from sklearn import tree
clf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=3,min_samples_leaf=5)
clf = clf.fit(X_train,y_train)
print("準確率為:{:.2f}".format(clf.score(X_test,y_test)))
輸出結果如下
準確率為:0.83
- 觀察各變數的重要性
clf.feature_importances_
輸出如下
array([ 0.08398076, 0. , 0.23320717, 0.10534824, 0.57746383])
- 生成特徵圖
import matplotlib.pyplot as plt
feature_importance = clf.feature_importances_
important_features = X_train.columns.values[0::]
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)[::-1]
pos = np.arange(sorted_idx.shape[0]) + .5
plt.title('Feature Importance')
plt.barh(pos, feature_importance[sorted_idx[::-1]], color='r',align='center')
plt.yticks(pos, important_features)
plt.xlabel('Relative Importance')
plt.draw()
plt.show()
當然在得到重要的特徵後,我們就可以把不重要的特徵去掉了,以提高模型的訓練速度
最後是
- 使用交叉驗證來評估模型
from sklearn import cross_validation
scores1 = cross_validation.cross_val_score(clf, X, y, cv=10)
scores1
輸出結果如下:
array([ 0.82222222, 0.82222222, 0.7752809 , 0.87640449, 0.82022472,
0.76404494, 0.7752809 , 0.76404494, 0.83146067, 0.78409091])
- 使用更多指標來評估模型
from sklearn import metrics
def measure_performance(X,y,clf, show_accuracy=True,
show_classification_report=True,
show_confusion_matrix=True):
y_pred=clf.predict(X)
if show_accuracy:
print("Accuracy:{0:.3f}".format(metrics.accuracy_score(y,y_pred)),"\n")
if show_classification_report:
print("Classification report")
print(metrics.classification_report(y,y_pred),"\n")
if show_confusion_matrix:
print("Confusion matrix")
print(metrics.confusion_matrix(y,y_pred),"\n")
measure_performance(X_test,y_test,clf, show_classification_report=True, show_confusion_matrix=True)
輸出結果如下,可以看到 precision(精確度)recall(召回率)等更多特徵
Accuracy:0.834
Classification report
precision recall f1-score support
0 0.85 0.88 0.86 134
1 0.81 0.76 0.79 89
avg / total 0.83 0.83 0.83 223
Confusion matrix
[[118 16]
[ 21 68]]
與隨機森林進行比較
from sklearn.ensemble import RandomForestClassifier
clf2 = RandomForestClassifier(n_estimators=1000,random_state=33)
clf2 = clf2.fit(X_train,y_train)
scores2 = cross_validation.cross_val_score(clf2,X, y, cv=10)
clf2.feature_importances_
scores2.mean(), scores1.mean()
準確率輸出(這裡用的是10折交叉驗證後的平均值)
(0.81262938372488946, 0.80352769265690616)
可以看到隨機森林的準確要比決策樹高0.1左右
總結
經過上面介紹分析,我們走過了一個數據科學家在拿到資料到得出結論的所有步驟
- 讀入資料
- 資料清理
- 特徵工程
- 構建模型
- 模型評估
- 引數調整
- 模型比較
這篇文章重要的不是結果,而是幫助你瞭解處理資料大致過程、步驟
剩下的細節,就是你發揮自己的想象力,進行改進、創新了