如何获得神经网络中每个神经元的进出边权重?
How can I get the in and out edges weights for each neuron in a neural network?
假设我有以下网络
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(1, 2)
self.fc2 = nn.Linear(2, 3)
self.fc3 = nn.Linear(3, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Model()
我知道我可以访问每一层的权重(即边):
net.fc1.weight
但是,我正在尝试创建一个函数,该函数从整个网络中随机选择一个神经元并输出它的内部连接(即从上一层附加到它的 edges/weights)及其出连接(即从它到下一层的 edges/weights)。
伪代码:
def get_neuron_in_out_edges(list_of_neurons):
shuffled_list_of_neurons = shuffle(list_of_neurons)
in_connections_list = []
out_connections_list = []
for neuron in shuffled_list_of_neurons:
in_connections = get_in_connections(neuron) # a list of connections
out_connections = get_out_connections(neuron) # a list of connections
in_connections_list.append([neuron,in_connections])
out_connections_list.append([neuron,out_connections])
return in_connections_list, out_connections_list
我的想法是,我可以访问这些值并说如果它们小于 10
,则在网络中将它们更改为 10
。这是针对网络 class 的,我们正在其中绘制不同的网络,因此从机器学习的角度来看这没有多大意义
让我们忽略此讨论的偏见。
线性层计算输出 y
给定权重 w
和输入 x
为:
y_i = sum_j w_ij x_j
因此,对于神经元 i
,所有传入边都是权重 w_ij
- 即第 i
-第 行 权重矩阵 W
.
同样,对于输入神经元j
,它影响所有y_i
根据权重矩阵j
-第列 17=].
假设我有以下网络
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(1, 2)
self.fc2 = nn.Linear(2, 3)
self.fc3 = nn.Linear(3, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Model()
我知道我可以访问每一层的权重(即边):
net.fc1.weight
但是,我正在尝试创建一个函数,该函数从整个网络中随机选择一个神经元并输出它的内部连接(即从上一层附加到它的 edges/weights)及其出连接(即从它到下一层的 edges/weights)。
伪代码:
def get_neuron_in_out_edges(list_of_neurons):
shuffled_list_of_neurons = shuffle(list_of_neurons)
in_connections_list = []
out_connections_list = []
for neuron in shuffled_list_of_neurons:
in_connections = get_in_connections(neuron) # a list of connections
out_connections = get_out_connections(neuron) # a list of connections
in_connections_list.append([neuron,in_connections])
out_connections_list.append([neuron,out_connections])
return in_connections_list, out_connections_list
我的想法是,我可以访问这些值并说如果它们小于 10
,则在网络中将它们更改为 10
。这是针对网络 class 的,我们正在其中绘制不同的网络,因此从机器学习的角度来看这没有多大意义
让我们忽略此讨论的偏见。
线性层计算输出 y
给定权重 w
和输入 x
为:
y_i = sum_j w_ij x_j
因此,对于神经元 i
,所有传入边都是权重 w_ij
- 即第 i
-第 行 权重矩阵 W
.
同样,对于输入神经元j
,它影响所有y_i
根据权重矩阵j
-第列 17=].