如何解决将pytorch变量转换为numpy时更改的值?

how to solve the values changed when converting a pytorch Variable to numpy?

我正在尝试将resnet34的一个参数转换成numpy,但是我发现转换后值会发生变化,如图。 为什么会这样?我该怎么做才能获得 numpy 格式的精确值? enter image description here

( 我试图在 torch 预训练模型中获取参数并将它们放入 tensorflow 1.x 模型中,因为在搜索了几天后我在 tensorflow1 中找不到预训练的 resnet34 模型。我担心这个更改值会影响模型的准确性。)

(顺便说一句,有没有办法下载带有基本块而不是瓶颈块的 tensorflow1.x resnet34 预训练模型? 我在 github 中搜索了几天,但没有找到。我讨厌 tensorflow。)

值在技术上是相同的,只是四舍五入到小数点后 04 位。

使用下面的代码,你应该得到相同的输出:

print(round(weight_np[0,0,0,0],4))

值没有改变,它们是相同的,但 PyTorch 将默认输出限制为小数点后 4 位(四舍五入)以便于检查。

您可以使用 torch.set_printoptions 更改该行为以显示更多小数位。

value = torch.tensor(0.0052872747)

print(value) # => tensor(0.0053)

# Show 10 decimal places
torch.set_printoptions(precision=10)

print(value) # => tensor(0.0052872747)

浮点输出的默认精度位数为 4。请参阅 PyTorch documentation

您可以将其设置为 8 位数字,如下所示:

import torch
a = torch.tensor([0.01298734, 0.00689523])
print(a) # tensor([0.0130, 0.0069])
torch.set_printoptions(precision=8)
print(a) # tensor([0.01298734, 0.00689523])