autogluon 快速实现机器学习
分类:机器学习
from autogluon 快速实现机器学习 - 知乎 (zhihu.com)
本人最近学习autogluon来实现机器学习分类算法,现针对目前学习做一些小结,如有错误希望大家及时指正。
AutoGluon 支持易使用和易扩展的 AutoML,并专注于涵盖图像、文本或表格数据的深度学习和实际应用。AutoGluon 适用于机器学习初学者和专家,能够使他们:
- 通过几行代码即可快速地为数据构建深度学习原型方案;
- 利用自动超参数微调、模型选择/架构搜索和数据处理;
- 无需专家知识即可自动使用深度学习 SOTA 方法;
- 轻松地提升现有定制模型和数据管道,或者根据用例自定义 AutoGluon。
应用场景:
机器学习:实现机器学习中的预测问题;
图像分类:识别图像中的主要对象;
对象检测:借助图像中的边界框检测多个对象;
文本分类:基于文本内容做出预测。
安装autogluon命令:
python -m pip install -U pip
python -m pip install -U setuptools wheel
python -m pip install -U "mxnet<2.0.0"
python -m pip install autogluon
实现步骤:
第一步,需要导入一些autogluon库,来进行数据的读取和模型的预测
from autogluon.tabular import TabularDataset,TabularPredictor
#其中TabularDataset格式与pandas基本一致
第二步,导入数据及数据处理
import pandas as pd
#导入数据
df=TabularDataset('/tmp/model_v2/data/dataset.csv')
#按照时间对数据进行排序
df=df.sort_values(by='dt')
#使用均值对数据进行填充
fea=["driver_id",'order_id']
for column in fea:
mean_val=df[column].mean()
df[column].fillna(mean_val,inplace=True)
df.isnull().sum()
第三步,划分数据集(训练数据没有把label划分出的原因是autogluon训练会识别出标签)
from sklearn.model_selection import train_test_split
X=df
y=df['label']
train_x,test_x,train_y,test_y=train_test_split(X,y,test_size=0.25,random_state=0)
print(test_x.shape)
print(train_x.shape)
print(test_y.shape)
第四步,模型训练(会默认划分训练集和验证集)
predictor = TabularPredictor(label='label').fit(train_data=train_x)
训练结束会展示具体的模型文件所在位置
第五步,模型test
from sklearn.metrics import confusion_matrix,accuracy_score,recall_score,
f1_score,classification_report
test_data_t=test_x.drop(labels=['label'],axis=1)
#模型预测
predictor=TabularPredictor.load("AutogluonModels/ag-20211108_092108/")
#可以设置不同的模型,也可以不写model,默认是最优的模型
pred=predictor.predict(test_data_t,model='LightGBM')
#获取准确率、召回率、F1值
cy=confusion_matrix(pred, test_y)
print("confusion_matrix:",cy)
dc=accuracy_score(pred, test_y)
print("accuracy_score",dc)
recall=recall_score(pred, test_y)
print("recall_score",recall)
f1=f1_score(pred, test_y)
print("f1_score",f1)
第六步,新数据预测效果
import pandas as pd
from autogluon.tabular import TabularDataset,TabularPredictor
#加载模型
predictor=TabularPredictor.load("AutogluonModels/ag-20211108_092108/")
#输入数据
df_pred_1=TabularDataset("/tmp/model_v2/pred_punish_model.csv")
#缺失值填充
fea=["driver_id",'order_id']
for column in fea:
mean_val=df[column].mean()
df_pred_1[column].fillna(mean_val,inplace=True)
#预测
pred=predictor.predict(df_pred_1,model='LightGBM')
pred_data_pro=predictor.predict_proba(df_pred_1,model='LightGBM')[1]
#保存结果
df_pred_1['result']=pred
df_pred_1['prob']=pred_data_pro
#保存成csv文件
df_pred_1.to_csv("pred_1.csv",index=False)
参考资料: