ndarray(numpy,python)赋值为0的数组:为什么?

时间:2016-08-11 10:19:15

标签: python numpy

所以在这个简单的代码中行

result[columnNumber] = column #this assignment fails for some reason!

失败,特别是它只是分配零数组而不是它应该分配的内容,我不明白为什么!所以这是完整的代码:

    """Softmax."""

scores = [3.0, 1.0, 0.2]

import numpy as np

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    data=np.array(x)
    columnNumber=0
    result=data.copy()
    result=result.T

    for column in data.T:
        sumCurrentColumn=0
        try: #Since 'column' can potentially be just a double,and sum needs some iterable object
            sumCurrentColumn=sum(np.exp(column))
        except TypeError:
            sumCurrentColumn=np.exp(column)



        column=np.divide(np.exp(column),sumCurrentColumn)
        print(column)
        print('before assignment:'+str(result[columnNumber]))
        result[columnNumber] = column #this assignment fails for some reason!
        print('after assignment:'+str(result[columnNumber]))
        columnNumber+=1 

    result=result.T

    return result


scores = np.array([[1, 2, 3, 6],
                   [2, 4, 5, 6],
                   [3, 8, 7, 6]])

print(softmax(scores))

这是它的输出:

   [ 0.09003057  0.24472847  0.66524096]
before assignment:[1 2 3]
after assignment:[0 0 0]
[ 0.00242826  0.01794253  0.97962921]
before assignment:[2 4 8]
after assignment:[0 0 0]
[ 0.01587624  0.11731043  0.86681333]
before assignment:[3 5 7]
after assignment:[0 0 0]
[ 0.33333333  0.33333333  0.33333333]
before assignment:[6 6 6]
after assignment:[0 0 0]
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

2 个答案:

答案 0 :(得分:2)

在您的示例中,输入scores都是整数,因此data数组的数据类型是整数。因此result也是一个整数数组。您不能将浮点值分配给整数数组 - numpy数组具有无法动态更改的同类数据类型。第result[columnNumber] = column行将column中的值截断为整数,因为它们都在0到1之间,所以赋值都是0。

尝试将result的创建更改为:

result = data.astype(float)

(默认情况下,即使astype已具有指定类型,data方法也会创建副本。)

答案 1 :(得分:0)

您的数组result的类型为int,因此您的所有浮点数都会自动转换为int,在这种情况下为0。使用此result = data.astype(float)