Sae*_*eed 3 python numpy scikit-learn
我阅读了许多与此类似的问题,但仍然无法弄清楚。
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
X_to_predict = 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,
9.24341823e+001, 1.11457878e+002, -1.90236954e+001]])
clf.predict_proba(X_to_predict)
ValueError: Input contains NaN, infinity or a value too large for dtype('float32').
Run Code Online (Sandbox Code Playgroud)
我的问题既不是也不 nan是inf价值观,因为:
np.isnan(X_to_predict).sum()
Out[147]: 0
np.isinf(X_to_predict).sum()
Out[148]: 0
Run Code Online (Sandbox Code Playgroud)
问题:如何转换X_to_predict为对于 float32 来说不太大的值,同时保留尽可能多的小数点后位数?
如果您检查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
Run Code Online (Sandbox Code Playgroud)
sklearn 的 RandomForestClassifier 会默默地将数组转换为float32,请参阅此处的讨论以了解错误消息的来源。
你可以自己转换
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)
Run Code Online (Sandbox Code Playgroud)
第三个值 (-1.82710826e+296) 变为-inffloat32。解决它的唯一方法是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)
Run Code Online (Sandbox Code Playgroud)
你的分类器应该接受它。
完整代码
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)
Run Code Online (Sandbox Code Playgroud)