假设要使用xgboost预测一维数据,可以按照以下步骤进行:
1. 导入必要的包和数据
import xgboost as xgb
import numpy as np
X_train = np.array([[1.2], [2.4], [3.6], [4.8], [5.0]]) # 特征数据
y_train = np.array([2.4, 4.8, 7.2, 9.6, 10.0]) # 标签数据
2. 创建DMatrix对象并进行训练
data_train = xgb.DMatrix(X_train, label=y_train) # 创建DMatrix对象
param = {'max_depth': 3, 'eta': 0.3, 'objective': 'reg:squarederror'} # 设置参数
num_round = 10 # 迭代次数
model = xgb.train(param, data_train, num_round) # 进行训练
3. 进行预测
X_test = np.array([[6.3]]) # 待预测数据
data_test = xgb.DMatrix(X_test) # 创建DMatrix对象
y_pred = model.predict(data_test) # 进行预测
print(y_pred) # 输出预测结果
完整代码如下:
import xgboost as xgb
import numpy as np
X_train = np.array([[1.2], [2.4], [3.6], [4.8], [5.0]])
y_train = np.array([2.4, 4.8, 7.2, 9.6, 10.0])
data_train = xgb.DMatrix(X_train, label=y_train)
param = {'max_depth': 3, 'eta': 0.3, 'objective': 'reg:squarederror'}
num_round = 10
model = xgb.train(param, data_train, num_round)
X_test = np.array([[6.3]])
data_test = xgb.DMatrix(X_test)
y_pred = model.predict(data_test)
print(y_pred)
|