决策树案例:泰坦尼克号生存者预测

这篇博客介绍了如何使用Python的pandas、sklearn库对数据进行预处理,包括删除无关列、填充缺失值、转换类别数据。接着,通过交叉验证评估决策树模型的性能,并使用GridSearchCV进行参数调优。最后,通过绘制曲线找到最优的最大深度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据预处理

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
from sklearn.model_selection import GridSearchCV # 超参数自动搜索模块

data = pd.read_csv('mytrain.csv')

data.info() # 显示表格信息,判断含有缺失值和非数字的列
# 数据预处理:
data.drop(['Name','Ticket','Cabin','Unnamed: 12'],inplace=True,axis=1) # inplace=True用新表覆盖原表
data['Age']=data['Age'].fillna(data['Age'].mean()) # 处理缺失值,用平均值填补
data=data.dropna() # 删除所有含有缺失值的行

data['Embarked'].unique().tolist() # # unique()取出所有值并通过删除重复部分进行压缩,tolist()将数据以列表的形式呈现

import numpy as np
data['Embarked']=data['Embarked'].apply(lambda x:labels.index(x))  # 将数据用索引数字代替,相同的数据用同一数字

data['Sex']=(data['Sex'] == 'male').astype('int') # 只有两种数据时,用布尔转化为整数的方法

调参

x= data.iloc[:,data.columns !='Survived'] # 数据
# y= data.iloc[:,data.columns =='Survived'] # 最好不要二次切,否则会报错:too many indices for array
y=data['Survived']  # 标签
from sklearn.model_selection import train_test_split
Xtrain,Xtest,Ytrain,Ytest=train_test_split(x,y,test_size=0.3)

for i in [Xtrain,Xtest,Ytrain,Ytest]:
    i.index = range(i.shape[0]) # 将数据集的索引重新排序,从0开始
    
clf = DecisionTreeClassifier(random_state = 25)
clf = clf.fit(Xtrain,Ytrain)
score = clf.score(Xtest,Ytest)
score # 测试集分数

from sklearn.model_selection import cross_val_score  
clf = DecisionTreeClassifier(random_state = 25)
score = cross_val_score(clf,x,y,cv=10).mean()
score
# 应用交叉验证后,测试集的分数依然不理想

# 参数曲线观察
tr = []
te = []
for i in range(10):
    clf = DecisionTreeClassifier(random_state = 25
                                ,max_depth=i+1
                                ,criterion='entropy'
                                )
    clf = clf.fit(Xtrain,Ytrain)
    score_tr = clf.score(Xtrain,Ytrain)
    score_te = cross_val_score(clf,x,y,cv=10).mean()
    tr.append(score_tr)
    te.append(score_te)
print(max(te))
plt.plot(range(1,11),tr,color='red',label='train')
plt.plot(range(1,11),te,color='blue',label='test')
plt.xticks(range(1,11))  # 设置横坐标显示1-10的所有整数值
plt.legend()
plt.show()
# 当max_depth=3时,测试集分数最大

网格搜索

import numpy as np
gini_threholds = np.linspace(0,0.5,50)  # 从0-0.5之间取50个数字,首尾都包含,间距不定

parameters = {'criterion':('gini','entropy') #指定了切分质量的评价准则:gini;熵
             ,'splitter':('best','random')  #指定了在每个节点切分的策略
             ,'max_depth':[*range(1,10)]  # [*range(1,10)]以列表的形式呈现
             ,'min_samples_leaf':[*range(1,50,5)] # 指定了每个叶子节点包含的最少样本数
             ,'min_impurity_decrease':[*np.linspace(0,0.5,50)] # 限制信息增益的大小,如果节点的分裂导致不纯度的减少(分裂后样本比分裂前更加纯净)大于或等于min_impurity_decrease,则分裂该节点
             }
clf = DecisionTreeClassifier(random_state = 25)
GS = GridSearchCV(clf,parameters,cv=10)   
GS = GS.fit(Xtrain,Ytrain)    


GS.best_params_ # 从我们输入的参数和参数取值的列表中,返回最佳组合
GS.best_score_  # 网格搜索后的模型的评判标准
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值