def classify(self, texts):
vectors = self.dictionary.feature_vectors(texts)
predictions = self.svm.decision_function(vectors)
predictions = np.transpose(predictions)[0]
predictions = predictions / 2 + 0.5
predictions[predictions > 1] = 1
predictions[predictions < 0] = 0
return predictions
错误:
TypeError: 'numpy.float64' object does not support item assignment
发生在以下行:
predictions[predictions > 1] = 1
有没有人有解决这个问题的想法?谢谢!
答案 0 :(得分:3)
尝试此测试代码并注意np.array([1,2,3], dtype=np.float64)
。
似乎self.svm.decision_function(向量)返回 1d 数组而不是2d。
如果将[1,2,3]替换为[[1,2,3],[4,5,6]],一切都会好的。
import numpy as np
predictions = np.array([1,2,3], dtype=np.float64)
predictions = np.transpose(predictions)[0]
predictions = predictions / 2 + 0.5
predictions[predictions > 1] = 1
predictions[predictions < 0] = 0
输出:
Traceback (most recent call last):
File "D:\temp\test.py", line 7, in <module>
predictions[predictions > 1] = 1
TypeError: 'numpy.float64' object does not support item assignment
那么,你的载体是什么?
答案 1 :(得分:0)
predictions > 1
是一个布尔操作。
predictions[predictions > 1] = 1
评估为
predictions[True]
您正在寻找np.where()运营商。您的代码应如下所示:
predictions[np.where(predictions > 1)] = 1
答案 2 :(得分:0)
>>> predictions = np.array([1,2,3], dtype=np.float64)
>>> predictions
array([1., 2., 3.])
>>> predictions = np.transpose(predictions)[0]
>>> predictions
1.0
>>> predictions = predictions / 2 + 0.5
>>> predictions
1.0
>>> predictions>1
False
数组中没有元素大于1,因此您无法将1分配给预测[predictions> 1],可以在分配前使用'predicts> 1'。
答案 3 :(得分:-3)
预测=预测/ 2 + 0.5
for i in range(predictions):
predictions[i] = predictions[i] / 2 + 0.5
预测[预测> 1] = 1
for i in range(predictions):
predictions[i] = predictions[i] / 2 + 0.5
if predictions[i] > 1:
predictions[i] = 1
elif predictions[i] < 0 :
predictions[i] = 0
return predictions