[英]2D numpy array doesn't implicitly convert from int64 to float64
当numpy数组是向量时,设置起作用并且dtype
隐式转换为float,但是当numpy数组是矩阵时,设置起作用但dtype
仍然是int。 这是一个演示脚本来说明问题。
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
输出:
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]]
这些数字被整数截断,这是我最初的问题,可追溯到此。
我正在使用Python 2.7.11
和numpy 1.13.0
每当您将值写入现有数组时,该值都将dtype
为与数组dtype
相匹配。 在您的情况下,将所得的float64
值int64
为int64
:
b = numpy.arange(4).reshape(2, 2)
b.dtype # dtype('int64')
取任何这些值的numpy.exp()
将返回float64
:
numpy.exp(b[0, :]).dtype # dtype('float64')
但是,如果现在使用此float64
并将其写回到原始的int64
数组中,则需要先进行转换:
b[0, :] = numpy.exp(b[0, :])
b.dtype # dtype('int64')
注意使用
b = numpy.exp(b)
创建一个具有自己的dtype
的新数组。 如果相反,您确实
b[:] = numpy.exp(b[:])
您将隐式地再次转换为int64
。
另请注意,无需像您一样编写循环。 相反,您可以将操作向量化:
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.