[英]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.