gpt4 book ai didi

python - 无法根据 ('float64' 将数组数据从 dtype ('int32' ) 转换为 dtype 'safe' )

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:45 25 4
gpt4 key购买 nike

我有一个包含 6 列的数据集“体重”(float)、“性别”(0 或 1 (int))、“高度”(float)、“代谢”(0,1,2,3 ( int))、“Psychology”(0,1,2,3,4,5,6 (int)),我们必须预测的列是“Age”(int)。我必须使用 sklearn 的 VotingClassifier 来完成此操作。在应用 one-hot-encoding 后,我以这种方式分割数据。

X_train, X_test, y_train, y_test = train_test_split(X_hot, y, test_size=0.25, random_state=1)

我使用这 4 种算法作为分类器。

gbm = GradientBoostingRegressor(loss='huber',n_estimators=5000,max_features="sqrt",subsample=0.9)
gbm.fit(X = X_train,y = np.log1p(y_train))

ada = AdaBoostClassifier(n_estimators=2000)
ada.fit(X = X_train,y = y_train)

log_reg = LogisticRegression()
log_reg.fit(X_train, y_train)

还有knn。现在,这部分工作完美

from sklearn.ensemble import VotingClassifier
estimators=[('knn', knn_best), ('ada', ada), ('log_reg', log_reg), ('gbm', gbm)]
new_ensemble = VotingClassifier(estimators, voting='hard')
new_ensemble.fit(X_train, y_train)

下面这部分是显示错误的地方

y_pred = new_ensemble.predict(X_test)

我尝试将所有内容从 X_train、X_test、y_train、y_test 转换为 float,但它没有改变任何内容。我将所有内容都更改为 int 但也发生了同样的错误。为什么该行显示错误?我真的很困惑。

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-37-86a04c2ceff1> in <module>
----> 1 y_pred = new_ensemble.predict(X_test)

~\AppData\Roaming\Python\Python37\site-packages\sklearn\ensemble\voting_classifier.py in predict(self, X)
237 lambda x: np.argmax(
238 np.bincount(x, weights=self._weights_not_none)),
--> 239 axis=1, arr=predictions)
240
241 maj = self.le_.inverse_transform(maj)

~\Anaconda3\lib\site-packages\numpy\lib\shape_base.py in apply_along_axis(func1d, axis, arr, *args, **kwargs)
378 except StopIteration:
379 raise ValueError('Cannot apply_along_axis when any iteration dimensions are 0')
--> 380 res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))
381
382 # build a buffer for storing evaluations of func1d.

~\AppData\Roaming\Python\Python37\site-packages\sklearn\ensemble\voting_classifier.py in <lambda>(x)
236 maj = np.apply_along_axis(
237 lambda x: np.argmax(
--> 238 np.bincount(x, weights=self._weights_not_none)),
239 axis=1, arr=predictions)
240

TypeError: Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'safe'

最佳答案

尝试对VotingClassifier使用参数voting='soft'。我认为对于voting='hard',它期望所有模型都具有整数标签,但会从回归器中获取一些浮点值。使用“软”时,它将模型结果作为概率,当然,概率是 float 。

关于python - 无法根据 ('float64' 将数组数据从 dtype ('int32' ) 转换为 dtype 'safe' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59493873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com