首页 > 解决方案 > 使用带有 numpy 的 XGBoost 的转换错误

问题描述

但是,当我想使用 numpy 数据和具有相同形状的标签创建模型时,我想在 Python 中使用包 XGboost。

之后:

如果我运行以下代码,应该可以工作:

 xg_reg = xgb.XGBRegressor(objective ='reg:linear', colsample_bytree = 0.3, learning_rate = 0.1,
                max_depth = 5, alpha = 10, n_estimators = 10)
 xg_reg.fit(xgb.DMatrix(X),y)

我收到此错误:

TypeError: Not supported type for data.<class 'xgboost.core.DMatrix'>

X 和 y 都有这个内容:

array([[41.4049364,  2.177356 ],
       [41.4049656,  2.1773926],
       [41.4049938,  2.1774287],
       [41.4050204,  2.1774638],
       [41.4050453,  2.1774975],
       [41.4050682,  2.1775296],
       [41.4050895,  2.1775597],
       [41.4051093,  2.1775874],
       [41.4051278,  2.1776125]])

更新:

如果使用

xg_reg.fit(X,y)

然后:

~\anaconda3\lib\site-packages\xgboost\data.py in _validate_meta_shape(data)
    615 def _validate_meta_shape(data):
    616     if hasattr(data, 'shape'):
--> 617         assert len(data.shape) == 1 or (
    618             len(data.shape) == 2 and
    619             (data.shape[1] == 0 or data.shape[1] == 1))

AssertionError: 

有什么线索吗?

标签: pythonnumpymatrixxgboost

解决方案


xg_reg = xgb.XGBRegressor(..) xg_reg.fit(xgb.DMatrix(X),y)

您正在尝试通过xgb.DMatrix不知道它的 Scikit-Learn API 传递数据矩阵类型。

如果您使用的是低级 XGBoost API,那么您需要根据 XGBoost 约定准备和呈现数据(例如,数据必须呈现为zgb.DMatrix)。但是,当您使用高级 XGBoost API(例如 Scikit-Learn API)时,您需要根据 Scikit-Learn 约定(例如 Numpy 数组、Pandas DataFrames)准备和呈现数据。

要解决问题,只需执行xg_reg.fit(X,y). 该类XGBRegressor将在内部创建一个适当的xgb.DMatrix实例,它不需要您的帮助。


推荐阅读