【问题标题】:pytorch acess of weights and biases from a spcecific neuronpytorch 访问特定神经元的权重和偏差
【发布时间】:2020-01-03 04:33:34
【问题描述】:

例如:

input_size = 784
hidden_sizes = [128, 64]
output_size = 10

# Build a feed-forward network
model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),
                      nn.ReLU(),
                      nn.Linear(hidden_sizes[0], hidden_sizes[1]),
                      nn.ReLU(),
                      nn.Linear(hidden_sizes[1], output_size),
                      nn.Softmax(dim=1))

我想访问特定层中 N-TH 神经元的所有权重和偏差。我知道model.layer[1].weight 可以访问一层中的所有权重,但我也想知道这个权重是什么神经元。

【问题讨论】:

标签: python neural-network pytorch


【解决方案1】:

假设层中有 n 个神经元, 权重应该按照从神经元[0]到神经元[n]的顺序。 例如访问全连接层的权重

Parameter containing:
tensor([[-7.3584e-03, -2.3753e-02, -2.2565e-02,  ...,  2.1965e-02,
      1.0699e-02, -2.8968e-02], #1st neuron weights
    [ 2.2930e-02, -2.4317e-02,  2.9939e-02,  ...,  1.1536e-02,
      1.9830e-02, -1.4294e-02], #2nd neuron weights
    [ 3.0891e-02,  2.5781e-02, -2.5248e-02,  ..., -1.5813e-02,
      6.1708e-03, -1.8673e-02], #3rd neuron weights
    ...,
    [-1.2596e-03, -1.2320e-05,  1.9106e-02,  ...,  2.1987e-02,
     -3.3817e-02, -9.4880e-03], #nth neuron weights
    [ 1.4234e-02,  2.1246e-02, -1.0369e-02,  ..., -1.2366e-02,
     -4.7024e-04, -2.5259e-02], #(n+1)th neuron weights
    [ 7.5356e-03,  3.4400e-02, -1.0673e-02,  ...,  2.8880e-02,
     -1.0365e-02, -1.2916e-02] #(n+2)th neuron weights], requires_grad=True)

例如

[-7.3584e-03, -2.3753e-02, -2.2565e-02, ..., 2.1965e-02, 1.0699e-02, -2.8968e-02] 将是第一个神经元的所有权重

-7.3584e-03 是下一层第一个神经元的权重

-2.3753e-02 是下一层第二个神经元的权重

-2.2565e-02 是下一层第三个神经元的权重

[ 2.2930e-02, -2.4317e-02, 2.9939e-02, ..., 1.1536e-02, 1.9830e-02, -1.4294e-02] 将是第二个神经元的所有权重

2.2930e-02 是下一层第一个神经元的权重

-2.4317e-02 是下一层第二个神经元的权重

-2.2565e-02 是下一层第三个神经元的权重

【讨论】:

    【解决方案2】:

    一个权重 w_ij^L 连接两个神经元,第 i 个神经元(在 L+1 层)和第 j 个神经元(在 L 层):

    model[2*L].weight[i, j]  # w_ij^L
    

    其中 L = 0、1、2。注意:我使用 2*L 是因为模型的线性层被索引为 0、2 和 4。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-01
      • 2016-08-17
      • 2020-04-01
      • 2021-11-07
      • 2017-12-14
      • 2016-09-08
      • 2019-04-10
      • 2015-05-11
      相关资源
      最近更新 更多