2021-03-25零基础入门数据挖掘-心跳信号分类预测


TASK04模型调参

理论基础

1.1逻辑回归模型
1.2树模型
1.3集成模型
1.3.1基于bagging思想的集成模型

  • 随机森林模型
  • 随机树模型
    1.3.2基于boosting思想的集成模型
  • XGBOOST
  • LIGHTGBM
  • CATBOOST
  • Adaboost
  • GBDT

1.3.3基于stacking思想的集成模型
1.4模型对比与性能评估
1.5模型调参
1.5.1贪心调参方法
1.5.2网格调参方法
1.5.3贝叶斯调参方法

代码实现

1.导入依赖包:

import pandas as pd
import numpy as np
from sklearn.metrics import f1_score
import os
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

2.定义一个减少内存占用的函数:

def reduce_mem_usage(df):
    start_mem = df.memory_usage().sum() / 1024**2 
    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
    
    for col in df.columns:
        col_type = df[col].dtype
        
        if col_type != object:
            c_min = df[col].min()
            c_max = df[col].max()
            if str(col_type)[:3] == 'int':
                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
                    df[col] = df[col].astype(np.int8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
                    df[col] = df[col].astype(np.int16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
                    df[col] = df[col].astype(np.int32)
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
                    df[col] = df[col].astype(np.int64)  
            else:
                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
                    df[col] = df[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
                    df[col] = df[col].astype(np.float32)
                else:
                    df[col] = df[col].astype(np.float64)
        else:
            df[col] = df[col].astype('category')

    end_mem = df.memory_usage().sum() / 1024**2 
    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))
    
    return df

这其中,第三行打印中,有**{:.2f}**,这个是指这部分填写后面format(start_mem)的内容,2是指保存两位小数,f是指float类型。
另外,介绍一下:

  • np.finfo()
    finfo(dtype)
    显示float类型的机器限制。
    finfo函数是根据dtype类型来获得信息,获得符合这个类型的float型.
  • np.iinfo()
    显示整数类型的机器限制。

3.缺失值处理

data.isnull().sum().sum()
data.isnull()会让data中的缺失值为true,不缺失的为false。第一次sum()是对各个列内部求和,第二次sum是对各列的和求和。
在这里插入图片描述
输出结果为0,所以没有缺失值。
也可以用上次提到任务中的缺失值处理方法impute:

from tsfresh.utilities.dataframe_functions import impute
# 去除抽取特征中的NaN值
impute(train_features)

4.异常值处理

def deal_sigma(data):
    columns = data.columns.values
    columns = np.delete(columns,0)
    for tag in columns:
        data_mean = data[tag].mean()
        data_std = data[tag].std()
        for index,row in data.iterrows():
            if row[tag]>(data_mean+ 3 * data_std) or row[tag]<(data_mean- 3 *data_std):
                data.drop(index=index,inplace=True)
    return data

这个是按3σ法则来写的。mean是求得各列得平均值,std为各列标准值差。如果不在3σ范围内,就认为此数据为异常值并丢弃(drop)。

5.K折交叉验证

from sklearn.model_selection import KFold
X_train = data.drop(['id','label'], axis=1)
y_train = data['label']

folds = 5
seed = 2021
kf = KFold(n_splits=folds, shuffle=True, random_state=seed)

这里folds可以设置是几折,seed是随机种子。

6.f1得分

def f1_score_vali(preds, data_vali):
    labels = data_vali.get_label()
    preds = np.argmax(preds.reshape(4, -1), axis=0)
    score_vali = f1_score(y_true=labels, y_pred=preds, average='macro')
    return 'f1_score', score_vali, True

传入真实值和预测值即可算出F1得分。进而判断效果。

7.数据集划分&训练

from sklearn.model_selection import train_test_split
import lightgbm as lgb
X_train_split, X_val, y_train_split, y_val = train_test_split(X_train, y_train, test_size=0.2)
train_matrix = lgb.Dataset(X_train_split, label=y_train_split)
valid_matrix = lgb.Dataset(X_val, label=y_val)

params = {
    "learning_rate": 0.1,
    "boosting": 'gbdt',  
    "lambda_l2": 0.1,
    "max_depth": -1,
    "num_leaves": 128,
    "bagging_fraction": 0.8,
    "feature_fraction": 0.8,
    "metric": None,
    "objective": "multiclass",
    "num_class": 4,
    "nthread": 10,
    "verbose": -1,
}

"""使用训练集数据进行模型训练"""
model = lgb.train(params, 
                  train_set=train_matrix, 
                  valid_sets=valid_matrix, 
                  num_boost_round=2000, 
                  verbose_eval=50, 
                  early_stopping_rounds=200,
                  feval=f1_score_vali)

train_test_split()函数
是用来随机划分样本数据为训练集和测试集的,也可以人为的切片划分.随机客观的划分数据,减少人为因素.
参数:

  • train_data:待划分样本数据
  • train_target:待划分样本数据的结果(标签)
  • test_size:测试数据占样本数据的比例,若整数则样本数量
  • random_state:设置随机数种子,保证每次都是同一个随机数。若为0或不填,则每次得到数据都不一样

params中的参数介绍:

  • learning_rate:学习速率,默认0.1
  • lambda_l2:默认0, alias=reg_lambda L2 正则
  • boosting:默认gbdt, type=enum, options=gbdt, rf, dart, goss,
    # gbdt, 传统的梯度提升决策树
    # rf, Random Forest (随机森林)
    # dart, Dropouts meet Multiple Additive Regression Trees
    # goss, Gradient-based One-Side Sampling (基于梯度的单侧采样)
  • num_leaves: 叶子节点的数量
  • nthread: LightGBM 的线程数
  • verbose: 日志冗长度

运行结果:
在这里插入图片描述

8.对验证集预测

val_pre_lgb = model.predict(X_val, num_iteration=model.best_iteration)
preds = np.argmax(val_pre_lgb, axis=1)
score = f1_score(y_true=y_val, y_pred=preds, average='macro')
print('未调参前lightgbm单模型在验证集上的f1:{}'.format(score))

numpy.argmax(array, axis)
用于返回一个numpy数组中最大值的索引值。
当一组中同时出现几个最大值时,返回第一个最大值的索引值。
参数axis,默认是0,表示第几维的最大值.看二维的情况.
(哈哈刚好最近用到这个)
输出结果为:
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值