首页 > 解决方案 > PyTorch 中图像的 Hello World 卷积

问题描述

我正在尝试使用 PyTorch 的 2D 卷积验证以下结果:

我有以下代码,但我无法正确分配权重并运行模型而不会出错。我在这里做错了什么?

import torch
import torch.nn as nn
import torchvision.transforms
import numpy as np

# Convert image to tensor
image2tensor = torchvision.transforms.ToTensor()

class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        # Test layer
        self.layer1 = nn.Conv2d(3, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))

    def forward(self, x):
        out = self.layer1(x)
        return out

# Test image
image = np.ones((10, 10, 3))
tensor = image2tensor(image).unsqueeze(0)

# Create new model
conv = ConvNet()

# Assign test weight - NOT WORKING!!
weight = torch.nn.Parameter(torch.ones(3, 3, 3))
conv.layer1.weight.data = weight

# Run the model
output = conv(tensor)

标签: pythonconv-neural-networkpytorch

解决方案


下次请发布您相应的错误消息。结果矩阵维度也必须匹配批量大小(即需要额外的第四维度):因此,您正在使用错误的参数初始化权重矩阵。

正确的是:

weight = torch.nn.Parameter(torch.ones(1, 3, 3, 3))

此外,对于我的 PyTorch (0.4.1) 版本,我不得不再次手动将张量转换为浮点数,否则会引发不同的错误。避免这样做:

tensor = image2tensor(image).unsqueeze(0).float() # note the additional .float()

然后它为我成功运行。


推荐阅读