前言:
非常感谢Datawhale AI夏令营能给我一个接触超多大佬的机会,能够让我和小伙伴们一起学习一起进步,通过这次学习,了解到了,我之前一直接触却从未留意到的很多知识。
学习收获:
收获了很多,首先是知道了当数据量过大时,应该运用h5存储和组织大量数据的文件格式,而后通过免费的阿里服务器,比如v100,A10进行训练任务(虽然不是很快,但是已经很不错了),然后通过常规的机器学习步骤进行训练
1.导入模块
2.数据探索
3.数据清洗
4.特征工程
5.模型训练与验证
6.结果输出
让我感触最深的是特征优化(通俗来讲就是寻找最好的特征)和模型融合(字面理解就是把很多模型融合到一块),在之前这两个概念对我来说并不是很熟悉(实在是惭愧),通过学习了解明白了一些,下面是datawhale夏令营的学习手册(我觉得非常不错,即简洁又易懂)
模型融合
def cv_model(clf, train_x, train_y, test_x, clf_name, seed = 2023):
'''
clf:调用模型
train_x:训练数据
train_y:训练数据对应标签
test_x:测试数据
clf_name:选择使用模型名
seed:随机种子
'''
folds = 5
kf = KFold(n_splits=folds, shuffle=True, random_state=seed)
oof = np.zeros(train_x.shape[0])
test_predict = np.zeros(test_x.shape[0])
cv_scores = []
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': 'regression',
'metric': 'mae',
'min_child_weight': 6,
'num_leaves': 2 ** 6,
'lambda_l2': 10,
'feature_fraction': 0.8,
'bagging_fraction': 0.8,
'bagging_freq': 4,
'learning_rate': 0.1,
'seed': 2023,
'nthread' : 16,
'verbose' : -1,
}
model = clf.train(params, train_matrix, 2000, valid_sets=[train_matrix, valid_matrix],
categorical_feature=[], verbose_eval=200, early_stopping_rounds=100)
val_pred = model.predict(val_x, num_iteration=model.best_iteration)
test_pred = model.predict(test_x, num_iteration=model.best_iteration)
if clf_name == "xgb":
xgb_params = {
'booster': 'gbtree',
'objective': 'reg:squarederror',
'eval_metric': 'mae',
'max_depth': 5,
'lambda': 10,
'subsample': 0.7,
'colsample_bytree': 0.7,
'colsample_bylevel': 0.7,
'eta': 0.1,
'tree_method': 'hist',
'seed': 520,
'nthread': 16
}
train_matrix = clf.DMatrix(trn_x , label=trn_y)
valid_matrix = clf.DMatrix(val_x , label=val_y)
test_matrix = clf.DMatrix(test_x)
watchlist = [(train_matrix, 'train'),(valid_matrix, 'eval')]
model = clf.train(xgb_params, train_matrix, num_boost_round=2000, evals=watchlist, verbose_eval=200, early_stopping_rounds=100)
val_pred = model.predict(valid_matrix)
test_pred = model.predict(test_matrix)
if clf_name == "cat":
params = {'learning_rate': 0.1, 'depth': 5, 'bootstrap_type':'Bernoulli','random_seed':2023,
'od_type': 'Iter', 'od_wait': 100, 'random_seed': 11, 'allow_writing_files': False}
model = clf(iterations=2000, **params)
model.fit(trn_x, trn_y, eval_set=(val_x, val_y),
metric_period=200,
use_best_model=True,
cat_features=[],
verbose=1)
val_pred = model.predict(val_x)
test_pred = model.predict(test_x)
oof[valid_index] = val_pred
test_predict += test_pred / kf.n_splits
score = mean_absolute_error(val_y, val_pred)
cv_scores.append(score)
print(cv_scores)
return oof, test_predict
# 选择lightgbm模型
lgb_oof, lgb_test = cv_model(lgb, traindata[cols], traindata['label'], testdata[cols], 'lgb')
# 选择xgboost模型
xgb_oof, xgb_test = cv_model(xgb, traindata[cols], traindata['label'], testdata[cols], 'xgb')
# 选择catboost模型
cat_oof, cat_test = cv_model(CatBoostRegressor, traindata[cols], traindata['label'], testdata[cols], 'cat')
# 进行取平均融合
final_test = (lgb_test + xgb_test + cat_test) / 3
stacking代码示例
def stack_model(oof_1, oof_2, oof_3, predictions_1, predictions_2, predictions_3, y):
'''
输入的oof_1, oof_2, oof_3可以对应lgb_oof,xgb_oof,cat_oof
predictions_1, predictions_2, predictions_3对应lgb_test,xgb_test,cat_test
'''
train_stack = pd.concat([oof_1, oof_2, oof_3], axis=1)
test_stack = pd.concat([predictions_1, predictions_2, predictions_3], axis=1)
oof = np.zeros((train_stack.shape[0],))
predictions = np.zeros((test_stack.shape[0],))
scores = []
from sklearn.model_selection import RepeatedKFold
folds = RepeatedKFold(n_splits=5, n_repeats=2, random_state=2021)
for fold_, (trn_idx, val_idx) in enumerate(folds.split(train_stack, train_stack)):
print("fold n°{}".format(fold_+1))
trn_data, trn_y = train_stack.loc[trn_idx], y[trn_idx]
val_data, val_y = train_stack.loc[val_idx], y[val_idx]
clf = Ridge(random_state=2021)
clf.fit(trn_data, trn_y)
oof[val_idx] = clf.predict(val_data)
predictions += clf.predict(test_stack) / (5 * 2)
score_single = mean_absolute_error(val_y, oof[val_idx])
scores.append(score_single)
print(f'{fold_+1}/{5}', score_single)
print('mean: ',np.mean(scores))
return oof, predictions
stack_oof, stack_pred = stack_model(lgb_oof, xgb_oof, cat_oof, lgb_test, xgb_test, cat_test, traindata['age'])
最终成绩:
学习感悟:
我的感悟就是学习是一个长久的过程,只有坚持不懈,才能走的更远,人外有人,天外有天,哪里都有更强的人存在,而这些人是我们终生追赶的目标。
学习链接:
【竞赛官网】
首届世界科学智能大赛:生命科学赛道——生物学年龄评价与年龄相关疾病风险预测_算法大赛_天池大赛-阿里云天池
【学习教程】
DocsAI夏令营第三期 - 生物学年龄评价与年龄相关疾病风险预测教程 - 飞书云文档 (feishu.cn)Docs
【学习者手册】
Docs (feishu.cn)《AI夏令营(第三期) - AI for Science 生命科学赛道》学习手册 - 飞书云文档 (feishu.cn)Docs (feishu.cn)
【问题库】
DocsAI for Science 赛道问题库 - 飞书云文档 (feishu.cn)Docs
【快速体验竞赛全流程】
阿里云云环境,具体部署教程如下:
阿里云DSW环境部署教程 - 飞书云文档 (feishu.cn)
【baseline 视频教程】
生物学年龄评价与年龄相关疾病风险预测视频演示 - 飞书云文档 (feishu.cn)
EDA(探索性数据分析)生命科学相关数据
1.全部流程
1.载入数据
import pandas as pd
# 读取前10行数据
#测试集
data_test = pd.read_csv(r'D:\work\aliyun\ai4bio_testset_final\ai4bio_testset_final\testdata.csv', nrows=10)
map_test = pd.read_csv(r'D:\work\aliyun\ai4bio_testset_final\ai4bio_testset_final\testmap.csv', nrows=10)
#训练集
data_train = pd.read_csv(r'D:\work\aliyun\ai4bio_trainset\traindata.csv', nrows=10)
map_train = pd.read_csv(r'D:\work\aliyun\ai4bio_trainset\trainmap.csv', nrows=10)
print(data_test)
print(map_test)
print(data_trian)
print(map_train)
2.查看数据
info()函数显示数据集的相关信息,包括列名、数据类型、非空值的数量以及每列的内存使用情况等
查看数据集的基本信息,并了解每个列的数据类型和缺失值情况
data_train.info()
data_test.info()
map_train.info()
map_test.info()
describle()函数生成一个包含数据集的统计信息的摘要。统计摘要通常包括每列的计数、平均值、标准差、最小值、25%分位数、中位数、75%分位数和最大值等。
注:如果数据集中包含非数值列,describe()
方法将只返回数值列的统计信息。
data_train.describe()
data_test.describe()
map_train.describe()
map_test.describe()