gpt4 book ai didi

python - 在 Pytorch 卷积神经网络中展平张量(大小不匹配错误)

转载 作者:行者123 更新时间:2023-12-01 04:25:06 28 4
gpt4 key购买 nike

我用随机像素做了一个可重复的例子。我正在尝试 压平 之后密集层的张量卷积层 .问题出在卷积层和密集层的交叉处。我不知道如何放置正确数量的神经元。

tl;博士 我正在寻找等效于 keras.layers.Flatten() 的手册因为它不存在于 pytorch .

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader

x = np.random.rand(1_00, 3, 100, 100)
y = np.random.randint(0, 2, 1_00)

if torch.cuda.is_available():
x = torch.from_numpy(x.astype('float32')).cuda()
y = torch.from_numpy(y.astype('float32')).cuda()

class ConvNet(nn.Module):

def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 32, 3)
self.conv2 = nn.Conv2d(32, 64, 3)
self.conv3 = nn.Conv2d(64, 128, 3)

self.fc1 = nn.Linear(128, 1024) # 128 is wrong here
self.fc2 = nn.Linear(1024, 1)

def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2))
x = F.max_pool2d(F.relu(self.conv3(x)), (2, 2))
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
x = torch.sigmoid(self.fc2(x))
return x

net = ConvNet()
net.cuda()
optimizer = optim.Adam(net.parameters(), lr=0.03)
loss_function = nn.BCELoss()

class Train:

def __init__(self):
self.len = x.shape[0]
self.x_train = x
self.y_train = y

def __getitem__(self, index):
return x[index], y[index].unsqueeze(0)

def __len__(self):
return self.len

train = Train()
train_loader = DataLoader(dataset=train, batch_size=64, shuffle=True)

epochs = 1
train_losses = list()
for e in range(epochs):
running_loss = 0
for images, labels in train_loader:
optimizer.zero_grad()
log_ps = net(images)
loss = loss_function(log_ps, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print('It\'s working.')

最佳答案

您一定会遇到尺寸不匹配错误,对吗?

那是因为应用卷积后结果的输出形状是 [B, 128, 10, 10]所以 .flatten 的结果将是形状 [B, 128*10*10] .所以需要使用输入大小为12800的线性层.那应该可以解决问题。

所以,只要改变
self.fc1 = nn.Linear(128, 1024) # 128 is wrong here

self.fc1 = nn.Linear(12800, 1024)
通常,为了获得正确尺寸的想法,您可以计算纸上输出的形状,或者只是 print(x.shape)正确位置的 forward 函数中的 debug 语句也可以完成这项工作。

关于python - 在 Pytorch 卷积神经网络中展平张量(大小不匹配错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108988/

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