为什么我的CPU pytorch模型的输出是不可重复的?

2024-04-23 12:14:05 发布

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

我最近开始使用pytorch,我注意到在评估新输入的预训练模型时,没有得到可重复/确定的结果。你知道吗

我把这个问题归结为一个最小的例子,这个例子表明重复应用同一个简单的卷积模型并不能得到相同的结果:

import numpy as np 
import matplotlib.pyplot as plt 
import torch

device = torch.device('cpu')

# function to get all the params from a pytorch model
def getParams(model):
    a = list(model.parameters())
    b = [a[i].detach().cpu().numpy() for i in range(len(a))]
    c = [b[i].flatten() for i in range(len(b))]
    d = np.hstack(c)

    return d

# set up a simple model (9 params)
testModule = torch.nn.Conv2d(1, 1, kernel_size = (3, 3), bias = False, stride = 1, padding = 1).double()
torch.nn.init.normal_(testModule.weight, mean=0, std=1)
testModule = testModule.eval()

# set up a dummy input
patch = torch.from_numpy(np.random.randn(1,1,80,80).astype('double')).to(device)

# apply the model 100 times
testVals = []
testParams = []
testModuleOut = []
for ii in range(100):
    testParams.append(getParams(testModule))
    testModuleOut.append(testModule(patch).cpu().detach()[0,:,:,:].numpy())

testParams = np.stack(testParams)
testModuleOut = np.stack(testModuleOut)

# view the variation of the model parameters and the output values
plt.figure()
plt.plot(np.std(testParams,axis=0))
plt.xlabel('Parameter index')
plt.ylabel('Standard deviation over runs')

plt.figure()
plt.plot(np.std(testModuleOut,axis=0).ravel())
plt.xlabel('Output index')
plt.ylabel('Standard deviation over runs')

如果重新运行网络是可重复的,我希望标准差图在SD=0时显示扁平线。但是我没有得到这个,而是得到了一些随机的图形线,它们随着脚本的每次运行而变化(有时模块参数的SD=0,但是网络输出似乎从来没有变化)。你知道吗

我的代码有什么问题?SDs似乎与机器精度有关,但是为什么反复从模块中提取参数会导致它们以这种方式改变呢?我们不只是从记忆中提取完全相同的值吗?你知道吗


Tags: theinimportnumpyformodeldevicenp