分類器:
隨機(jī)森林分類器(RandomForest):包含多個(gè)決策樹的分類器,每一個(gè)子分類器都是一顆CART分類器。
RandomForestClassifier()

隨即森林參數(shù)含義.png
GridSearchTV工具對模型參數(shù)進(jìn)行調(diào)優(yōu):
它是python的自動(dòng)參數(shù)搜索模塊,只要給它參數(shù)取值范圍,它可以自動(dòng)跑一邊所有的參數(shù),并且告訴我們最優(yōu)參數(shù)是什么。
代碼:
from sklearn.model_selection import GridSearchCV

參數(shù)含義.png
使用管道機(jī)制流水線線作業(yè):
當(dāng)模型需要,數(shù)據(jù)規(guī)范化處理、PCA方法對數(shù)據(jù)進(jìn)行數(shù)據(jù)降維,等步驟時(shí),便可以穿件Pipeline流水線。
from sklearn.model_selection import GridSearchCV
pipeline = Pipeline([
('scaler', StandardScaler()),
('pca', PCA()),
('randomforestclassifier', RandomForestClassifier())
])
代碼步驟:
1、數(shù)據(jù)導(dǎo)入與數(shù)據(jù)探索
2、數(shù)據(jù)清洗、特征選擇、訓(xùn)練集與測試集選擇
3、構(gòu)造四個(gè)分類器、四個(gè)名稱、四個(gè)參數(shù)及取值范圍(字典或列表形式),以列表的形式存在
4、函數(shù),帶入自動(dòng)篩選函數(shù),參數(shù)為管道執(zhí)行順序,測試訓(xùn)練值,以及變化參數(shù)
5、用for 循環(huán)解封分類器、參數(shù)……列表,并管道執(zhí)行數(shù)據(jù)標(biāo)準(zhǔn)化,分類器創(chuàng)建
# 查看信用卡違約率
import pandas as pd
from sklearn.model_selection import learning_curve,train_test_split,GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import seaborn as sns
#1、數(shù)據(jù)探索
data=pd.read_csv('E:/數(shù)據(jù)學(xué)習(xí)網(wǎng)站/credit_default-master/UCI_Credit_Card.csv')
# print(data.head(5))
# print(data.describe())
# print(data.shape)
next_month=data['default.payment.next.month'].value_counts()#統(tǒng)計(jì)個(gè)數(shù)
# print(next_month)
df=pd.DataFrame({'default.payment.next.month':next_month.index,'values':next_month.values})#將統(tǒng)計(jì)數(shù)據(jù)設(shè)置成pandas格式
# print(df)
# 可視化
# plt.rcParams['font.sans-serif']=['SimHei']#用來正常顯示中文
# plt.figure(figsize=(6,6))#圖形大小
# plt.title('信用卡違約率客戶\n(違約:1,守約:0)')#圖形標(biāo)題
# sns.set_color_codes('pastel')#圖形顏色
# sns.barplot(x='default.payment.next.month',y='values',data=df)
# locs,labels=plt.xticks()
# plt.show()
#2、數(shù)據(jù)清洗、特征選擇
data.drop(['ID'],inplace=True,axis=1)#除去沒用的ID
target=data['default.payment.next.month'].values#結(jié)果
columns=data.columns.tolist()
columns.remove('default.payment.next.month')#移除結(jié)果欄
features=data[columns].values
train_x,test_x,train_y,test_y=train_test_split(features,target,test_size=0.3,stratify=target,random_state=1)#一般來說0.3用來測試
# 3、構(gòu)造各種分類器,四個(gè)分類器,以列表的形式存在
classifiers=[
SVC(random_state=1,kernel='rbf'),
DecisionTreeClassifier(random_state=1,criterion='gini'),
RandomForestClassifier(random_state=1,criterion='gini'),
KNeighborsClassifier(metric='minkowski')
]
# 4、分類器名稱
classifier_names=[
'svc',
'decisiontreeclassifier',
'randomforestclassifier',
'kneighborsclassifier'
]
# 5、分類器參數(shù)
classifier_param_grid = [
{'svc__C': [1], 'svc__gamma': [0.01]},
{'decisiontreeclassifier__max_depth': [6, 9, 11]},
{'randomforestclassifier__n_estimators': [3, 5, 6]},
{'kneighborsclassifier__n_neighbors': [4, 6, 8]},
]
#6、函數(shù),帶入自動(dòng)篩選函數(shù),參數(shù)為管道執(zhí)行順序,測試訓(xùn)練值,以及變化參數(shù)
def GridSearchCV_work(pipeline,train_x,train_y,test_x,test_y,param_grid,score='accuracy'):
response={}
gridsearch=GridSearchCV(estimator=pipeline,param_grid=param_grid,scoring=score)
gridsearch.fit(train_x,train_y)
print('最優(yōu)參數(shù)為:',gridsearch.best_params_)
print('最優(yōu)分?jǐn)?shù)為:',gridsearch.best_score_)
predict_y=gridsearch.predict(test_x)
print('準(zhǔn)確率為:',accuracy_score(test_y,predict_y))
response['predict_y']=predict_y
response['accuracy_score']=accuracy_score(test_y,predict_y)
return response
#7、用for 循環(huán)解封分類器、參數(shù)……列表,并管道執(zhí)行數(shù)據(jù)標(biāo)準(zhǔn)化,分類器創(chuàng)建
for model,model_name,model_param_grid in zip(classifiers,classifier_names,classifier_param_grid):
pipeline=Pipeline([
('scaler',StandardScaler()),
(model_name,model)
])
result=GridSearchCV_work(pipeline,train_x,train_y,test_x,test_y,model_param_grid,score='accuracy')
結(jié)果:
最優(yōu)參數(shù)為: {'svc__C': 1, 'svc__gamma': 0.01}
最優(yōu)分?jǐn)?shù)為: 0.8173809523809524
準(zhǔn)確率為: 0.8172222222222222
最優(yōu)參數(shù)為: {'decisiontreeclassifier__max_depth': 6}
最優(yōu)分?jǐn)?shù)為: 0.8186190476190476
準(zhǔn)確率為: 0.8113333333333334
最優(yōu)參數(shù)為: {'randomforestclassifier__n_estimators': 6}
最優(yōu)分?jǐn)?shù)為: 0.7998095238095239
準(zhǔn)確率為: 0.7994444444444444
最優(yōu)參數(shù)為: {'kneighborsclassifier__n_neighbors': 8}
最優(yōu)分?jǐn)?shù)為: 0.804047619047619
準(zhǔn)確率為: 0.8035555555555556
可以看出,各個(gè)分類器的最優(yōu)結(jié)果和最優(yōu)的參數(shù)。
數(shù)據(jù)來源:
我們現(xiàn)在來做一個(gè)信用卡違約率的項(xiàng)目,這個(gè)數(shù)據(jù)集你可以從 GitHub 上下載:https://github.com/cystanford/credit_default。