gpt4 book ai didi

machine-learning - Conv2d的预期参数

转载 作者:行者123 更新时间:2023-11-30 08:31:37 25 4
gpt4 key购买 nike

下面的代码:

import torch 
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as data_utils
import numpy as np

train_dataset = []
mu, sigma = 0, 0.1 # mean and standard deviation
num_instances = 20
batch_size_value = 10
for i in range(num_instances) :
image = []
image_x = np.random.normal(mu, sigma, 1000).reshape((1 , 100, 10))
train_dataset.append(image_x)
labels = [1 for i in range(num_instances)]
x2 = torch.tensor(train_dataset).float()
y2 = torch.tensor(labels).long()
my_train2 = data_utils.TensorDataset(x2, y2)
train_loader2 = data_utils.DataLoader(my_train2, batch_size=batch_size_value, shuffle=False)

# Device configuration
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

# Hyper parameters
num_epochs = 5
num_classes = 1
batch_size = 5
learning_rate = 0.001

# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
def __init__(self, num_classes=1):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(7*7*32, num_classes)

def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out

model = ConvNet(num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_step = len(train_loader2)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader2):
images = images.to(device)
labels = labels.to(device)

# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)

# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()

if (i+1) % 100 == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))

返回错误:

RuntimeError: size mismatch, m1: [10 x 1600], m2: [1568 x 1] at /pytorch/aten/src/THC/generic/THCTensorMathBlas.cu:249

阅读documentation for conv2d ,我尝试将第一个参数更改为10X100以匹配

input – input tensor of shape (minibatch×in_channels×iH×iW)

来自https://pytorch.org/docs/stable/nn.html#torch.nn.functional.conv2d

但随后收到错误:

RuntimeError: Given groups=1, weight[16, 1000, 5, 5], so expected input[10, 1, 100, 10] to have 1000 channels, but got 1 channels instead

所以我不确定我是否已经纠正了原来的错误或者只是导致了新的错误?

应该如何设置Conv2d才能匹配(10,100)的图像形状?

最佳答案

错误来自最终的全连接层self.fc = nn.Linear(7*7*32, num_classes),而不是卷积层。

给定您的输入尺寸 ((10, 100)),out = self.layer2(out) 的形状为 (batch_size, 32, 25 , 2),因此 out = out.reshape(out.size(0), -1) 的形状为 (batch_size, 32*25*2) = (批量大小,1600)

另一方面,您的全连接层是为形状 (batch_size, 32*7*7) = (batch_size, 1568) 的输入定义的。

第二个卷积输出的形状与全连接层的预期形状之间的不匹配导致了错误(请注意跟踪中提到的形状如何与上述形状相对应)。

关于machine-learning - Conv2d的预期参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com