Conv2d的预期参数

以下代码 :

import torch import torch.nn as nnimport torchvisionimport torchvision.transforms as transformsimport torch.utils.data as data_utilsimport numpy as nptrain_dataset = []mu, sigma = 0, 0.1 # mean and standard deviationnum_instances = 20batch_size_value = 10for 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 configurationdevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')# Hyper parametersnum_epochs = 5num_classes = 1batch_size = 5learning_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 outmodel = ConvNet(num_classes).to(device)# Loss and optimizercriterion = nn.CrossEntropyLoss()optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)# Train the modeltotal_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

阅读conv2d的文档后,我尝试将第一个参数改为10X100以匹配

input – 形状为(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) = (batch_size, 1600)

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

你的第2个卷积层输出与全连接层预期形状之间的这种不匹配导致了错误(请注意,错误信息中提到的形状与上述形状对应)。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注