如果您检查dtype
你的数组的X_to_predict
它应该显示float64
.
# slightly modified array from the question
X_to_predict = np.array([1.37097033e+002, 0.00000000e+000, -1.82710826e+296,
1.22703799e+002, 1.37097033e+002, -2.56391552e+001,
1.11457878e+002, 1.37097033e+002, -2.56391552e+001,
9.81898928e+001, 1.22703799e+002, -2.45139066e+001]).reshape((3, 4))
print(X_to_predict.dtype)
>>> float64
sklearn RandomForestClassifier 默默地将数组转换为float32
,参见讨论here https://github.com/scikit-learn/scikit-learn/issues/2809错误消息的来源。
你可以自己转换一下
print(X_to_predict.astype(np.float32)))
>>> array([[137.09703 , 0. , -inf, 122.7038 ],
[137.09703 , -25.639154, 111.45788 , 137.09703 ],
[-25.639154, 98.189896, 122.7038 , -24.513906]],
dtype=float32)
第三个值 (-1.82710826e+296) 变为-inf
在 float32 中。解决这个问题的唯一方法是更换你的inf
最大值为 float32 的值。你会失去一些精度,据我所知,除了更改 sklearn 中的实现并重新编译之外,目前没有参数或解决方法。
如果你使用np.nan_to_num
你的数组应该是这样的:
new_X = np.nan_to_num(X_to_predict.astype(np.float32))
print(new_X)
>>> array([[ 1.3709703e+02, 0.0000000e+00, -3.4028235e+38, 1.2270380e+02],
[ 1.3709703e+02, -2.5639154e+01, 1.1145788e+02, 1.3709703e+02],
[-2.5639154e+01, 9.8189896e+01, 1.2270380e+02, -2.4513906e+01]],
dtype=float32)
您的分类器应该接受它。
完整代码
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
iris = load_iris()
clf = RandomForestClassifier(n_estimators=10,
random_state=42)
clf.fit(iris.data, iris.target)
X_to_predict = np.array([1.37097033e+002, 0.00000000e+000, -1.82710826e+296,
1.22703799e+002, 1.37097033e+002, -2.56391552e+001,
1.11457878e+002, 1.37097033e+002, -2.56391552e+001,
9.81898928e+001, 1.22703799e+002, -2.45139066e+001]).reshape((3, 4))
print(X_to_predict.dtype)
print(X_to_predict.astype(np.float32))
new_X = np.nan_to_num(X_to_predict.astype(np.float32))
print(new_X)
#should return array([2, 2, 0])
print(clf.predict(new_X))
# should crash
clf.predict(X_to_predict)