类型错误:'numpy.float64' 对象不支持项目分配

che*_*hen 10 python numpy

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
Run Code Online (Sandbox Code Playgroud)

错误:

TypeError: 'numpy.float64' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)

发生在以下行:

        predictions[predictions > 1] = 1
Run Code Online (Sandbox Code Playgroud)

有没有人有解决这个问题的想法?谢谢!

Max*_*nko 5

尝试这个测试代码并注意np.array([1,2,3], dtype=np.float64). 看来 self.svm.decision_function(vectors) 返回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
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

那么,你的向量是什么?