pytorch 一维卷积api理解

发布时间 2023-11-28 21:01:43作者: lif323
import torch
torch.manual_seed(2021)

# in_channels 表示输入特征数量,卷积核的第一个维度
# out_channels 表示输出特征数量,也是卷积核的数量
# kernel_size 是卷积核的第二维度。 卷积核维度为  in_channels * kernel_size
m = torch.nn.Conv1d(in_channels=4, out_channels=1, kernel_size=2)

w = torch.tensor([[[1, 1],[2, 2],[3, 3], [4, 4]]], dtype=torch.float32)
b = torch.tensor([0], dtype=torch.float32)
print("W.shape: ", w.shape)
print("b.shape: ", b.shape)
with torch.no_grad():
    for name, param in m.named_parameters():
        if 'weight' in name:
            param.copy_(w)

        if 'bias' in name:
            param.copy_(b)

inputs = torch.tensor([[[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3], [4, 4, 4, 4]]], dtype=torch.float32)
print(inputs.shape)
inputs = inputs.permute(0, 2, 1)
output = m(inputs)
print(output.shape) 
# output[0] = 1 * 1 + 1 * 2 + 1 * 3 + 1 * 4 + 2 * 1 + 2 * 2 + 2 * 3 + 2 * 4
print(output)

参考:
https://www.cnblogs.com/aionwu/p/15088988.html
https://discuss.pytorch.org/t/how-to-assign-an-arbitrary-tensor-to-models-parameter/44082/2