数据STUDIO

用Python算法预测客户行为案例

数据STUDIO转载|作者 :吴达科
这是一份kaggle上的银行的数据集,研究该数据集可以预测客户是否认购定期存款y。这里包含20个特征。

1. 分析框架

2. 数据读取,数据清洗

# 导入相关包import numpy as npimport pandas as pd # 读取数据data = pd.read_csv('./1bank-additional-full.csv')# 查看表的行列数data.shape

输出:

这里只有nr.employed这列有丢失数据,查看下:

data['nr.employed'].value_counts()

这里只有5191.0这个值,没有其他的,且只有7763条数据,这里直接将这列当做异常值,直接将这列直接删除了。

# data.drop('nr.employed', axis=1, inplace=True)

3. 探索性数据分析

3.1查看各年龄段的人数的分布

这里可以看出该银行的主要用户主要集中在23-60岁这个年龄层,其中29-39这个年龄段的人数相对其他年龄段多。

import matplotlib.pyplot as pltimport seaborn as snsplt.rcParams['font.sans-serif'] = 'SimHei'plt.figure(figsize=(20, 8), dpi=256)sns.countplot(x='age', data=data)plt.title("各年龄段的人数")

3.2 其他特征的一些分布

plt.figure(figsize=(18, 16), dpi=512)plt.subplot(221)sns.countplot(x='contact', data=data)plt.title("contact分布情况")plt.subplot(222)sns.countplot(x='day_of_week', data=data)plt.title("day_of_week分布情况")plt.subplot(223)sns.countplot(x='default', data=data)plt.title("default分布情况")plt.subplot(224)sns.countplot(x='education', data=data)plt.xticks(rotation=70)plt.title("education分布情况")plt.savefig('./1.png')
plt.figure(figsize=(18, 16), dpi=512)plt.subplot(221)sns.countplot(x='housing', data=data)plt.title("housing分布情况")plt.subplot(222)sns.countplot(x='job', data=data)plt.xticks(rotation=70)plt.title("job分布情况")plt.subplot(223)sns.countplot(x='loan', data=data)plt.title("loan分布情况")plt.subplot(224)sns.countplot(x='marital', data=data)plt.xticks(rotation=70)plt.title("marital分布情况")plt.savefig('./2.png')
plt.figure(figsize=(18, 8), dpi=512)plt.subplot(221)sns.countplot(x='month', data=data)plt.xticks(rotation=30)plt.subplot(222)sns.countplot(x='poutcome', data=data)plt.xticks(rotation=30)plt.savefig('./3.png')

3.3 各特征的相关性

plt.figure(figsize=(10, 8), dpi=256)plt.rcParams['axes.unicode_minus'] = Falsesns.heatmap(data.corr(), annot=True)plt.savefig('./4.png')

4. 特征规范化

4.1 将自变量的特征值转换成标签类型

# 特征化数据from sklearn.preprocessing import LabelEncoderfeatures = ['contact', 'day_of_week', 'default', 'education', 'housing',           'job','loan', 'marital', 'month', 'poutcome']le_x = LabelEncoder()for feature in features:    data[feature] = le_x.fit_transform(data[feature]) 

4.2 将结果y值转换成0、1

def parse_y(x):    if (x == 'no'):        return 0    else:        return 1data['y'] = data['y'].apply(parse_y)data['y'] = data['y'].astype(int)

4.3 数据规范化

# 数据规范化到正态分布的数据# 测试数据和训练数据的分割from sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitss = StandardScaler()train_x, test_x, train_y, test_y = train_test_split(data.iloc[:,:-1],                                                    data['y'],                                                    test_size=0.3)train_x = ss.fit_transform(train_x)test_x = ss.transform(test_x)

5. 模型训练

5.1 AdaBoost分类器

from sklearn.ensemble import AdaBoostClassifierfrom sklearn.metrics import accuracy_scoreada = AdaBoostClassifier()ada.fit(train_x, train_y)predict_y = ada.predict(test_x)print("准确率:", accuracy_score(test_y, predict_y))

5.2 SVC分类器

from sklearn.svm import SVCsvc = SVC()svc.fit(train_x, train_y)predict_y = svc.predict(test_x)print("准确率:", accuracy_score(test_y, predict_y))

5.3 K邻近值分类器

from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier()knn.fit(train_x, train_y)predict_y = knn.predict(test_x)print("准确率:", accuracy_score(test_y, predict_y))

5.4 决策树分类器

from sklearn.tree import DecisionTreeClassifierdtc = DecisionTreeClassifier()dtc.fit(train_x, train_y)predict_y = dtc.predict(test_x)print("准确率:", accuracy_score(test_y, predict_y))

6 模型评价

6.1 AdaBoost分类器

from sklearn.metrics import roc_curvefrom sklearn.metrics import aucplt.figure(figsize=(8,6))fpr1, tpr1, threshoulds1 = roc_curve(test_y, ada.predict(test_x))plt.stackplot(fpr1, tpr1,color='steelblue', alpha = 0.5, edgecolor = 'black')plt.plot(fpr1, tpr1, linewidth=2, color='black')plt.plot([0,1], [0,1], ls='-', color='red')plt.text(0.5, 0.4, auc(fpr1, tpr1))plt.title('AdaBoost分类器的ROC曲线')

6.2 SVC分类器

plt.figure(figsize=(8,6))fpr2, tpr2, threshoulds2 = roc_curve(test_y, svc.predict(test_x))plt.stackplot(fpr2, tpr2, alpha = 0.5)plt.plot(fpr2, tpr2, linewidth=2, color='black')plt.plot([0,1], [0,1],ls='-', color='red')plt.text(0.5, 0.4, auc(fpr2, tpr2))plt.title('SVD的ROC曲线')

6.3 K邻近值分类器

plt.figure(figsize=(8,6))fpr3, tpr3, threshoulds3 = roc_curve(test_y, knn.predict(test_x))plt.stackplot(fpr3, tpr3, alpha = 0.5)plt.plot(fpr3, tpr3, linewidth=2, color='black')plt.plot([0,1], [0,1],ls='-', color='red')plt.text(0.5, 0.4, auc(fpr3, tpr3))plt.title('K邻近值的ROC曲线')

6.4 决策树分类器

plt.figure(figsize=(8,6))fpr4, tpr4, threshoulds4 = roc_curve(test_y, dtc.predict(test_x))plt.stackplot(fpr4, tpr4, alpha = 0.5)plt.plot(fpr4, tpr4, linewidth=2, color='black')plt.plot([0,1], [0,1],ls='-', color='red')plt.text(0.5, 0.4, auc(fpr4, tpr4))plt.title('决策树的ROC曲线')
来源: https://blog.csdn.net/qq_33333002/article/details/106280462
🏴‍☠️宝藏级🏴‍☠️ 原创公众号『 数据STUDIO 』内容超级硬核。公众号以Python为核心语言,垂直于数据科学领域,包括 可戳 👉 Python | MySQL | 数据分析 | 数据可视化 | 机器学习与数据挖掘 | 爬虫 等,从入门到进阶!

长按👇关注- 数据STUDIO -设为星标,干货速递