为什么每次保存时模型的哈希值都会改变?

2024-04-26 00:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用火炬。救命()保存模型文件。但是,每次我保存它时,它都会改变。为什么会这样?你知道吗

netG_1 = torch.load('netG.pth')
netG_2 = torch.load('netG.pth')

torch.save(netG_1, 'netG_1.pth')
torch.save(netG_2, 'netG_2.pth')

使用md5sum *.pth

779f0fefca47d17a0644033f9b65e594  netG_1.pth
476f502ec2d1186c349cdeba14983d09  netG_2.pth
b0ceec8ac886a11b79f73fc04f51c6f9  netG.pth

模型是此类的实例:

https://github.com/taoxugit/AttnGAN/blob/master/code/model.py#L397


Tags: 文件实例https模型githubcomsaveload
1条回答
网友
1楼 · 发布于 2024-04-26 00:30:58

未定义__hash__方法的类将根据其id对其实例进行哈希处理。对于CPython,这意味着每次保存和重新加载实例时,它都会更改哈希值,因为它在内存中的位置发生了更改。你知道吗

这是一个概念证明。你知道吗

class Foo:
    pass

instance = Foo()

print('hash:', hex(hash(instance)))
print('id:  ', hex(id(instance)))

输出

hash: 0x22f3f57608
id:   0x22f3f576080

精确变换是hash(o) == id(o) // 16。你知道吗

相关问题 更多 >