TypeError: 'numpy.float64' object does not

2020-07-11 08:04发布

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

The error:

TypeError: 'numpy.float64' object does not support item assignment

occurs on the following line:

        predictions[predictions > 1] = 1

Does anyone has an idea of solving this problem? Thanks!

标签: python numpy
4条回答
Emotional °昔
2楼-- · 2020-07-11 08:26

You can't perform this operation in all elements at once,

predictions = predictions / 2 + 0.5

If you want to update all the elements contained by 'predictions', rather do the following

for i in range(predictions):
   predictions[i] = predictions[i] / 2 + 0.5
                                    
 

What are you doing here ???????????

predictions[predictions > 1] = 1

I am not sure of what you are trying to do , but if you are trying to compare if elements at each index of 'predictions' is greater than 1, rather put the statements under the above if statement as follows

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
查看更多
Melony?
3楼-- · 2020-07-11 08:32

Try this testing code and pay attention to np.array([1,2,3], dtype=np.float64). It seems self.svm.decision_function(vectors) returns 1d array instead of 2d. If you replace [1,2,3] to [[1,2,3], [4,5,6]] everything will be ok.

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

Output:

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

So, what your vectors are?

查看更多
老娘就宠你
4楼-- · 2020-07-11 08:40
    >>> 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

there is no element in array is bigger than 1,So you cannot assign 1 to predictions[predictions>1],you can use ' predictions>1 ' before your assignment.

查看更多
疯言疯语
5楼-- · 2020-07-11 08:42
predictions > 1

is a boolean operation.

predictions[predictions > 1] = 1

evaluates to

predictions[True]

You are looking for the np.where() operator. Your code should look like this:

predictions[np.where(predictions > 1)] = 1
查看更多
登录 后发表回答