1. 程式人生 > 其它 >python機器學習-泰坦尼克號決策樹

python機器學習-泰坦尼克號決策樹

案例:泰坦尼克號乘客生存預測

  • 泰坦尼克號資料

在泰坦尼克號和titanic2資料幀描述泰坦尼克號上的個別乘客的生存狀態。這裡使用的資料集是由各種研究人員開始的。其中包括許多研究人員建立的旅客名單,由Michael A. Findlay編輯。我們提取的資料集中的特徵是票的類別,存活,乘坐班,年齡,登陸,home.dest,房間,票,船和性別。

1、乘坐班是指乘客班(1,2,3),是社會經濟階層的代表。

2、其中age資料存在缺失。

分析

  • 選擇我們認為重要的幾個特徵 ['pclass', 'age', 'sex']
  • 填充缺失值
  • 特徵中出現類別符號,需要進行one-hot編碼處理(DictVectorizer)
    • x.to_dict(orient="records") 需要將陣列特徵轉換成字典資料
  • 資料集劃分
  • 決策樹分類預測
#泰坦尼克號決策樹
def titanic():
    #1.獲取資料
    data_titanic=pd.read_csv("titanic.csv")
    #2.獲取目標值與特徵值
    x=data_titanic[["pclass","age","sex"]]
    y=data_titanic["survived"]
    #3.資料處理
    #1).缺失值處理
    x["age"].fillna(x["age"].mean(),inplace=True)#填補處理dropna()刪除缺失值所在的行
    #2).轉換為字典
x=x.to_dict(orient="records") #4.劃分資料集 x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=22) #5.字典特徵抽取 transfer=DictVectorizer() x_train=transfer.fit_transform(x_train) x_test=transfer.transform(x_test) #6.決策樹預估器 estimator=DecisionTreeClassifier(criterion="
entropy")#criterion預設為gini係數,此處選擇的為資訊增益的熵 #max_depth:樹深的大小,random_state:隨機數種子 estimator.fit(x_train,y_train) #7.模型評估 y_predict=estimator.predict(x_test) print("y_predict:\n",y_predict) print("直接對比真實值和預測值:\n",y_test==y_predict) score=estimator.score(x_test,y_test) print("準確率為:\n",score) #8.決策樹視覺化 export_graphviz(estimator,out_file="titanic_tree.dot",feature_names=transfer.get_feature_names()) #使用隨機森林 estimator=RandomForestClassifier()