一、数据集

本数据集依旧开源,友友们可自行获取练习。

通过网盘分享的文件:银行数据分析
链接: https://pan.baidu.com/s/1jddVOCNV7YKVWUXdEPWtbg 提取码: ixyq

二、数据分析

(一)简单查看数据

import numpy as np
import sklearn
import pandas as pd
df_bank = pd.read_csv("BankCustomer.csv")

print(df_bank.head(10))

(二)简单可视化数据

import matplotlib.pyplot as plt
import seaborn as sns

features = ['City','Gender','Age','Tenure','ProductsNo','HasCard','ActiveMember','Exited']

fig = plt.subplots(figsize=(15,15))
for i ,j in enumerate(features):
    plt.subplot(4, 2, i+1)
    plt.subplots_adjust(hspace = 1.0)
    sns.countplot(x=j,data = df_bank)
    plt.title("NO. of costuumers")

(三)数据处理

df_bank['Gender'].replace("Female",0,inplace = True)

df_bank['Gender'].replace("Male",1,inplace=True)
print("Gender unique values",df_bank["Gender"].unique())

d_city = pd.get_dummies(df_bank['City'], prefix = "City")
df_bank = [df_bank, d_city]
df_bank = pd.concat(df_bank, axis = 1)
y = df_bank['Exited']
x = df_bank.drop(['Name','Exited','City'], axis=1)
x.head()

三、训练模型

from sklearn.model_selection import train_test_split

X_train,X_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=6)

from sklearn.linear_model import LogisticRegression

lr = LogisticRegression()

history = lr.fit(X_train, y_train)

print("逻辑回归测试集准确率{:.2f}%".format(lr.score(X_test,y_test)*100))
import tensorflow.keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

ann = Sequential()
ann.add(Dense(units=12, input_dim=12, activation='relu'))
ann.add(Dense(units=24, activation='relu'))
ann.add(Dense(units=1, activation='sigmoid'))
ann.summary()

ann.compile(optimizer = "adam",loss="binary_crossentropy",metrics=['acc'])

# 查看每一列的数据类型
print(X_train.dtypes)

# 查看数组底层类型
print(X_train.values.dtype)

这里可以看出数据集有OBJECT类型的数据,ann模型训练是不支持这个类型的,所以要先转换一下数据集。

import pandas as pd
from sklearn.preprocessing import LabelEncoder

# 找出所有object类型列
cat_cols = X_train.select_dtypes(include=['object']).columns

le = LabelEncoder()
for col in cat_cols:
    X_train[col] = le.fit_transform(X_train[col])
    X_test[col] = le.transform(X_test[col])

# 转成numpy float数组
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
y_train = y_train.astype('float32')
y_test = y_test.astype('float32')

history = ann.fit(X_train,y_train,epochs=30,batch_size=64,validation_data=(X_train,y_train))

四、数据可视化

def show_history(history):
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    epochs = range(1, len(loss) + 1)
    plt.figure(figsize=(12, 4))
    plt.subplot(1, 2, 1)
    plt.plot(epochs, loss, 'bo', label='Training loss')
    plt.plot(epochs, val_loss, 'b', label='Validation loss')
    plt.title('Training and validation loss')
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.legend()
    acc = history.history['acc']
    val_acc = history.history['val_acc']
    plt.subplot(1, 2, 2)
    plt.plot(epochs, acc, 'bo', label='Training acc')
    plt.plot(epochs, val_acc, 'b', label='Validation acc')
    plt.title('Training and validation accuracy')
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.legend()
    plt.show()
show_history(history) 

y_pred = ann.predict(X_test,batch_size=10)
y_pred = np.round(y_pred)

from sklearn.metrics import classification_report 
def show_report(X_test, y_test, y_pred):
    if y_test.shape != (2000,1):
        y_test = y_test.values
        y_test = y_test.reshape((len(y_test),1))
    print(classification_report(y_test,y_pred,labels=[0, 1]))

import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, classification_report

def show_report(X_test, y_test, y_pred):
    print(classification_report(y_test, y_pred))

def show_matrix(y_test, y_pred):
    cm = confusion_matrix(y_test, y_pred)
    plt.figure(figsize=(6,4))
    sns.heatmap(cm, annot=True, fmt="d", cmap="Blues")
    plt.xlabel("Predicted")
    plt.ylabel("Actual")
    plt.title("Confusion Matrix")
    plt.show()

show_report(X_test, y_test, y_pred)
show_matrix(y_test, y_pred)

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐