我不知道为什么张量的结果都是0。这里有什么问题吗?
>>> import torch
>>> import numpy as np
>>> import math
>>> torch.__version__
'0.4.1'
>>> np.__version__
'1.15.4'
>>> torch.arange(0, 10, 2) *-(math.log(10000.0) / 10)
tensor([0, 0, 0, 0, 0])
>>> np.arange(0, 10, 2) *-(math.log(10000.0) / 10)
array([-0. , -1.84206807, -3.68413615, -5.52620422, -7.3682723 ])
>>> torch.arange(0, 10, 2)
tensor([0, 2, 4, 6, 8])
>>> np.arange(0, 10, 2)
array([0, 2, 4, 6, 8])
发布于 2018-11-25 11:54:43
正如注释中所写的,当使用0.4.0时,会得到与使用numpy相同的结果:
tensor([-0.0000, -1.8421, -3.6841, -5.5262, -7.3683])
然而,对于0.4.1
,我也得到了一个零向量。
这是因为torch.arange(0, 10, 2)
为0.4.0返回float
类型的张量,而为0.4.1返回long
类型的张量。
因此,将张量转换为float
应该对您有效:
torch.arange(0, 10, 2).float() *-(math.log(10000.0) / 10)
将long
和float
相乘是通过重四舍五入实现的,因为结果仍然是long
类型的张量。因此,在将FloatTensor
转换为LongTensor
时,介于-1和1之间的值将四舍五入为0。
因为-(math.log(10000.0) / 10)
结果是-0.9210340371976183
,所以你的结果是0
。因此,在乘法之前,有效地将-0.9210340371976183
转换为long
类型。但在将其向下转换为0
时,请参见此示例:
t = torch.tensor((-(math.log(10000.0) / 10)))
print('FloatTensor:', t)
print('Converted to Long:', t.long())
输出:
FloatTensor: tensor(-0.9210)
Converted to Long: tensor(0)
因此:
torch.arange(0, 10, 2).float() *-(math.log(10000.0) / 10)
变成:
torch.arange(0, 10, 2).float() * 0
因此,你会得到一个零张量作为结果。
更多的例子:
如果将其与1和2之间的值相乘,假设为1.7,它将始终四舍五入为1:
t = torch.tensor(range(5), dtype=torch.long)
print(t)
print(t * 1.7)
输出:
tensor([ 0, 1, 2, 3, 4])
tensor([ 0, 1, 2, 3, 4])
类似地,当与2.7
相乘导致2
的有效相乘时
t = torch.tensor(range(5), dtype=torch.long)
print(t)
print(t * 2.7)
输出:
tensor([ 0, 1, 2, 3, 4])
tensor([ 0, 2, 4, 6, 8])
https://stackoverflow.com/questions/53467011
复制相似问题