gpt4 book ai didi

pytorch - 可以在 Pytorch nn.Sequential() 中添加条件

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

有没有办法在 nn.Sequential() 中添加条件语句? .类似于下面的代码。

import torch


class Building_Blocks(torch.nn.Module):
def conv_block (self, in_features, out_features, kernal_size, upsample=False):
block = torch.nn.Sequential(
torch.nn.Conv2d(in_features, out_features, kernal_size),
torch.nn.ReLU(inplace = True),
torch.nn.Conv2d(out_features, out_features, kernal_size),
torch.nn.ReLU(inplace = True),
if(upsample):
torch.nn.ConvTranspose2d(out_features, out_features, kernal_size)
)
return block

def __init__(self):
super(Building_Blocks, self).__init__()
self.contracting_layer1 = self.conv_block(3, 64, 3, upsample=True)

def forward(self, x):
x=self.contracting_layer1(x)
return x

最佳答案

不,但在您的情况下很容易接受 ifnn.Sequential :

class Building_Blocks(torch.nn.Module):
def conv_block(self, in_features, out_features, kernal_size, upsample=False):
layers = [
torch.nn.Conv2d(in_features, out_features, kernal_size),
torch.nn.ReLU(inplace=True),
torch.nn.Conv2d(out_features, out_features, kernal_size),
torch.nn.ReLU(inplace=True),
]
if upsample:
layers.append(
torch.nn.ConvTranspose2d(out_features, out_features, kernal_size)
)
block = torch.nn.Sequential(*layers)
return block

def __init__(self):
super(Building_Blocks, self).__init__()
self.contracting_layer1 = self.conv_block(3, 64, 3, upsample=True)

def forward(self, x):
x = self.contracting_layer1(x)
return x

你总是可以构建一个 list包含您想要的图层并将其解压缩到 torch.nn.Sequential然后。

关于pytorch - 可以在 Pytorch nn.Sequential() 中添加条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61545224/

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