Python 根据pytorch中的参数设置可变网络层
我想将以下网络定义设置为参数化网络定义。连续列和离散列的数量因数据而异。我首先传递整个输入数据,在本例中是110维的,来自一个线性的relu激活。我的数据的每个分类字段的输出根据前一个热编码数据转换而变化。我需要为它们中的每一个定义一个nn.Linear(110,编码数)Python 根据pytorch中的参数设置可变网络层,python,neural-network,pytorch,Python,Neural Network,Pytorch,我想将以下网络定义设置为参数化网络定义。连续列和离散列的数量因数据而异。我首先传递整个输入数据,在本例中是110维的,来自一个线性的relu激活。我的数据的每个分类字段的输出根据前一个热编码数据转换而变化。我需要为它们中的每一个定义一个nn.Linear(110,编码数) class Generator(nn.Module): def __init__(self): super(Generator, self).__init__(110) self.lin1 = nn.Lin
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__(110)
self.lin1 = nn.Linear(110,110)
self.lin_numerical = nn.Linear(110, 6)
self.lin_cat_job = nn.Linear(110, 9)
self.lin_cat_sex = nn.Linear(110, 2)
self.lin_cat_incomeclass = nn.Linear(110, 7)
def forward(self, x):
x = torch.relu(self.lin1(x))
x_numerical = f.leaky_relu(self.lin_numerical(x))
x_cat1 = f.gumbel_softmax(self.lin_cat_job(x), tau=0.2)
x_cat2 = f.gumbel_softmax(self.lin_cat_sex(x), tau=0.2)
x_cat3 = f.gumbel_softmax(self.lin_cat_incomeclass(x), tau=0.2)
x_final = torch.cat((x_numerical, x_cat1, x_cat2, x_cat3),1)
return x_final
我已经设法更改了init部分,使用离散列输入,这是一个有序的DICT,将我的数据的每个分类字段的一个热编码的名称和编号作为键和值,以及连续列,它只是一个带有连续列名称的列表。但我不知道如何编辑转发部分:
class Generator(nn.Module):
def __init__(self, input_dim, continuous_columns, discrete_columns):
super(Generator, self).__init__()
self._input_dim = input_dim
self._discrete_columns = discrete_columns
self._num_continuous_columns = len(continuous_columns)
self.lin1 = nn.Linear(self._input_dim, self._input_dim)
self.lin_numerical = nn.Linear(self._input_dim, self._num_continuous_columns)
for key, value in self._discrete_columns.items():
setattr(self, "lin_cat_{}".format(key), nn.Linear(self._input_dim, value))
def forward(self, x):
x = torch.relu(self.lin1(x))
x_numerical = f.leaky_relu(self.lin_numerical(x))
####
This is the problematic part
#####
return x
您不需要使用
setattr
,老实说,也不应该使用,因为您需要getattr
,如果有任何其他方法来完成这项工作,那么它带来的麻烦比它解决的要多
这就是我要做的
self.lin_cat = nn.ModuleDict()
for key, value in self._discrete_columns.items():
self.lin_cat[key] = nn.Linear(self._input_dim, value)
# setattr(self, "lin_cat_{}".format(key), nn.Linear(self._input_dim, value))
def forward(self, x):
x = torch.relu(self.lin1(x))
x_numerical = f.leaky_relu(self.lin_numerical(x))
x_cat = []
for key in self.lin_cat:
x_cat.append(f.gumbel_softmax(self.lin_cat[key](x), tau=0.2))
x_final = torch.cat((x_numerical, *x_cat), 1)
return x