【问题标题】:set variable network layers based on parameters in pytorch根据 pytorch 中的参数设置可变网络层
【发布时间】:2021-08-17 00:26:26
【问题描述】:

我想将以下网络定义设为参数化。连续和离散列的数量因数据而异。我首先从带有 relu 激活的线性传递整个输入数据,在这种情况下是 110 维。我的数据的每个分类字段的输出根据之前的 one-hot 编码数据转换而变化。我需要为它们中的每一个定义一个 nn.Linear(110, number of encodings)。

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 部分,使用离散列输入,这是一个有序字典,它具有我的数据的每个分类字段的单热编码的名称和编号作为键和值,和 Continuous_columns,它只是一个包含连续列名称的列表。但我不知道如何编辑转发部分:

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

【问题讨论】:

    标签: python neural-network pytorch


    【解决方案1】:

    你不需要使用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
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2020-12-17
      • 2023-02-17
      • 2018-07-01
      • 2016-06-05
      • 2021-12-30
      • 1970-01-01
      • 2019-11-17
      • 2019-04-13
      相关资源
      最近更新 更多