错误:RuntimeError: expected scalar type Byte but found Float
错误:RuntimeError: expected scalar type Byte but found Float
问题描述:
在使用pytorch的nn.Conv2d()编写卷积神经网络时,提示报错。
网络结构
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=7, stride=2, padding=0)
self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2, padding=0)
self.conv3 = nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=0)
self.conv4 = nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=0)
self.conv5 = nn.Conv2d(128, 1, kernel_size=2, stride=2, padding=0)
self.lin = nn.Linear(88, 4)
def forward(self, xb):
xb = xb.view(-1, 3, 280, 380)
xb = self.conv1(xb)
xb = F.relu(xb)
xb = F.relu(self.conv2(xb))
xb = F.relu(self.conv3(xb))
xb = F.relu(self.conv4(xb))
xb = F.relu(self.conv5(xb))
xb = xb.view(-1, 88)
xb = self.lin(xb)
return xb
调用网络
import numpy as np
import matplotlib.pyplot as plt
import cv2
from PIL import Image
from net import CNN
image = Image.open('photo.jpg')
image = image.resize([280, 380], Image.BICUBIC)
print(np.array(image) .transpose(2, 1, 0))
photo = np.array(image).transpose(2, 1, 0)
images = torch.from_numpy(np.asarray([photo]))
model = CNN()
x = model.forward(images)
报错
提示在self.conv1()计算卷积时报错。
解决方案:
方法一:
方法二: 两个方法其实都一样,只不过是先后顺序不同。
|