竞赛实战--天池金融风控分类问题

news/2024/11/10 13:40:32/

背景

1、金融风控分类问题,作为机器学习竞赛是一个比较好的选择
2、如何进行数据处理

代码

数据分析部分

#!/usr/bin/env python
# coding: utf-8import os
import gc
import numpy as np
import pandas as pd
import warnings
import lightgbm as lgb
import catboost as cbt
import xgboost as xgb
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, KFold, train_test_split, GridSearchCV
from sklearn.preprocessing import LabelEncoder, StandardScaler
from tqdm import tqdm
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import kstestwarnings.filterwarnings("ignore")
pd.set_option('display.max_columns', None)
# plt.ion()

# ## 导入数据
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_PATH = os.path.join(BASE_DIR, 'data')train_data_file = os.path.join(DATA_PATH, "train.csv")
train_data = pd.read_csv(train_data_file)test_data_file = os.path.join(DATA_PATH, "testA.csv")
test_data = pd.read_csv(test_data_file)target = train_data['isDefault']
train_data = train_data.drop(['isDefault'], axis=1)data = pd.concat([train_data, test_data])objectList = [i for i in train_data.columns if train_data[i].dtype == 'O']
classList = [i for i in train_data.select_dtypes(exclude=['object']).columns if len(train_data[i].unique()) <= 10]
numericalList = [i for i in train_data.select_dtypes(exclude=['object']).columns if i not in classList]

对不同类型变量进行分类分组处理

# ## 变量分类和缺失值处理
info = pd.DataFrame(data.isnull().sum())
info = info[info[0] != 0]
miss_fea = info.indexmiss_objectList = [i for i in miss_fea if i in objectList]
miss_classList = [i for i in miss_fea if i in classList]
miss_numericalList = [i for i in miss_fea if i in numericalList]# 填补缺失值
data['employmentLength'] = data['employmentLength'].fillna(0)
data['n11'] = data['n11'].fillna(0)
data['n12'] = data['n12'].fillna(0)
data['employmentTitle'] = data['employmentTitle'].fillna(data['employmentTitle'].mode()[0])
data['postCode'] = data['postCode'].fillna(data['postCode'].mode()[0])
data['dti'] = data['dti'].fillna(data['postCode'].mean())
data['pubRecBankruptcies'] = data['pubRecBankruptcies'].fillna(data['pubRecBankruptcies'].mean())
data['revolUtil'] = data['revolUtil'].fillna(data['revolUtil'].mean())
data['title'] = data['title'].fillna(data['title'].mode()[0])NoNameList = [i for i in miss_numericalList if i.startswith("n")]
for i in NoNameList:data[i] = data[i].fillna(data[i].mode()[0])# ## object 变量处理
data['employmentLength'].replace({'10+ years': '10 years', '< 1 year': '0 years', '0': '0 years'}, inplace=True)
data['employmentLength'] = data['employmentLength'].apply(lambda s: int(str(s).split()[0]) if pd.notnull(s) else s)data['earliesCreditLine'] = data['earliesCreditLine'].apply(lambda s: int(s[-4:]))
data = data.drop(['issueDate'], axis=1)le = LabelEncoder()
data['grade'] = le.fit_transform(data['grade'])
data['subGrade'] = le.fit_transform(data['subGrade'])# 删除不需要的列
dropList = ['id', 'ficoRangeHigh', 'applicationType', 'policyCode', 'n3', 'n11', 'n12', 'n13']
data.drop(dropList, axis=1, inplace=True)train_data = data[:800000]
# 将target和train_data进行重新拼接
train_data['isDefault']=target
test_data = data[800000:]
print("Divide data.")
# # ## 异常值处理
# percentile = pd.DataFrame()
# numList = [i for i in train_data.columns if i not in classList]# # 正态分布检测
# for i in numList:
#     print(kstest(data[i], 'norm', (data[i].mean(), data[i].std())))# # 异常值处理
# stdsc = StandardScaler()
# for i in numList:
#     new_i = "zheng_" + i
#     train_data[new_i] = stdsc.fit_transform(train_data[i].values.reshape(-1, 1))
#     data_std = np.std(train_data[new_i])
#     data_mean = np.mean(train_data[new_i])
#     outliers_cut_off = data_std * 3
#     lower_rule = data_mean - outliers_cut_off
#     upper_rule = data_mean + outliers_cut_off
#     train_data = train_data[(train_data[new_i] < upper_rule) & (train_data[new_i] > lower_rule)]
# train_data = train_data.iloc[:, :38]

保存数据,在部分情况下由于数据体量过大,保存中间数据有助于后续处理。

FEATURE_PATH = os.path.join(BASE_DIR, 'feature')
feature_train_data = os.path.join(FEATURE_PATH, 'train_data.csv')
feature_test_data = os.path.join(FEATURE_PATH, 'test_data.csv')
train_data.to_csv(feature_train_data,index=0)
test_data.to_csv(feature_test_data,index=0)

模型搭建部分

# 定义模型训练函数
def train_model(x_train, y_train, test_data, params, n_splits=5):skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=2019)oof = np.zeros(len(x_train))predictions = np.zeros((len(test_data), n_splits))for fold_, (train_idx, valid_idx) in enumerate(skf.split(x_train, y_train)):print(f"\nFold {fold_ + 1}")x_tr, x_val = x_train.iloc[train_idx], x_train.iloc[valid_idx]y_tr, y_val = y_train.iloc[train_idx], y_train.iloc[valid_idx]train_set = lgb.Dataset(x_tr, label=y_tr)val_set = lgb.Dataset(x_val, label=y_val)clf = lgb.train(params, train_set, 5000, valid_sets=[val_set], verbose_eval=250, early_stopping_rounds=50)oof[valid_idx] = clf.predict(x_val, num_iteration=clf.best_iteration)predictions[:, fold_] = clf.predict(test_data, num_iteration=clf.best_iteration)print("\n\nCV AUC: {:<0.4f}".format(roc_auc_score(y_train, oof)))return oof, predictions# 训练模型并生成预测
oof, predictions = train_model(x_train_gbdt, y_train_gbdt, x_test_bgdt, default_params)

参考资料


http://www.ppmy.cn/news/1520420.html

相关文章

fastapi接口里日志重复写,用metaclass 单例模式解决了

遇到这个妖 我用fastapi写接口&#xff0c;打印日志用我自定义的日志类&#xff0c;但只要是fastapi 接口[即注解app.get(‘/’) 或者 app.post(‘/’) ] 之内打印的都是两遍&#xff0c;其他地方都是正常。这我很费解。说是我日志类的问题吧&#xff0c;我这类放其他地方都好…

OceanBase性能相关

**OceanBase 关于SQL监控与执行计划记录**记录来源&#xff1a;(OceanBase)DBA 从入门到实践 一、慢SQL与性能视图 慢SQL参数说明&#xff1a; V3.2.3前 trace_log_slow_query_watermark 默认是 100ms。 V3.2.3及后续 trace_log_slow_query_watermark 默认是 1s。慢SQL性能查看…

【贪心算法】区间类算法题(整数替换、俄罗斯套娃、重构字符串等、C++)

文章目录 1. 前言2. 算法题1.整数替换2.俄罗斯套娃信封问题3.可被三整除的最大和4.距离相等的条形码5.重构字符串 1. 前言 贪心算法&#xff08;Greedy Algorithm&#xff09;是一种在每一步选择中都采取当前状态下最优决策的算法。贪心算法通常用来解决最优化问题&#xff0c…

惠中科技光伏清洗剂:科技创新引领绿色清洁新风尚

惠中科技光伏清洗剂&#xff1a;科技创新引领绿色清洁新风尚 在光伏产业蓬勃发展的今天&#xff0c;光伏板的清洁问题日益凸显&#xff0c;成为影响发电效率的关键因素之一。面对传统清洗方法效率低、成本高、环境影响大等痛点&#xff0c;惠中科技以科技创新为驱动&#xff0…

Spring 源码解读:自定义依赖注入机制与其核心原理

引言 依赖注入&#xff08;Dependency Injection, DI&#xff09;是现代软件开发中的一个关键概念&#xff0c;特别是在Spring框架中&#xff0c;它被广泛应用来解耦组件之间的依赖关系。通过这种设计模式&#xff0c;开发者能够创建更加灵活和可维护的系统。这篇文章将带你深…

uni-app支持Vue 3的组件库推荐几个

uni-app支持Vue 3的组件库有多个&#xff0c;这些组件库为开发者提供了丰富的UI组件和工具&#xff0c;帮助开发者快速构建多端应用。以下是一些支持Vue 3的uni-app组件库&#xff1a; iui Design&#xff1a; 简介&#xff1a;iui Design是一款专为uni-app框架打造的Vue3 UI组…

win10使用系统自带照片查看器的步骤

1、按【winr】组合快捷键&#xff0c;输入&#xff1a;regedit&#xff0c;打开注册表 2、依次点击展开&#xff1a;HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Photo Viewer\Capabilities\FileAssociations 3、在FileAssociations项的右侧窗口&#xff0c;右击选择【新建…

将一个结构体的地址传入给一个函数,这个函数将此结构体的地址传给另一个函数,为什么跑不起来,原因尽然是……

1.test函数 void testInitList(SL* sl) {//SL sl;//在创建结构体对象的时候就把这个结构体的地址定下来了&#xff0c;要改变其内部&#xff0c;需传递地址SQLinitList(sl);//无敌之精华&#xff0c;写入csdn }void test_pushback() {SL sl;//SQLinitList(&sl);testInitLi…