python - PyTorch 中图像的 Hello World 卷积
问题描述
我正在尝试使用 PyTorch 的 2D 卷积验证以下结果:
- 输入矩阵:X (10, 10, 3) [Dummy numpy image]
- 权重矩阵:W (3, 3, 3) [My Conv Filter to test]
- 输出矩阵:Y (10, 10, 1)
我有以下代码,但我无法正确分配权重并运行模型而不会出错。我在这里做错了什么?
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)
解决方案
下次请发布您相应的错误消息。结果矩阵维度也必须匹配批量大小(即需要额外的第四维度):因此,您正在使用错误的参数初始化权重矩阵。
正确的是:
weight = torch.nn.Parameter(torch.ones(1, 3, 3, 3))
此外,对于我的 PyTorch (0.4.1) 版本,我不得不再次手动将张量转换为浮点数,否则会引发不同的错误。避免这样做:
tensor = image2tensor(image).unsqueeze(0).float() # note the additional .float()
然后它为我成功运行。
推荐阅读
- node.js - 如何访问嵌套数据,这是猫鼬数组中的参考数据?
- angularjs - 如果有任何变化,AngularJS会同时重新加载多个选项卡
- ios - 如何在 iOS 中进行身份验证后显示谷歌帐户屏幕?
- flutter - 没有模拟器的颤振
- curl - curl: (7) 连接 127.0.0.1 端口 3000 失败:连接被拒绝
- sql - 通过调用函数更新列非常慢 - 如何改进?SQL 服务器
- python - 使用对象时面临“列表索引超出范围”错误
- c# - MailKit - SmtpClient Connect 方法冻结
- c# - Azure函数使用实体框架但连接字符串不起作用
- javascript - 为 ag-grid 定义仅一个特定列的自动大小列是可能的吗?