目录
一、数据预览
1.Data.head()
2. Class分布预览
1.3 其他
- 无缺失值
- class 名称是
'cand_pty_affiliation '
1.4 问题
- 将class值从REP、DEM变成0,1
- 要进行one-hot变换
二、数据预处理
2.1 将class值从REP、DEM变成0,1
data['cand_pty_affiliation'] = data[['cand_pty_affiliation']].replace({
'REP':1,'DEM':0})
2.2 one-hot变换
首先将属性和class分离开
X = data.drop(['cand_pty_affiliation'],axis=1)
y = data['cand_pty_affiliation']
再进行one-hot变换,转成稀疏格式
X = pd.get_dummies(X,sparse=True)
2.3 测试集、训练集分离
from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.4, random_state=33)
因为数据有点多,训练集就取60%,方便计算
三、模型构建
3.1 随机森林
不断地用Grid SearchCV调试参数
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
parameters = {
'max_depth':np.arange(14,18),'min_samples_split':np.arange(5,8)}
clf = GridSearchCV(estimator=RandomForestClassifier(n_estimators=186,random_state=33,n_jobs=-1),param_grid=parameters,cv=5,n_jobs=-1,scoring='roc_auc')
clf.fit(train_x,train_y)
print(clf.best_score_)
print(clf