简体   繁体   English

2D numpy数组不会从int64隐式转换为float64

[英]2D numpy array doesn't implicitly convert from int64 to float64

How come when the numpy array is a vector, the setting works and the dtype is implicitly converted to float but when the numpy array is a matrix, the setting works but the dtype is still int. 当numpy数组是向量时,设置起作用并且dtype隐式转换为float,但是当numpy数组是矩阵时,设置起作用但dtype仍然是int。 Here's a demo script to illustrate the problem. 这是一个演示脚本来说明问题。

import numpy as np

# successfully sets / converts
x = np.array([100, 101])
c = -np.max(x)
x += c
print 'before', x.dtype
x = np.exp(x)
print 'after', x.dtype

print x

# doesn't successfully set / convert
matrix = np.array([(100, 101), (102, 103)])
for i in range(len(matrix)):
    c = -np.max(matrix[i])
    matrix[i] += c
    print 'before', matrix[i].dtype
    matrix[i] = np.exp(matrix[i])
    print 'after', matrix[i].dtype

print matrix

output: 输出:

before int64
after float64 <-- from vector
[ 0.36787944  1.        ]
before int64
after int64 <-- from row 1 of matrix
before int64
after int64 <-- from row 2 of matrix
[[0 1]
 [0 1]]

The numbers are integer truncated, which was my original problem, traced down to this. 这些数字被整数截断,这是我最初的问题,可追溯到此。

I'm using Python 2.7.11 and numpy 1.13.0 我正在使用Python 2.7.11numpy 1.13.0

Whenever you write a value into an existing array, the value is cast to match the array dtype . 每当您将值写入现有数组时,该值都将dtype为与数组dtype相匹配。 In your case, the resulting float64 value is cast to int64 : 在您的情况下,将所得的float64int64int64

b = numpy.arange(4).reshape(2, 2)
b.dtype  # dtype('int64')

taking numpy.exp() of any of these values will return a float64 : 取任何这些值的numpy.exp()将返回float64

numpy.exp(b[0, :]).dtype  # dtype('float64')

but if you now take this float64 and write it back into the original int64 array, it needs to be cast first: 但是,如果现在使用此float64并将其写回到原始的int64数组中,则需要先进行转换:

b[0, :] = numpy.exp(b[0, :])
b.dtype  # dtype('int64')

Note that using 注意使用

b = numpy.exp(b)

creates a new array with its own dtype . 创建一个具有自己的dtype的新数组。 If instead you did 如果相反,您确实

b[:] = numpy.exp(b[:])

you would be implicitly casting to int64 again. 您将隐式地再次转换为int64

Also note that there is no need to write a loop like you did. 另请注意,无需像您一样编写循环。 Instead you can vectorize the operation: 相反,您可以将操作向量化:

np.exp(matrix - numpy.max(matrix, axis=1, keepdims=True))
# array([[ 0.36787944,  1.        ],
#        [ 0.36787944,  1.        ]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM