构建数据的归一化和标准化(某金融数据集)

导入各种包

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score,roc_auc_score,roc_curve,auc
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from sklearn.linear_model import LogisticRegression
from  sklearn import svm
from sklearn.tree import DecisionTreeClassifier

导入数据

data=pd.read_csv('./data.csv',index_col=0,encoding='gbk')

数据理解

#单独提取出y列标签,和其余的88列标记为x
y=data['status']
X=data.drop('status',axis=1)
#X值的行列数,以及y的分布类型
print('X.shape:',X.shape)
print('y的分布:',y.value_counts())
X.shape: (4754, 88)
y的分布: 0    3561
1    1193
Name: status, dtype: int64

数据准备(添加数据标准化或归一化)

#首先剔除一些明显无用的特征,如id_name,custid,trade_no,bank_card_no
X.drop(['id_name','custid','trade_no','bank_card_no'],axis=1,inplace=True)
print(X.shape)
#选取数值型特征
X_num=X.select_dtypes('number').copy()
print(X_num.shape)
type(X_num.mean())
#使用均值填充缺失值
X_num.fillna(X_num.mean(),inplace=True)
#观察数值型以外的变量
X_str=X.select_dtypes(exclude='number').copy()
X_str.describe()
#把reg_preference用虚拟变量代替,其它三个变量删除
X_str['reg_preference_for_trad'] = X_str['reg_preference_for_trad'].fillna(X_str['reg_preference_for_trad'].mode()[0])
X_str_dummy = pd.get_dummies(X_str['reg_preference_for_trad'])
X_str_dummy.head()
#合并数值型变量和名义型(字符型)变量
X_cl = pd.concat([X_num,X_str_dummy],axis=1,sort=False)
#X_cl.shape
X_cl.head()
"""
#数据标准化和归一化
from sklearn import preprocessing
min_max_scale = preprocessing.MinMaxScaler()
min_max_data = min_max_scale.fit_transform(X_cl)
"""
from sklearn import preprocessing
X_cl = preprocessing.scale(X_cl)

(4754, 84)
(4754, 80)
#以三七比例分割训练集和测试集
random_state = 1118
X_train,X_test,y_train,y_test = train_test_split(X_cl,y,test_size=0.3,random_state=1118)
print(X_train.shape)
print(X_test.shape)

"""
#建立xgboost模型
xgboost_model=XGBClassifier()
xgboost_model.fit(X_train,y_train)

#用建立好的xgboost模型运用到训练集和测试集上,进行预测
y_train_pred = xgboost_model.predict(X_train)
y_test_pred = xgboost_model.predict(X_test)



#建立逻辑回归模型
lr = LogisticRegression(C=0.09,random_state=0,penalty='l1')
lr.fit(X_train, y_train)
#用建立好的lr模型运用到训练集和测试集上,进行预测
y_train_pred = lr.predict(X_train)
y_test_pred = lr.predict(X_test)
"""
Lin_SVC = svm.SVC(probability=True)
Lin_SVC.fit(X_train,y_train)
    
y_train_pred = Lin_SVC.predict(X_train)
y_test_pred = Lin_SVC.predict(X_test)





(3327, 85)
(1427, 85)

模型评估

print('训练集:{:.4f}'.format(roc_auc_score(y_train, y_train_pred)))
print('测试集:{:.4f}'.format(roc_auc_score(y_test, y_test_pred)))
训练集:1.0000
测试集:0.5000

总结:数据的归一化对模型效果是有影响的,其中lr有提升,xgboost反而下降了一点(可能是树模型自身对归一化不敏感),svm在没有归一化时AUC始终为0.5,归一化后效果变好。
问题:尝试lr模型惩罚函数用默认值l2,在不做数据归一化时,效果很差,训练集和测试集auc都=0.5,不知道为什么。改成l1是否做归一化,影响就不大了。

猜你喜欢

转载自blog.csdn.net/qq_41205464/article/details/84348766