摘要
本文演示如何在DataWorks中通过PyODPS3类型节点调用XGBoost算法实现模型训练与测试,进而实现算法的周期离线调度。
操作步骤
1、ODPS SQL构建数据集
-- 创建表 CREATE TABLE IF NOT EXISTS xgboost_sample ( f1 DOUBLE COMMENT '特征1', f2 DOUBLE COMMENT '特征2', label BIGINT COMMENT '标签' ); -- 插入示例数据(10组) INSERT INTO xgboost_sample VALUES (0.1, 0.2, 0), (0.2, 0.3, 0), (0.3, 0.4, 0), (0.4, 0.5, 0), (0.5, 0.6, 1), (0.6, 0.7, 1), (0.7, 0.8, 1), (0.8, 0.9, 1), (0.9, 1.0, 1), (1.0, 1.1, 1); SELECT * from xgboost_sample;
2、创建PyODPS3节点
'''PyODPS 3 请确保不要使用从 MaxCompute下载数据来处理。下载数据操作常包括Table/Instance的open_reader以及 DataFrame的to_pandas方法。 推荐使用 PyODPS DataFrame(从 MaxCompute 表创建)和MaxCompute SQL来处理数据。 更详细的内容可以参考:https://help.aliyun.com/document_detail/90481.html ''' from xgboost import XGBClassifier from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from odps import ODPS, options import numpy as np import pandas as pd from odps import ODPS import os import sys od = o.as_account("******","******") iris = DataFrame(od.get_table('xgboost_sample')) print(iris) # 提取特征列 X_train = iris[['f1', 'f2']].to_pandas() # 得到一个形状为 (10, 2) 的 NumPy 数组 # 提取标签列 y_train = iris['label'].to_pandas() # 得到一个形状为 (10,) 的一维数组 # # create model instance bst = XGBClassifier(n_estimators=2, max_depth=2, learning_rate=1, objective='binary:logistic') # # fit model bst.fit(X_train, y_train) print(X_train) # make predictions # 构造 DataFrame input_data = pd.DataFrame([[0.1, 0.2]], columns=['f1', 'f2']) preds = bst.predict(input_data) print("*"*100) print(preds) print("*"*100)
3、创建自定义镜像
默认资源组并未安装XGBoost算法,如果要运行必须使用基于官方镜像且支持PyODPS3任务类型的官方镜像构建自定义镜像。
4、测试运行(选择对应的镜像)