Manually set weights for nn.Conv2d?

I’m trying to manually set the weights for ann.Conv2d. I’ve seen this post: How to set nn.conv2d weights, however I’m trying to use a numpy array as the weights. Why? Because np.asarray(x) allows me to easily construct my weights array using a nested Python list (x is Python list).

Example code:

IN = 2
OUT = 3
KERNEL_SIZE = 2
proof_conv = nn.Conv2d(IN, OUT, kernel_size=KERNEL_SIZE, padding=0, bias=False)
assert proof_conv.weight.shape == (OUT, IN, KERNEL_SIZE, KERNEL_SIZE)

ZERO_FILTER = [[0., 0.], [0., 0.]]
ONE_FILTER =  [[1., 1.], [1., 1.]]
weights = [
           [ZERO_FILTER, ZERO_FILTER],
           [ONE_FILTER, ONE_FILTER],
           [ONE_FILTER, ZERO_FILTER],
]
weights = np.asarray(weights).astype(np.float64)
proof_conv.weight = nn.Parameter(torch.from_numpy(weights))

ones = torch.ones((IN, 4, 4))
out_img = proof_conv(ones)

However, this code fails with the error:

RuntimeError: expected scalar type Float but found Double

Does anyone know what’s going on here?

Transform the tensor to float and it should work:

with torch.no_grad():
    proof_conv.weight.copy_(torch.from_numpy(weights).float())