員工流動(dòng)分析和預(yù)測(cè)
公司員工,是一家公司成長(zhǎng)和發(fā)展的關(guān)鍵要素之一。留不住優(yōu)秀的員工,也就難以打造出卓越的公司。很多公司,比方說,惠普公司,IBM公司等,已經(jīng)采用數(shù)據(jù)科學(xué)的手段,對(duì)內(nèi)部員工的流動(dòng)做分析和預(yù)測(cè),并且進(jìn)行提前的干預(yù),以最小化員工流動(dòng)所帶來的的影響。
本文是關(guān)于員工流動(dòng)分析和預(yù)測(cè)的案例,通過閱讀,可以得到:
需要解決什么問題?
描述員工流動(dòng)的特征或者標(biāo)簽有哪些?
對(duì)于采集的數(shù)據(jù)集如何做準(zhǔn)備工作?
如何對(duì)整理好的數(shù)據(jù)做分析和建模?
模型的效果如何評(píng)估?
模型的結(jié)果如何應(yīng)用?
一、業(yè)務(wù)理解,
要解決什么問題?
根據(jù)公司員工的數(shù)據(jù),分析和挖掘潛在流動(dòng)的員工白名單,輸出給人力資源部門,指導(dǎo)他們進(jìn)行提前干預(yù)和挽留,以減少公司人員流動(dòng)所帶來的的損失和影響。
二、數(shù)據(jù)理解,
數(shù)據(jù)的畫像問題?
本案例的數(shù)據(jù)集來自Kaggle平臺(tái)提供一份公司人員流動(dòng)數(shù)據(jù)。這份數(shù)據(jù)集包括18列,用于記錄公司員工的相關(guān)信息。目標(biāo)變量是status記錄了兩種狀態(tài),取值是ACTIVE和TERMINATED。其它列可以從后面代碼里面了解。
1、導(dǎo)入Python庫
import?random
import?time?as?time
from?datetime?import?timedelta
import?pandas?as?pd
import?numpy?as?np
import?matplotlib.pyplot?as?plt
import?seaborn?as?sns
from?sklearn?import?model_selection
from?sklearn.preprocessing?import?MinMaxScaler
from?sklearn.preprocessing?import?StandardScaler
from?sklearn.preprocessing?import?Normalizer
from?sklearn.pipeline?import?Pipeline
from?sklearn.linear_model?import?LogisticRegression
from?sklearn.tree?import?DecisionTreeClassifier
from?sklearn.neighbors?import?KNeighborsClassifier
from?sklearn.metrics?import?classification_report
from?sklearn.metrics?import?confusion_matrix
from?sklearn.metrics?import?accuracy_score
from?sklearn.exceptions?import?DataConversionWarning
import?warnings
def?disable_DataConversionWarning():
????warnings.filterwarnings(action='ignore',?category=DataConversionWarning)
????
def?disable_FutureWarning():
????warnings.filterwarnings(action='ignore',?category=FutureWarning)
def?enable_All_Warning():
????warnings.simplefilter('always')
????
get_ipython().run_line_magic('matplotlib',?'inline')
2、導(dǎo)入數(shù)據(jù)集
file?=?'./datasets/MFG10YearTerminationData.csv'
data?=?pd.read_csv(filepath_or_buffer=file,?header=0,?sep=',')
print('數(shù)據(jù)檢視:輸出數(shù)據(jù)集前5行...')
data.head(5)
3、元數(shù)據(jù)理解
print('樣本數(shù):',?data.shape[0])
print('變量數(shù):',?data.shape[1])
print('變量的數(shù)據(jù)類型:')
print(data.dtypes)
4、數(shù)值型變量描述性統(tǒng)計(jì)分析
print('數(shù)值類型變量的描述性統(tǒng)計(jì)分析:')
data.describe().T

三、數(shù)據(jù)準(zhǔn)備,
數(shù)據(jù)如何整理好?
這份數(shù)據(jù)集有很多變量的取值是文本信息,為了能夠使用它做分析和建模。我們需要做編碼處理。這里采用了一種簡(jiǎn)單的處理策略,即基于領(lǐng)域知識(shí)把一些類別變量進(jìn)行標(biāo)簽編碼。同時(shí),刪除ID列,對(duì)目標(biāo)變量列也進(jìn)行編碼處理。對(duì)整理好的數(shù)據(jù)集,進(jìn)行可視化分析,以加深對(duì)數(shù)據(jù)進(jìn)一步認(rèn)知和理解。
5、類別變量的標(biāo)簽編碼
第一步:把所需的對(duì)象變量強(qiáng)制轉(zhuǎn)換為類別變量;第二步:對(duì)類別變量進(jìn)行標(biāo)簽編碼映射,從而轉(zhuǎn)換為數(shù)值變量。
#?第一步:對(duì)象轉(zhuǎn)換為類別變量
data["city_name"]?=?data["city_name"].astype('category')
data["department_name"]?=?data["department_name"].astype('category')
data["job_title"]?=?data["job_title"].astype('category')
data["gender_short"]?=?data["gender_short"].astype('category')
data["termreason_desc"]?=?data["termreason_desc"].astype('category')
data["termtype_desc"]?=?data["termtype_desc"].astype('category')
data["BUSINESS_UNIT"]?=?data["BUSINESS_UNIT"].astype('category')
#?第二步:類別變量做標(biāo)簽編碼
data["city_name_NUMERIC"]?=?data["city_name"].cat.codes
data["department_name_NUMERIC"]?=?data["department_name"].cat.codes
data["job_title_NUMERIC_NUMERIC"]?=?data["job_title"].cat.codes
data["gender_short_NUMERIC"]?=?data["gender_short"].cat.codes
data["termreason_desc_NUMERIC"]?=?data["termreason_desc"].cat.codes
data["termtype_desc_NUMERIC"]?=?data["termtype_desc"].cat.codes
data["BUSINESS_UNIT_NUMERIC"]?=?data["BUSINESS_UNIT"].cat.codes
6、移除ID列和目標(biāo)變量編碼
#?移除ID列
data?=?data.drop(columns=['EmployeeID'])
#?目標(biāo)變量類型轉(zhuǎn)換
data['ClasseNumerica']?=?np.where(data['STATUS']=='ACTIVE',?1,?0)
data.tail(15)
7、目標(biāo)變量分布情況
print('->?目標(biāo)變量類別的分布情況:')
QtdObservacoes?=?data.shape[0]
QtdValClasse?=?data['STATUS'].unique().size
count?=?0
print('樣本數(shù):',?QtdObservacoes)
while?count?????print(data['STATUS'].unique()[count],?':',?(data.groupby('STATUS').size())[count],?'(',?(((data.groupby('STATUS').size())[count]/?(QtdObservacoes))?*?100),?'%?)')
????count?=?count?+?1

8、數(shù)據(jù)可視化分析
1)單變量分析
data.hist(sharex=False,?sharey=False,?figsize=(20,12),?grid=True)
plt.show()

2)數(shù)值型變量相關(guān)系數(shù)矩陣可視化
#?相關(guān)系數(shù)矩陣
ColunaNumericas?=?(data._get_numeric_data()).columns.tolist()?#獲取數(shù)值型變量集
QtdTotalElementos?=?len(ColunaNumericas)
values_corr?=?data.corr()?#生成相關(guān)性系數(shù)矩陣
#?相關(guān)性系數(shù)矩陣可視化
fig?=?plt.figure()?#?構(gòu)建圖表
ax?=?fig.add_subplot(1,1,1)?
correlation_matrix?=?ax.matshow(values_corr
????????????????????????????????,vmin?=?-1
????????????????????????????????,vmax?=?1
????????????????????????????????,interpolation?=?'none'
????????????????????????????????,cmap?=?'hot_r'?#'hot_r',?'pink_r',?'spring',?'spring_r'
????????????????????????????????,aspect='auto'
????????????????????????????????#,alpha?=?0.75
????????????????????????????????,origin?=?'upper'
???????????????????????????????)?#matshow?->?把數(shù)組或者矩陣?yán)L制為圖形
fig.colorbar(correlation_matrix)?
ticks?=?np.arange(0,?QtdTotalElementos,?1)?
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xticklabels(labels=ColunaNumericas,?rotation=85,?fontsize=12)
ax.set_yticklabels(labels=ColunaNumericas,?fontsize=12)
plt.show()

3)觀察一些預(yù)測(cè)預(yù)測(cè)變量和目標(biāo)變量的關(guān)系
#?可視化一些預(yù)測(cè)變量和目標(biāo)變量的關(guān)系
ColunaNumericas?=?['STATUS_YEAR',?'age',?'length_of_service',?'store_name',?'city_name_NUMERIC']
dataframe?=?data[ColunaNumericas]
dataframe?=?dataframe.assign(Classe=data['STATUS'])?#?往數(shù)據(jù)框中添加新列
sns.pairplot(data=dataframe,?hue="Classe",?kind='scatter',?palette="cubehelix")

9、類別不平衡問題的處理
通過類別變量取值分布,發(fā)現(xiàn)有類別不平衡問題。處理策略,采用一種欠抽樣的方法。具體操作:目標(biāo)變量為離職的所有數(shù)據(jù)集+在職數(shù)據(jù)集隨機(jī)抽取5000條記錄以構(gòu)成訓(xùn)練集。
ColunaNumericas?=?(data._get_numeric_data()).columns.tolist()
QtColunasNumericas?=?len(ColunaNumericas)
df_ALL_TERMINATED?=?data[data['ClasseNumerica']?==?0]
df_ALL_ACTIVE?=?data[data['ClasseNumerica']?==?1]
df_ALL_TERMINATED?=?(df_ALL_TERMINATED[ColunaNumericas])
df_ALL_ACTIVE?=?(df_ALL_ACTIVE[ColunaNumericas])
preditoras_ALL_TERMINATED?=?df_ALL_TERMINATED.values[:,:-1]
preditoras_ALL_ACTIVE?=?df_ALL_ACTIVE.values[:,:-1]
alvo_ALL_TERMINATED?=?df_ALL_TERMINATED.values[:,-1:QtColunasNumericas]
alvo_ALL_ACTIVE?=?df_ALL_ACTIVE.values[:,-1:QtColunasNumericas]四、模型構(gòu)建和評(píng)價(jià),
如何創(chuàng)建最佳模型?
對(duì)于整理好的數(shù)據(jù)集,首先把數(shù)據(jù)集劃分為訓(xùn)練集和測(cè)試集,然后利用交叉驗(yàn)證的思想選擇最佳模型,第三,使用最佳模型對(duì)訓(xùn)練集做模型構(gòu)建,第四,利用測(cè)試集對(duì)模型的性能做評(píng)價(jià)。
10、訓(xùn)練集和測(cè)試集
random.seed(1)
#?訓(xùn)練集
preditoras_5000_INSTANCES_ACTIVE?=?np.array(?random.sample(population?=?list(preditoras_ALL_ACTIVE),?k?=?5000))
preditoras_treino?=?np.concatenate([preditoras_ALL_TERMINATED,?preditoras_5000_INSTANCES_ACTIVE])
#?測(cè)試集
preditoras_1000_INSTANCES_TERMINATED?=?np.array(?random.sample(population?=?list(preditoras_ALL_TERMINATED),?k?=?1000)?)
preditoras_40000_INSTANCES_ACTIVE?=?np.array(?random.sample(population?=?list(preditoras_ALL_ACTIVE),?k?=?40000)?)
preditoras_teste?=?np.concatenate([preditoras_1000_INSTANCES_TERMINATED,?preditoras_40000_INSTANCES_ACTIVE])
#?訓(xùn)練集目標(biāo)變量
alvo_treino_5000_INSTANCES_ACTIVE?=?np.array(?random.sample(population?=?list(alvo_ALL_ACTIVE),?k?=?5000)?)
alvo_treino?=?np.concatenate([alvo_ALL_TERMINATED,?alvo_treino_5000_INSTANCES_ACTIVE])
#?測(cè)試集目標(biāo)變量
alvo_1000_INSTANCES_TERMINATED?=?np.array(?random.sample(population?=?list(alvo_ALL_TERMINATED),?k?=?1000)?)
alvo_40000_INSTANCES_ACTIVE?=?np.array(?random.sample(population?=?list(alvo_ALL_ACTIVE),?k?=?40000)?)
alvo_teste?=?np.concatenate([alvo_1000_INSTANCES_TERMINATED,?alvo_40000_INSTANCES_ACTIVE])
11、交叉驗(yàn)證做模型的選擇
#?交叉驗(yàn)證--模型的選擇
#?顯示模型的性能分析
disable_DataConversionWarning()
disable_FutureWarning()
#?根據(jù)每種算法創(chuàng)建機(jī)器學(xué)習(xí)模型
#?使用accuracy指標(biāo)做度量,值越大,模型性能越好
modelos?=?[]
modelos.append(('LogisticRegression',?LogisticRegression()))
modelos.append(('KNeighborsClassifier',?KNeighborsClassifier()))
modelos.append(('DecisionTreeClassifier',?DecisionTreeClassifier()))
resultados?=?[]
nomes?=?[]
modelos_nome?=?[]?
mensagens?=?[]?
tempo?=?[]
n_folds?=?10
seed?=?7
for?nome,?modelo?in?modelos:
????#?設(shè)置處理開始的時(shí)間
????start_time?=?time.time()
????#?創(chuàng)建交叉驗(yàn)證?10折交叉驗(yàn)證
????k_folds?=?model_selection.KFold(n_splits?=?n_folds,?random_state?=?seed)
????#?創(chuàng)建模型
????result_saida?=?model_selection.cross_val_score(modelo?
????????????????????????????????????????????????????,preditoras_treino?
????????????????????????????????????????????????????,alvo_treino?
????????????????????????????????????????????????????,cv?=?k_folds?
????????????????????????????????????????????????????#,n_jobs?=?-1?
????????????????????????????????????????????????????,scoring?=?'accuracy'
????????????????????????????????????????????????????#,verbose?=?5?
????????????????????????????????????????????????????)
????#記錄模型名稱
????modelos_nome.append(nome)
????#記錄模型結(jié)果
????resultados.append(result_saida?*?100)
????#輸出最終消息
????mensagens.append('模型:?%s??????\n\n性能平均值:?%.2f%%\n性能標(biāo)準(zhǔn)差:?%.2f%%'?%?(modelo,?(result_saida.mean()*100),?(result_saida.std()*100)))
????#?執(zhí)行模型所需要的時(shí)間
????tempo.append(time.time()?-?start_time)
qtd_mensagens?=?len(mensagens)
iterador?=?0
print('--->?準(zhǔn)確性描述評(píng)估?<---')
while?qtd_mensagens?>?iterador:
????print('--------------------------------------------------------------------',?'\n')
????print(mensagens[iterador])
????print('運(yùn)行的時(shí)間:?%s (HH:MM:SS)'?%?timedelta(seconds=round(tempo[iterador])))
????iterador?=?iterador?+?1
print('--------------------------------------------------------------------')
#?模型準(zhǔn)確性可視化比較
fig?=?plt.figure()
fig.suptitle('分類算法性能比較')
ax?=?fig.add_subplot(111)
plt.boxplot(resultados)
ax.set_xticklabels(modelos_nome)
plt.show()
enable_All_Warning()
12、最佳模型對(duì)訓(xùn)練集重構(gòu)模型
通過交叉驗(yàn)證,發(fā)現(xiàn)決策樹模型是最佳模型。我們使用決策樹模型對(duì)訓(xùn)練數(shù)集重構(gòu)模型。
#?基于模型選擇里面最佳模型?決策樹模型?構(gòu)建預(yù)測(cè)模型
#?警告處理
disable_DataConversionWarning()
disable_FutureWarning()
#?創(chuàng)建管道
pipeline?=?[]
pipeline.append(('Standardize',?StandardScaler()))
pipeline.append(('ScaleFit',?MinMaxScaler()))
pipeline.append(('Normalizer',?Normalizer()))
pipeline.append(('DecisionTreeClassifier',?DecisionTreeClassifier()))
pipeline?=?Pipeline(steps=pipeline)
model?=?pipeline.fit(preditoras_treino,?alvo_treino)
13、模型的性能分析
對(duì)構(gòu)建好的模型,在測(cè)試集進(jìn)行模型的性能分析??梢酝ㄟ^模型準(zhǔn)確率,模型混淆矩陣或者模型性能分析報(bào)告,了解所構(gòu)建模型的性能狀況。
previsoes?=?model.predict(preditoras_teste)
#?模型在測(cè)試數(shù)據(jù)集上應(yīng)用
print('->?模型的準(zhǔn)確率:',?str(round((accuracy_score(alvo_teste,?previsoes)*100),2))?+?'%')
print('\n->?模型的混淆矩陣:\n',?confusion_matrix(alvo_teste,?previsoes),?'\n')
print('->?模型分類性能評(píng)價(jià)報(bào)告:\n\n',?classification_report(alvo_teste,?previsoes))五、模型的應(yīng)用,
如何指導(dǎo)決策?
針對(duì)新的的數(shù)據(jù)集,按著模型構(gòu)建前的數(shù)據(jù)加工邏輯,做好數(shù)據(jù)處理后,然后利用構(gòu)建好的模型對(duì)新數(shù)據(jù)集做預(yù)測(cè),對(duì)預(yù)測(cè)的結(jié)果做應(yīng)用。
總結(jié)
通過員工流動(dòng)分析和預(yù)測(cè)這個(gè)案例,我們可以了解到數(shù)據(jù)科學(xué)工作的流程,從業(yè)務(wù)問題入手,然后到數(shù)據(jù)的理解和準(zhǔn)備,模型的構(gòu)建和評(píng)價(jià),以及模型應(yīng)用和指導(dǎo)決策與行動(dòng),以創(chuàng)造價(jià)值的系統(tǒng)化過程。我們也可以學(xué)習(xí)到使用Python語言做數(shù)據(jù)科學(xué)工作的相關(guān)技能,包括所使用的Python庫,數(shù)據(jù)畫像的手段,變量類型的編碼,管道式模型設(shè)計(jì)方法等。
這個(gè)案例還有很多地方值得進(jìn)一步深入思考和挖掘,感興趣的朋友可以在此基礎(chǔ)上,做進(jìn)一步的工作。比方說,數(shù)據(jù)的處理方法,類別不平衡處理,算法的設(shè)計(jì),模型性能的提升,特征工程等課題。
附錄:案例完整代碼(需要數(shù)據(jù)集的朋友可以添加我的個(gè)人微信獲取或者從Kaggle平臺(tái)下載獲?。?br>
#!/usr/bin/env?python
#?coding:?utf-8
import?random
import?time?as?time
from?datetime?import?timedelta
import?pandas?as?pd
import?numpy?as?np
import?matplotlib.pyplot?as?plt
import?seaborn?as?sns
from?sklearn?import?model_selection
from?sklearn.preprocessing?import?MinMaxScaler
from?sklearn.preprocessing?import?StandardScaler
from?sklearn.preprocessing?import?Normalizer
from?sklearn.pipeline?import?Pipeline
from?sklearn.linear_model?import?LogisticRegression
from?sklearn.tree?import?DecisionTreeClassifier
from?sklearn.neighbors?import?KNeighborsClassifier
from?sklearn.metrics?import?classification_report
from?sklearn.metrics?import?confusion_matrix
from?sklearn.metrics?import?accuracy_score
from?sklearn.exceptions?import?DataConversionWarning
import?warnings
def?disable_DataConversionWarning():
????warnings.filterwarnings(action='ignore',?category=DataConversionWarning)
????
def?disable_FutureWarning():
????warnings.filterwarnings(action='ignore',?category=FutureWarning)
def?enable_All_Warning():
????warnings.simplefilter('always')
????
get_ipython().run_line_magic('matplotlib',?'inline')
file?=?'./datasets/MFG10YearTerminationData.csv'
data?=?pd.read_csv(filepath_or_buffer=file,?header=0,?sep=',')
print('數(shù)據(jù)檢視:輸出數(shù)據(jù)集前5行...')
data.head(5)
print('樣本數(shù):',?data.shape[0])
print('變量數(shù):',?data.shape[1])
data.shape
print('變量的數(shù)據(jù)類型:')
data.dtypes
print('數(shù)值類型變量的描述性統(tǒng)計(jì)分析:')
data.describe().T
print('目標(biāo)變量的取值:',?data['STATUS'].unique())
#?類別變量編碼?
#?第一步:對(duì)象轉(zhuǎn)換為類別變量
data["city_name"]?=?data["city_name"].astype('category')
data["department_name"]?=?data["department_name"].astype('category')
data["job_title"]?=?data["job_title"].astype('category')
data["gender_short"]?=?data["gender_short"].astype('category')
data["termreason_desc"]?=?data["termreason_desc"].astype('category')
data["termtype_desc"]?=?data["termtype_desc"].astype('category')
data["BUSINESS_UNIT"]?=?data["BUSINESS_UNIT"].astype('category')
#?第二步:類別變量做標(biāo)簽編碼
data["city_name_NUMERIC"]?=?data["city_name"].cat.codes
data["department_name_NUMERIC"]?=?data["department_name"].cat.codes
data["job_title_NUMERIC_NUMERIC"]?=?data["job_title"].cat.codes
data["gender_short_NUMERIC"]?=?data["gender_short"].cat.codes
data["termreason_desc_NUMERIC"]?=?data["termreason_desc"].cat.codes
data["termtype_desc_NUMERIC"]?=?data["termtype_desc"].cat.codes
data["BUSINESS_UNIT_NUMERIC"]?=?data["BUSINESS_UNIT"].cat.codes
data.head()
#?移除ID列
data?=?data.drop(columns=['EmployeeID'])
#?目標(biāo)變量類型轉(zhuǎn)換
data['ClasseNumerica']?=?np.where(data['STATUS']=='ACTIVE',?1,?0)
data.tail(15)
print('->?目標(biāo)變量類別的分布情況:')
QtdObservacoes?=?data.shape[0]
QtdValClasse?=?data['STATUS'].unique().size
count?=?0
print('樣本數(shù):',?QtdObservacoes)
while?count?????print(data['STATUS'].unique()[count],?':',?(data.groupby('STATUS').size())[count],?'(',?(((data.groupby('STATUS').size())[count]/?(QtdObservacoes))?*?100),?'%?)')
????count?=?count?+?1
data.groupby('STATUS').size()
#?可視化分析?
data.hist(sharex=False,?sharey=False,?figsize=(20,12),?grid=True)
plt.show()
#?相關(guān)系數(shù)矩陣
ColunaNumericas?=?(data._get_numeric_data()).columns.tolist()?#獲取數(shù)值型變量集
QtdTotalElementos?=?len(ColunaNumericas)
values_corr?=?data.corr()?#生成相關(guān)性系數(shù)矩陣
#?相關(guān)性系數(shù)矩陣可視化
fig?=?plt.figure()?#?構(gòu)建圖表
ax?=?fig.add_subplot(1,1,1)?
correlation_matrix?=?ax.matshow(values_corr
????????????????????????????????,vmin?=?-1
????????????????????????????????,vmax?=?1
????????????????????????????????,interpolation?=?'none'
????????????????????????????????,cmap?=?'hot_r'?#'hot_r',?'pink_r',?'spring',?'spring_r'
????????????????????????????????,aspect='auto'
????????????????????????????????#,alpha?=?0.75
????????????????????????????????,origin?=?'upper'
???????????????????????????????)?#matshow?->?把數(shù)組或者矩陣?yán)L制為圖形
fig.colorbar(correlation_matrix)?
ticks?=?np.arange(0,?QtdTotalElementos,?1)?
ax.set_xticks(ticks)
ax.set_yticks(ticks)
ax.set_xticklabels(labels=ColunaNumericas,?rotation=85,?fontsize=12)
ax.set_yticklabels(labels=ColunaNumericas,?fontsize=12)
plt.show()
#?可視化主要變量和目標(biāo)變量的關(guān)系
ColunaNumericas?=?['STATUS_YEAR',?'age',?'length_of_service',?'store_name',?'city_name_NUMERIC']
dataframe?=?data[ColunaNumericas]
dataframe?=?dataframe.assign(Classe=data['STATUS'])?#?往數(shù)據(jù)框中添加新列
sns.pairplot(data=dataframe,?hue="Classe",?kind='scatter',?palette="cubehelix")
ColunaNumericas?=?(data._get_numeric_data()).columns.tolist()
QtColunasNumericas?=?len(ColunaNumericas)
df_ALL_TERMINATED?=?data[data['ClasseNumerica']?==?0]
df_ALL_ACTIVE?=?data[data['ClasseNumerica']?==?1]
df_ALL_TERMINATED?=?(df_ALL_TERMINATED[ColunaNumericas])
df_ALL_ACTIVE?=?(df_ALL_ACTIVE[ColunaNumericas])
preditoras_ALL_TERMINATED?=?df_ALL_TERMINATED.values[:,:-1]
preditoras_ALL_ACTIVE?=?df_ALL_ACTIVE.values[:,:-1]
alvo_ALL_TERMINATED?=?df_ALL_TERMINATED.values[:,-1:QtColunasNumericas]
alvo_ALL_ACTIVE?=?df_ALL_ACTIVE.values[:,-1:QtColunasNumericas]
#?構(gòu)建訓(xùn)練集和測(cè)試集?
random.seed(1)
#?訓(xùn)練集
preditoras_5000_INSTANCES_ACTIVE?=?np.array(?random.sample(population?=?list(preditoras_ALL_ACTIVE),?k?=?5000))
preditoras_treino?=?np.concatenate([preditoras_ALL_TERMINATED,?preditoras_5000_INSTANCES_ACTIVE])
#?測(cè)試集
preditoras_1000_INSTANCES_TERMINATED?=?np.array(?random.sample(population?=?list(preditoras_ALL_TERMINATED),?k?=?1000)?)
preditoras_40000_INSTANCES_ACTIVE?=?np.array(?random.sample(population?=?list(preditoras_ALL_ACTIVE),?k?=?40000)?)
preditoras_teste?=?np.concatenate([preditoras_1000_INSTANCES_TERMINATED,?preditoras_40000_INSTANCES_ACTIVE])
#?訓(xùn)練集目標(biāo)變量
alvo_treino_5000_INSTANCES_ACTIVE?=?np.array(?random.sample(population?=?list(alvo_ALL_ACTIVE),?k?=?5000)?)
alvo_treino?=?np.concatenate([alvo_ALL_TERMINATED,?alvo_treino_5000_INSTANCES_ACTIVE])
#?測(cè)試集目標(biāo)變量
alvo_1000_INSTANCES_TERMINATED?=?np.array(?random.sample(population?=?list(alvo_ALL_TERMINATED),?k?=?1000)?)
alvo_40000_INSTANCES_ACTIVE?=?np.array(?random.sample(population?=?list(alvo_ALL_ACTIVE),?k?=?40000)?)
alvo_teste?=?np.concatenate([alvo_1000_INSTANCES_TERMINATED,?alvo_40000_INSTANCES_ACTIVE])
#?交叉驗(yàn)證--模型的選擇
#?顯示模型的性能分析
disable_DataConversionWarning()
disable_FutureWarning()
#?根據(jù)每種算法創(chuàng)建機(jī)器學(xué)習(xí)模型
modelos?=?[]
modelos.append(('LogisticRegression',?LogisticRegression()))
modelos.append(('KNeighborsClassifier',?KNeighborsClassifier()))
modelos.append(('DecisionTreeClassifier',?DecisionTreeClassifier()))
resultados?=?[]
nomes?=?[]
modelos_nome?=?[]?
mensagens?=?[]?
tempo?=?[]
n_folds?=?10
seed?=?7
for?nome,?modelo?in?modelos:
????#?設(shè)置處理開始的時(shí)間
????start_time?=?time.time()
????#?創(chuàng)建交叉驗(yàn)證?10折交叉驗(yàn)證
????k_folds?=?model_selection.KFold(n_splits?=?n_folds,?random_state?=?seed)
????#?創(chuàng)建模型
????result_saida?=?model_selection.cross_val_score(modelo?
????????????????????????????????????????????????????,preditoras_treino?
????????????????????????????????????????????????????,alvo_treino?
????????????????????????????????????????????????????,cv?=?k_folds?
????????????????????????????????????????????????????#,n_jobs?=?-1?
????????????????????????????????????????????????????,scoring?=?'accuracy'
????????????????????????????????????????????????????#,verbose?=?5?
????????????????????????????????????????????????????)
????#記錄模型名稱
????modelos_nome.append(nome)
????#記錄模型結(jié)果
????resultados.append(result_saida?*?100)
????#輸出最終消息
????mensagens.append('模型:?%s??????\n\n性能平均值:?%.2f%%\n性能標(biāo)準(zhǔn)差:?%.2f%%'?%?(modelo,?(result_saida.mean()*100),?(result_saida.std()*100)))
????#?執(zhí)行模型所需要的時(shí)間
????tempo.append(time.time()?-?start_time)
qtd_mensagens?=?len(mensagens)
iterador?=?0
print('--->?準(zhǔn)確性描述評(píng)估?<---')
while?qtd_mensagens?>?iterador:
????print('--------------------------------------------------------------------',?'\n')
????print(mensagens[iterador])
????print('運(yùn)行的時(shí)間:?%s (HH:MM:SS)'?%?timedelta(seconds=round(tempo[iterador])))
????iterador?=?iterador?+?1
print('--------------------------------------------------------------------')
#?模型準(zhǔn)確性可視化比較
fig?=?plt.figure()
fig.suptitle('分類算法性能比較')
ax?=?fig.add_subplot(111)
plt.boxplot(resultados)
ax.set_xticklabels(modelos_nome)
plt.show()
enable_All_Warning()
#?基于模型選擇里面最佳模型?決策樹模型?構(gòu)建預(yù)測(cè)模型
#?警告處理
disable_DataConversionWarning()
disable_FutureWarning()
#?創(chuàng)建管道
pipeline?=?[]
pipeline.append(('Standardize',?StandardScaler()))
pipeline.append(('ScaleFit',?MinMaxScaler()))
pipeline.append(('Normalizer',?Normalizer()))
pipeline.append(('DecisionTreeClassifier',?DecisionTreeClassifier()))
pipeline?=?Pipeline(steps=pipeline)
model?=?pipeline.fit(preditoras_treino,?alvo_treino)
previsoes?=?model.predict(preditoras_teste)
#?模型在測(cè)試數(shù)據(jù)集上應(yīng)用
print('->?模型的準(zhǔn)確率:',?str(round((accuracy_score(alvo_teste,?previsoes)*100),2))?+?'%')
print('\n->?模型的混淆矩陣:\n',?confusion_matrix(alvo_teste,?previsoes),?'\n')
print('->?模型分類性能評(píng)價(jià)報(bào)告:\n\n',?classification_report(alvo_teste,?previsoes))
參考資料:
1、案例的數(shù)據(jù)集-來自Kaggle平臺(tái)
(https://www.kaggle.com/HRAnalyticRepository/employee-attrition-data/)
2、 pandas庫類別變量的數(shù)據(jù)處理-類別編碼
(https://pandas.pydata.org/pandasdocs/stable/user_guide/categorical.html)
3、Numpy庫where函數(shù)
https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.where.html
4、StandardScaler/MinMaxScaler/Normalizer之間的區(qū)別
(https://blog.csdn.net/u010471284/article/details/97627441)
5、sklearn: 管道與特征聯(lián)合
(https://tsinghua-gongjing.github.io/posts/sklearn_pipeline.html)
6、cross_val_score的 scoring參數(shù)值解析
https://blog.csdn.net/qq_32590631/article/details/82831613
7、https://github.com/daniellj/DataScience
公眾號(hào)推薦
數(shù)據(jù)思踐
數(shù)據(jù)思踐公眾號(hào)記錄和分享數(shù)據(jù)人思考和踐行的內(nèi)容與故事。
Python語言群
誠邀您加入
《數(shù)據(jù)科學(xué)與人工智能》公眾號(hào)推薦朋友們學(xué)習(xí)和使用Python語言,需要加入Python語言群的,請(qǐng)掃碼加我個(gè)人微信,備注【姓名-Python群】,我誠邀你入群,大家學(xué)習(xí)和分享。
