
CDA數(shù)據(jù)分析師 出品
作者:真達(dá)、Mika
數(shù)據(jù):真達(dá)
【導(dǎo)讀】今天的內(nèi)容是一期python實(shí)戰(zhàn)訓(xùn)練,我們來手把手教你用Python分析保險(xiǎn)產(chǎn)品交叉銷售和哪些因素有關(guān)。
01、實(shí)戰(zhàn)背景
首先介紹下實(shí)戰(zhàn)的背景, 這次的數(shù)據(jù)集來自kaggle:
https://www.kaggle.com/anmolkumar/health-insurance-cross-sell-prediction
我們的客戶是一家保險(xiǎn)公司,最近新推出了一款汽車保險(xiǎn)?,F(xiàn)在他們的需要是建立一個(gè)模型,用來預(yù)測去年的投保人是否會(huì)對這款汽車保險(xiǎn)感興趣。
我們知道,保險(xiǎn)單指的是,保險(xiǎn)公司承諾為特定類型的損失、損害、疾病或死亡提供賠償保證,客戶則需要定期向保險(xiǎn)公司支付一定的保險(xiǎn)費(fèi)。這里再進(jìn)一步說明一下。
例如,你每年要為20萬的健康保險(xiǎn)支付2000元的保險(xiǎn)費(fèi)。那么你肯定會(huì)想,保險(xiǎn)公司只收取5000元的保費(fèi),這種情況下,怎么能承擔(dān)如此高的住院費(fèi)用呢? 這時(shí),“概率”的概念就出現(xiàn)了。例如,像你一樣,可能有100名客戶每年支付2000元的保費(fèi),但當(dāng)年住院的可能只有少數(shù)人,(比如2-3人),而不是所有人。通過這種方式,每個(gè)人都分擔(dān)了其他人的風(fēng)險(xiǎn)。
和醫(yī)療保險(xiǎn)一樣,買了車險(xiǎn)的話,每年都需要向保險(xiǎn)公司支付一定數(shù)額的保險(xiǎn)費(fèi),這樣在車輛發(fā)生意外事故時(shí),保險(xiǎn)公司將向客戶提供賠償(稱為“保險(xiǎn)金額”)。
我們要做的就是建立模型,來預(yù)測客戶是否對汽車保險(xiǎn)感興趣。這對保險(xiǎn)公司來說是非常有幫助的,公司可以據(jù)此制定溝通策略,接觸這些客戶,并優(yōu)化其商業(yè)模式和收入。
02、數(shù)據(jù)理解
為了預(yù)測客戶是否對車輛保險(xiǎn)感興趣,我們需要了解一些客戶信息 (性別、年齡等)、車輛(車齡、損壞情況)、保單(保費(fèi)、采購渠道)等信息。
數(shù)據(jù)劃分為訓(xùn)練集和測試集,訓(xùn)練數(shù)據(jù)包含381109筆客戶資料,每筆客戶資料包含12個(gè)字段,1個(gè)客戶ID字段、10個(gè)輸入字段及1個(gè)目標(biāo)字段-Response是否響應(yīng)(1代表感興趣,0代表不感興趣)。測試數(shù)據(jù)包含127037筆客戶資料;字段個(gè)數(shù)與訓(xùn)練數(shù)據(jù)相同,目標(biāo)字段沒有值。字段的定義可參考下文。
下面我們開始吧!
03、數(shù)據(jù)讀入和預(yù)覽
首先開始數(shù)據(jù)讀入和預(yù)覽。
# 數(shù)據(jù)整理 import numpy as np import pandas as pd # 可視化 import matplotlib.pyplot as plt import seaborn as sns import plotly as py import plotly.graph_objs as go import plotly.express as px pyplot = py.offline.plot from exploratory_data_analysis import EDAnalysis # 自定義
# 讀入訓(xùn)練集 train = pd.read_csv('../data/train.csv') train.head()
# 讀入測試集 test = pd.read_csv('../data/test.csv') test.head()
print(train.info()) print('-' * 50) print(test.info())
<class 'pandas.core.frame.DataFrame'> RangeIndex: 381109 entries, 0 to 381108 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 381109 non-null int64 1 Gender 381109 non-null object 2 Age 381109 non-null int64 3 Driving_License 381109 non-null int64 4 Region_Code 381109 non-null float64 5 Previously_Insured 381109 non-null int64 6 Vehicle_Age 381109 non-null object 7 Vehicle_Damage 381109 non-null object 8 Annual_Premium 381109 non-null float64 9 Policy_Sales_Channel 381109 non-null float64 10 Vintage 381109 non-null int64 11 Response 381109 non-null int64 dtypes: float64(3), int64(6), object(3) memory usage: 34.9+ MB None -------------------------------------------------- <class 'pandas.core.frame.DataFrame'> RangeIndex: 127037 entries, 0 to 127036 Data columns (total 11 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 127037 non-null int64 1 Gender 127037 non-null object 2 Age 127037 non-null int64 3 Driving_License 127037 non-null int64 4 Region_Code 127037 non-null float64 5 Previously_Insured 127037 non-null int64 6 Vehicle_Age 127037 non-null object 7 Vehicle_Damage 127037 non-null object 8 Annual_Premium 127037 non-null float64 9 Policy_Sales_Channel 127037 non-null float64 10 Vintage 127037 non-null int64 dtypes: float64(3), int64(5), object(3) memory usage: 10.7+ MB None
04、探索性分析
下面,我們基于訓(xùn)練數(shù)據(jù)集進(jìn)行探索性數(shù)據(jù)分析。
1. 描述性分析
首先對數(shù)據(jù)集中數(shù)值型屬性進(jìn)行描述性統(tǒng)計(jì)分析。
desc_table = train.drop(['id', 'Vehicle_Age'], axis=1).describe().T desc_table
通過描述性分析后,可以得到以下結(jié)論。從以上描述性分析結(jié)果可以得出:
2. 目標(biāo)變量的分布
訓(xùn)練集共有381109筆客戶資料,其中感興趣的有46710人,占比12.3%,不感興趣的有334399人,占比87.7%。
train['Response'].value_counts() 0 334399 1 46710 Name: Response, dtype: int64
values = train['Response'].value_counts().values.tolist() # 軌跡 trace1 = go.Pie(labels=['Not interested', 'Interested'], values=values, hole=.5, marker={'line': {'color': 'white', 'width': 1.3}} ) # 軌跡列表 data = [trace1] # 布局 layout = go.Layout(title=f'Distribution_ratio of Response', height=600) # 畫布 fig = go.Figure(data=data, layout=layout) # 生成HTML pyplot(fig, filename='./html/目標(biāo)變量分布.html')
3. 性別因素
從條形圖可以看出,男性的客戶群體對汽車保險(xiǎn)感興趣的概率稍高,是13.84%,相較女性客戶高出3個(gè)百分點(diǎn)。
pd.crosstab(train['Gender'], train['Response'])
# 實(shí)例類 eda = EDAnalysis(data=train, id_col='id', target='Response') # 柱形圖 fig = eda.draw_bar_stack_cat(colname='Gender') pyplot(fig, filename='./html/性別與是否感興趣.html')
4. 之前是否投保
沒有購買汽車保險(xiǎn)的客戶響應(yīng)概率更高,為22.54%,有購買汽車保險(xiǎn)的客戶則沒有這一需求,感興趣的概率僅為0.09%。
pd.crosstab(train['Previously_Insured'], train['Response'])
fig = eda.draw_bar_stack_cat(colname='Previously_Insured') pyplot(fig, filename='./html/之前是否投保與是否感興趣.html')
5. 車齡因素
車齡越大,響應(yīng)概率越高,大于兩年的車齡感興趣的概率最高,為29.37%,其次是1~2年車齡,概率為17.38%。小于1年的僅為4.37%。
6. 車輛損壞情況
車輛曾經(jīng)損壞過的客戶有較高的響應(yīng)概率,為23.76%,相比之下,客戶過去車輛沒有損壞的響應(yīng)概率僅為0.52%
7. 不同年齡
從直方圖中可以看出,年齡較高的群體和較低的群體響應(yīng)的概率較低,30~60歲之前的客戶響應(yīng)概率較高。通過可視化探索,我們大致可以知道:
車齡在1年以上,之前有車輛損壞的情況出現(xiàn),且未購買過車輛保險(xiǎn)的客戶有較高的響應(yīng)概率。
此部分工作主要包含字段選擇,數(shù)據(jù)清洗和數(shù)據(jù)編碼,字段的處理如下:
# 刪除字段 train = train.drop(['Region_Code', 'Policy_Sales_Channel'], axis=1) # 蓋帽法處理異常值 f_max = train['Annual_Premium'].mean() + 3*train['Annual_Premium'].std() f_min = train['Annual_Premium'].mean() - 3*train['Annual_Premium'].std() train.loc[train['Annual_Premium'] > f_max, 'Annual_Premium'] = f_max train.loc[train['Annual_Premium'] < f_min, 'Annual_Premium'] = f_min # 數(shù)據(jù)編碼 train['Gender'] = train['Gender'].map({'Male': 1, 'Female': 0}) train['Vehicle_Damage'] = train['Vehicle_Damage'].map({'Yes': 1, 'No': 0}) train['Vehicle_Age'] = train['Vehicle_Age'].map({'< 1 Year': 0, '1-2 Year': 1, '> 2 Years': 2}) train.head()
測試集做相同的處理:
# 刪除字段 test = test.drop(['Region_Code', 'Policy_Sales_Channel'], axis=1) # 蓋帽法處理 test.loc[test['Annual_Premium'] > f_max, 'Annual_Premium'] = f_max test.loc[test['Annual_Premium'] < f_min, 'Annual_Premium'] = f_min # 數(shù)據(jù)編碼 test['Gender'] = test['Gender'].map({'Male': 1, 'Female': 0}) test['Vehicle_Damage'] = test['Vehicle_Damage'].map({'Yes': 1, 'No': 0}) test['Vehicle_Age'] = test['Vehicle_Age'].map({'< 1 Year': 0, '1-2 Year': 1, '> 2 Years': 2}) test.head()
我們選擇使用以下幾種模型進(jìn)行建置,并比較模型的分類效能。首先在將訓(xùn)練集劃分為訓(xùn)練集和驗(yàn)證集,其中訓(xùn)練集用于訓(xùn)練模型,驗(yàn)證集用于驗(yàn)證模型效果。首先導(dǎo)入建模庫:
# 建模 from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from lightgbm import LGBMClassifier # 預(yù)處理 from sklearn.preprocessing import StandardScaler, MinMaxScaler # 模型評(píng)估 from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.metrics import confusion_matrix, classification_report, accuracy_score, f1_score, roc_auc_score
# 劃分特征和標(biāo)簽 X = train.drop(['id', 'Response'], axis=1) y = train['Response'] # 劃分訓(xùn)練集和驗(yàn)證集(分層抽樣) X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0) print(X_train.shape, X_val.shape, y_train.shape, y_val.shape) (304887, 8) (76222, 8) (304887,) (76222,)
# 處理樣本不平衡,對0類樣本進(jìn)行降采樣 from imblearn.under_sampling import RandomUnderSampler under_model = RandomUnderSampler(sampling_strategy={0:133759, 1:37368}, random_state=0) X_train, y_train = under_model.fit_sample(X_train, y_train) # 保存一份極值標(biāo)準(zhǔn)化的數(shù)據(jù) mms = MinMaxScaler() X_train_scaled = pd.DataFrame(mms.fit_transform(X_train), columns=x_under.columns) X_val_scaled = pd.DataFrame(mms.transform(X_val), columns=x_under.columns) # 測試集 X_test = test.drop('id', axis=1) X_test_scaled = pd.DataFrame(mms.transform(X_test), columns=X_test.columns)
1. KNN算法
# 建立knn knn = KNeighborsClassifier(n_neighbors=3, n_jobs=-1) knn.fit(X_train_scaled, y_train) y_pred = knn.predict(X_val_scaled) print('Simple KNeighborsClassifier accuracy:%.3f' % (accuracy_score(y_val, y_pred))) print('Simple KNeighborsClassifier f1_score: %.3f' % (f1_score(y_val, y_pred))) print('Simple KNeighborsClassifier roc_auc_score: %.3f' % (roc_auc_score(y_val, y_pred)))
Simple KNeighborsClassifier accuracy:0.807 Simple KNeighborsClassifier f1_score: 0.337 Simple KNeighborsClassifier roc_auc_score: 0.632
# 對測試集評(píng)估 test_y = knn.predict(X_test_scaled) test_y[:5] array([0, 0, 1, 0, 0], dtype=int64)
2. Logistic回歸
# Logistic回歸 lr = LogisticRegression() lr.fit(X_train_scaled, y_train) y_pred = lr.predict(X_val_scaled) print('Simple LogisticRegression accuracy:%.3f' % (accuracy_score(y_val, y_pred))) print('Simple LogisticRegression f1_score: %.3f' % (f1_score(y_val, y_pred))) print('Simple LogisticRegression roc_auc_score: %.3f' % (roc_auc_score(y_val, y_pred)))
Simple LogisticRegression accuracy:0.863 Simple LogisticRegression f1_score: 0.156 Simple LogisticRegression roc_auc_score: 0.536
3. 決策樹
# 決策樹 dtc = DecisionTreeClassifier(max_depth=10, random_state=0) dtc.fit(X_train, y_train) y_pred = dtc.predict(X_val) print('Simple DecisionTreeClassifier accuracy:%.3f' % (accuracy_score(y_val, y_pred))) print('Simple DecisionTreeClassifier f1_score: %.3f' % (f1_score(y_val, y_pred))) print('Simple DecisionTreeClassifier roc_auc_score: %.3f' % (roc_auc_score(y_val, y_pred)))
Simple DecisionTreeClassifier accuracy:0.849 Simple DecisionTreeClassifier f1_score: 0.310 Simple DecisionTreeClassifier roc_auc_score: 0.603
4. 隨機(jī)森林
# 決策樹 rfc = RandomForestClassifier(n_estimators=100, max_depth=10, n_jobs=-1) rfc.fit(X_train, y_train) y_pred = rfc.predict(X_val) print('Simple RandomForestClassifier accuracy:%.3f' % (accuracy_score(y_val, y_pred))) print('Simple RandomForestClassifier f1_score: %.3f' % (f1_score(y_val, y_pred))) print('Simple RandomForestClassifier roc_auc_score: %.3f' % (roc_auc_score(y_val, y_pred)))
Simple RandomForestClassifier accuracy:0.870 Simple RandomForestClassifier f1_score: 0.177 Simple RandomForestClassifier roc_auc_score: 0.545
5. LightGBM
lgbm = LGBMClassifier(n_estimators=100, random_state=0) lgbm.fit(X_train, y_train) y_pred = lgbm.predict(X_val) print('Simple LGBM accuracy: %.3f' % (accuracy_score(y_val, y_pred))) print('Simple LGBM f1_score: %.3f' % (f1_score(y_val, y_pred))) print('Simple LGBM roc_auc_score: %.3f' % (roc_auc_score(y_val, y_pred)))
Simple LGBM accuracy: 0.857 Simple LGBM f1_score: 0.290 Simple LGBM roc_auc_score: 0.591
綜上,以f1-score作為評(píng)價(jià)標(biāo)準(zhǔn)的情況下,KNN算法有較好的分類效能,這可能是由于數(shù)據(jù)樣本本身不平衡導(dǎo)致,后續(xù)可以通過其他類別不平衡的方式做進(jìn)一步處理,同時(shí)可以通過參數(shù)調(diào)整的方式來優(yōu)化其他模型,通過調(diào)整預(yù)測的門檻值來增加預(yù)測效能等其他方式。
——熱門課程推薦:
想學(xué)習(xí)PYTHON數(shù)據(jù)分析與金融數(shù)字化轉(zhuǎn)型精英訓(xùn)練營,您可以點(diǎn)擊>>>“人才轉(zhuǎn)型”了解課程詳情;
想從事業(yè)務(wù)型數(shù)據(jù)分析師,您可以點(diǎn)擊>>>“數(shù)據(jù)分析師”了解課程詳情;
想從事大數(shù)據(jù)分析師,您可以點(diǎn)擊>>>“大數(shù)據(jù)就業(yè)”了解課程詳情;
想成為人工智能工程師,您可以點(diǎn)擊>>>“人工智能就業(yè)”了解課程詳情;
想了解Python數(shù)據(jù)分析,您可以點(diǎn)擊>>>“Python數(shù)據(jù)分析師”了解課程詳情;
想咨詢互聯(lián)網(wǎng)運(yùn)營,你可以點(diǎn)擊>>>“互聯(lián)網(wǎng)運(yùn)營就業(yè)班”了解課程詳情;
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對策略? 長短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場調(diào)研是企業(yè)洞察市場動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03