How to load weights to model using .npy model?

Hi everyone,

I am making a CNN and I need to load weights from a preexisting .npy file.
Up until now I have made this function to do it.

def load_weights():
    params = net.state_dict()
    pathtoweights = os.path.join(os.path.abspath("."), "saved_models", "numpy", "weights.npy")
    pretrained_weights = np.load(pathtoweights allow_pickle=True).item()
    with torch.no_grad(): 
        for key in params:
            if "weight" == key[-6:]:
                npkey = bytes(key[:-7], "utf-8")
                if npkey in pretrained_weights.keys():
                    print("Weight found for " + npkey + "layer")
                    params[key].copy_(torch.from_numpy(pretrained_weights[npkey]["weights"]).type(Tensor))
            elif "bias" == key[-5:]:
                npkey = bytes(key[:-5], "utf-8")
                if npkey in pretrained_weights.keys():
                    print("Bias found for " + npkey + "layer")
                    params[key].copy_(torch.from_numpy(pretrained_weights[npkey]["biases"]).type(Tensor))

However, when I run this function, the values inside params does get changed but it remains same when I print net.state_dict(). Why is it happening, tell me if I am doing anything wrong or see if you can find a fix. Greatly appreciate your help.

Your approach should work, as seen in this example:

lin = nn.Linear(1, 1)
sd = lin.state_dict()
print(sd)
> OrderedDict([('weight', tensor([[-0.5414]])), ('bias', tensor([0.8279]))])

sd['weight'].copy_(torch.tensor([[1.]]))
print(lin.state_dict())
> OrderedDict([('weight', tensor([[1.]])), ('bias', tensor([0.8279]))])

print(lin.weight)
> Parameter containing:
tensor([[1.]], requires_grad=True)

Thanks, I just checked again and it was working this time as you said. I don’t know what happened last time, but it was not showing up. Maybe I made some error while printing state_dict after updating it. Anyways thank you for the response.