心跳信号分类---(上)

​ ”明月如霜,好风如水,清景无限 “

为了能打上卡,文远硬冲了一手,没来得及认真看程序,不过也记录一下。来分析一下baseline。

天池心跳分类

首先是读取数据就不说了,数据的特色就是输入为序列数据,所以最好还是做一下处理,用split(’,’)来分割一下。

for i in range(1000):
    dd.iloc[i,:] = train.values[i][1].split(',')
dd

再看一下输出label。
在这里插入图片描述
再看看这个标签为1(八成有问题)的心跳序列:
在这里插入图片描述
看起来,波动的很剧烈啊,这个心跳数据应该是归一化了。

下面是数据预处理:

首先的经典地方就是,通过类型转换来减小内存,还是很值得模仿的。

def reduce_mem_usage(df):  ###类型转化,减少内存(下面是重点代码)
        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')

在这里插入图片描述
看下这个可以一说的地方:

x_train = train.drop(['id','label'], axis=1)
y_train = train['label']
x_test=test.drop(['id'], axis=1)

对于df数据的增删操作,与数组不同,并不会对原数据生效,直接重新赋值才会生效。
也就是说这样,才会改变原df:

train = train.drop(['id','label'], axis=1)

模型训练:

def abs_sum(y_pre,y_tru):
    y_pre=np.array(y_pre)
    y_tru=np.array(y_tru)
    loss=sum(sum(abs(y_pre-y_tru))) ## AE
    return loss

这里还是值得思考的,这是个分类问题,所以这种定义还是挺好的。如果是回归问题,一般用MSE或者RMSE还是比较多。

def cv_model(clf, train_x, train_y, test_x, clf_name):
    folds = 5
    seed = 2021
    kf = KFold(n_splits=folds, shuffle=True, random_state=seed)
    test = np.zeros((test_x.shape[0],4))
​
    cv_scores = []
    onehot_encoder = OneHotEncoder(sparse=False)
    for i, (train_index, valid_index) in enumerate(kf.split(train_x, train_y)):
        print('************************************ {} ************************************'.format(str(i+1)))
        trn_x, trn_y, val_x, val_y = train_x.iloc[train_index], train_y[train_index], train_x.iloc[valid_index], train_y[valid_index]
        
        if clf_name == "lgb":
            train_matrix = clf.Dataset(trn_x, label=trn_y)
            valid_matrix = clf.Dataset(val_x, label=val_y)
​
            params = {
                'boosting_type': 'gbdt',
                'objective': 'multiclass',
                'num_class': 4,
                'num_leaves': 2 ** 5,
                'feature_fraction': 0.8,
                'bagging_fraction': 0.8,
                'bagging_freq': 4,
                'learning_rate': 0.1,
                'seed': seed,
                'nthread': 28,
                'n_jobs':24,
                'verbose': -1,
            }
​
            model = clf.train(params, 
                      train_set=train_matrix, 
                      valid_sets=valid_matrix, 
                      num_boost_round=2000, 
                      verbose_eval=100, 
                      early_stopping_rounds=200)
            val_pred = model.predict(val_x, num_iteration=model.best_iteration)
            test_pred = model.predict(test_x, num_iteration=model.best_iteration) 
            
        val_y=np.array(val_y).reshape(-1, 1)
        
        val_y = onehot_encoder.fit_transform(val_y)print('预测的概率矩阵为:')
        print(test_pred)
        test += test_pred
        score=abs_sum(val_y, val_pred)
        cv_scores.append(score)
        print(cv_scores)
    print("%s_scotrainre_list:" % clf_name, cv_scores)
    print("%s_score_mean:" % clf_name, np.mean(cv_scores))
    print("%s_score_std:" % clf_name, np.std(cv_scores))
    test=test/kf.n_splits
​
    return test
    
def lgb_model(x_train, y_train, x_test):
    lgb_test = cv_model(lgb, x_train, y_train, x_test, "lgb")
    return lgb_test
    
lgb_test = lgb_model(x_train, y_train, x_test)

这个代码里,可以说的地方有:OneHotEncoder编码,clf_name == “lgb” 模型为lightgbm,然后是params 参数优化,可以尝试下网格搜索或者是随机搜索,最后就是交叉验证的调整。

最后的输出结果提交的时候,记得把小数的都调整成0和1。当然验证是发现:
在这里插入图片描述
也就是说分类第0类到第3类都不是。好了最后记录一下天池的cdw安装第三方库的操作:

!pip install catboost

文章对你有帮助的话,记得点赞并将公众号设置成星标哦。源码

END

作者:不爱跑马的影迷不是好程序猿

   喜欢的话请关注点赞? ?? ?                     

图片

壹句: 北山移文


版权声明:本文为john_ashley原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。