RuntimeError: mat1 and mat2 shapes cannot be multiplied

RuntimeError: mat1 and mat2 shapes cannot be multiplied

我正在尝试将形状为 ( 1, 8, 32, 32, 32 ) 的 5D 张量输入到我写的 VAE 中:

self.encoder = nn.Sequential(
        nn.Conv3d( 8, 16, 4, 2, 1 ), # 32 -> 16
        nn.BatchNorm3d( 16 ), 
        nn.LeakyReLU( 0.2 ),
        
        nn.Conv3d( 16, 32, 4, 2, 1 ), # 16 -> 8
        nn.BatchNorm3d( 32 ),
        nn.LeakyReLU( 0.2 ),
        
        nn.Conv3d( 32, 48, 4, 2, 1 ), # 16 -> 4
        nn.BatchNorm3d( 48 ),
        nn.LeakyReLU( 0.2 ), 
    )
    
    self.fc_mu = nn.Linear( 3072, 100 ) # 48*4*4*4 = 3072
    self.fc_logvar = nn.Linear( 3072, 100 )
    
self.decoder = nn.Sequential(
    nn.Linear( 100, 3072 ),
    nn.Unflatten( 1, ( 48, 4, 4 )),
    nn.ConvTranspose3d( 48, 32, 4, 2, 1 ), # 4 -> 8
    nn.BatchNorm3d( 32 ),
    nn.Tanh(),
        
    nn.ConvTranspose3d( 32, 16, 4, 2, 1 ), # 8 -> 16
    nn.BatchNorm3d( 16 ),
    nn.Tanh(),
        
    nn.ConvTranspose3d( 16, 8, 4, 2, 1 ), # 16 -> 32
    nn.BatchNorm3d( 8 ),
    nn.Tanh(), 
)

def reparametrize( self, mu, logvar ):
    std = torch.exp( 0.5 * logvar )
    eps = torch.randn_like(  std )
    return mu + eps * std 

def encode( self, x ) :
    x = self.encoder( x )
    x = x.view( -1, x.size( 1 ))
    
    mu = self.fc_mu( x )
    logvar = self.fc_logvar( x )
    
    return self.reparametrize( mu, logvar ), mu, logvar 
    
def decode( self, x ):
    return self.decoder( x )
    
def forward( self, data ):
    z, mu, logvar = self.encode( data )
    return self.decode( z ), mu, logvar 

我得到的错误是:RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x48 and 3072x100)。我以为我已经正确计算了每一层的输出尺寸,但我一定是错了,但我不确定在哪里。

这一行

x = x.view( -1, x.size( 1 ))

意味着您将第二个维度(通道)保持原样,并将其他所有内容放在第一个维度(批次)中。

由于 self.encoder 的输出是 (1, 48, 4, 4, 4),这样做意味着你会得到 (64, 48),但从它的外观来看,我认为你想要 (1, 3072)相反。

所以这应该可以解决这个特定问题。

x = x.view(x.size(0), -1)

然后你会 运行 进入 RuntimeError: unflatten: Provided sizes [48, 4, 4] don't multiply up to the size of dim 1 (3072) in the input tensor

原因是这里的unflatten

nn.Linear(100, 3072),
nn.Unflatten(1, (48, 4, 4)),
nn.ConvTranspose3d(48, 32, 4, 2, 1)

必须改为 (48, 4, 4, 4)