简体   繁体   English

你好世界卷积图像在PyTorch中

[英]Hello World Convolution on Images in PyTorch

I am trying to verify some results with PyTorch's 2D convolution with the following: 我正在尝试通过PyTorch的2D卷积验证以下结果:

  • Input matrix: X (10, 10, 3) [Dummy numpy image] 输入矩阵:X(10、10、3)[虚拟numpy图片]
  • Weight matrix: W (3, 3, 3) [My Conv Filter to test] 权重矩阵:W(3,3,3)[要测试的我的转化过滤器]
  • Output matrix: Y (10, 10, 1) 输出矩阵:Y(10,10,1)

I have the following code but I am not able to assign the weights properly and run the model without errors. 我有以下代码,但无法正确分配权重并运行模型而没有错误。 What am I doing wrong here?? 我在这里做错了什么?

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)

Next time please post your corresponding error message. 下次,请发布您相应的错误消息。 Turns out the matrix dimension also has to match the batch size (ie needs an additional fourth dimension): Thus, you are initializing the weight matrix with the wrong parameters. 事实证明,矩阵尺寸还必须与批次大小匹配(即需要额外的第四维):因此,您正在使用错误的参数初始化权重矩阵。

Correct would be this instead: 正确的是:

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

Additionally, for my version of PyTorch (0.4.1), I had to manually cast the tensor again to a float because it otherwise threw a different error. 另外,对于我的PyTorch(0.4.1)版本,我不得不再次手动将张量转换为浮点数,否则会引发其他错误。 Avoid by doing it like so: 避免这样做:

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

Then it runs successfully for me. 然后它为我成功运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM