知識篇——sklearn決策樹分類器使用(網(wǎng)格搜索+交叉驗證)

使用sklearn的DecisionTreeClassifier解決分類問題實例。

數(shù)據(jù)集描述

數(shù)據(jù)集存放在一個csv文件中商膊,其中11列特征變量伏伐,1列目標(biāo)變量。特征變量的類型有數(shù)字類型和字符串類型晕拆。

加載數(shù)據(jù)

from sklearn import tree
from sklearn.model_selection import train_test_split
import pandas as pandas
in_file = 'titanic_data.csv'
full_data = pd.read_csv(in_file)

處理數(shù)據(jù)

1藐翎、剔除Nan的數(shù)據(jù)

full_data = full_data.dropna(axis=0)

2、拆分特征變量和目標(biāo)變量

out = full_data['Survived']
features = full_data.drop('Survived', axis = 1)

3实幕、將特征變量中的字符串類型轉(zhuǎn)成數(shù)字類型

features = pandas.get_dummies(features)

拆分訓(xùn)練集和測試集

X_train, X_test, y_train, y_test = train_test_split(features, out, test_size = 0.2, random_state = 0)
# 顯示切分的結(jié)果
print "Training set has {} samples.".format(X_train.shape[0])
print "Testing set has {} samples.".format(X_test.shape[0])

定義評價指標(biāo)

def accuracy_score(truth, pred):
    """ Returns accuracy score for input truth and predictions. """
    
    # Ensure that the number of predictions matches number of outcomes
    # 確保預(yù)測的數(shù)量與結(jié)果的數(shù)量一致
    if len(truth) == len(pred): 
        
        # Calculate and return the accuracy as a percent
        # 計算預(yù)測準(zhǔn)確率(百分比)
        # 用bool的平均數(shù)算百分比
        return(truth == pred).mean()*100
    
    else:
        return 0

建模

用兩種方式吝镣,一種是用網(wǎng)格搜索和交叉驗證找決策樹的最優(yōu)參數(shù),創(chuàng)建有最優(yōu)參數(shù)的決策樹昆庇,一種是默認(rèn)決策樹

創(chuàng)建決策樹,用網(wǎng)格搜索和交叉驗證找最優(yōu)參數(shù)并擬合數(shù)據(jù)

from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold
from sklearn.metrics import make_scorer
from sklearn.tree import DecisionTreeClassifier
def fit_model_k_fold(X, y):
    """ Performs grid search over the 'max_depth' parameter for a 
        decision tree regressor trained on the input data [X, y]. """
    
    # Create cross-validation sets from the training data
    # cv_sets = ShuffleSplit(n_splits = 10, test_size = 0.20, random_state = 0)
    k_fold = KFold(n_splits=10)
    
    #  Create a decision tree clf object
    clf = DecisionTreeClassifier(random_state=80)

    params = {'max_depth':range(1,21),'criterion':np.array(['entropy','gini'])}

    # Transform 'accuracy_score' into a scoring function using 'make_scorer' 
    scoring_fnc = make_scorer(accuracy_score)

    # Create the grid search object
    grid = GridSearchCV(clf, param_grid=params,scoring=scoring_fnc,cv=k_fold)

    # Fit the grid search object to the data to compute the optimal model
    grid = grid.fit(X, y)

    # Return the optimal model after fitting the data
    return grid.best_estimator_

查看最優(yōu)參數(shù)

print "k_fold Parameter 'max_depth' is {} for the optimal model.".format(clf.get_params()['max_depth'])
print "k_fold Parameter 'criterion' is {} for the optimal model.".format(clf.get_params()['criterion'])

創(chuàng)建默認(rèn)參數(shù)的決策樹

def predict_4(X, Y):
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(X, Y)
    return clf

預(yù)測

clf = fit_model_k_fold(X_train, y_train)

繪制決策樹

from IPython.display import Image  
import pydotplus
dot_data = tree.export_graphviz(clf, out_file=None,
                         class_names=['0','1'],  
                         filled=True, rounded=True,  
                         special_characters=True)  
graph = pydotplus.graph_from_dot_data(dot_data)  
Image(graph.create_png()) 
決策樹

以上內(nèi)容來自822實驗室2017年5月7日17:30第二次知識分享活動:Titanic幸存者預(yù)測末贾。
我們的822,我們的青春
歡迎所有熱愛知識熱愛生活的朋友和822實驗室一起成長整吆,吃喝玩樂拱撵,享受知識。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末表蝙,一起剝皮案震驚了整個濱河市拴测,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌府蛇,老刑警劉巖集索,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異汇跨,居然都是意外死亡务荆,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進(jìn)店門扰法,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蛹含,“玉大人,你說我怎么就攤上這事塞颁。” “怎么了?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵祠锣,是天一觀的道長酷窥。 經(jīng)常有香客問我,道長伴网,這世上最難降的妖魔是什么蓬推? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮澡腾,結(jié)果婚禮上沸伏,老公的妹妹穿的比我還像新娘。我一直安慰自己动分,他們只是感情好毅糟,可當(dāng)我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著澜公,像睡著了一般姆另。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上坟乾,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天迹辐,我揣著相機(jī)與錄音,去河邊找鬼甚侣。 笑死明吩,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的殷费。 我是一名探鬼主播印荔,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼宗兼!你這毒婦竟也來了躏鱼?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤殷绍,失蹤者是張志新(化名)和其女友劉穎染苛,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體主到,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡茶行,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了登钥。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片畔师。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖牧牢,靈堂內(nèi)的尸體忽然破棺而出看锉,到底是詐尸還是另有隱情姿锭,我是刑警寧澤,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布伯铣,位于F島的核電站呻此,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏腔寡。R本人自食惡果不足惜焚鲜,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望放前。 院中可真熱鬧忿磅,春花似錦、人聲如沸凭语。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽叽粹。三九已至览效,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間虫几,已是汗流浹背锤灿。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留辆脸,地道東北人但校。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像啡氢,于是被迫代替她去往敵國和親状囱。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容