gpt4 book ai didi

python - PyTorch:使用 numpy 数组为 GRU/LSTM 手动设置权重参数

转载 作者:太空狗 更新时间:2023-10-29 20:22:20 25 4
gpt4 key购买 nike

我正在尝试使用 pytorch 中手动定义的参数填充 GRU/LSTM。

我有 numpy 参数数组,其形状在其文档 (https://pytorch.org/docs/stable/nn.html#torch.nn.GRU) 中定义。

似乎可以,但我不确定返回值是否正确。

这是用 numpy 参数填充 GRU/LSTM 的正确方法吗?

gru = nn.GRU(input_size, hidden_size, num_layers,
bias=True, batch_first=False, dropout=dropout, bidirectional=bidirectional)

def set_nn_wih(layer, parameter_name, w, l0=True):
param = getattr(layer, parameter_name)
if l0:
for i in range(3*hidden_size):
param.data[i] = w[i*input_size:(i+1)*input_size]
else:
for i in range(3*hidden_size):
param.data[i] = w[i*num_directions*hidden_size:(i+1)*num_directions*hidden_size]

def set_nn_whh(layer, parameter_name, w):
param = getattr(layer, parameter_name)
for i in range(3*hidden_size):
param.data[i] = w[i*hidden_size:(i+1)*hidden_size]

l0=True

for i in range(num_directions):
for j in range(num_layers):
if j == 0:
wih = w0[i, :, :3*input_size]
whh = w0[i, :, 3*input_size:] # check
l0=True
else:
wih = w[j-1, i, :, :num_directions*3*hidden_size]
whh = w[j-1, i, :, num_directions*3*hidden_size:]
l0=False

if i == 0:
set_nn_wih(
gru, "weight_ih_l{}".format(j), torch.from_numpy(wih.flatten()),l0)
set_nn_whh(
gru, "weight_hh_l{}".format(j), torch.from_numpy(whh.flatten()))
else:
set_nn_wih(
gru, "weight_ih_l{}_reverse".format(j), torch.from_numpy(wih.flatten()),l0)
set_nn_whh(
gru, "weight_hh_l{}_reverse".format(j), torch.from_numpy(whh.flatten()))

y, hn = gru(x_t, h_t)

numpy 数组定义如下:

rng = np.random.RandomState(313)
w0 = rng.randn(num_directions, hidden_size, 3*(input_size +
hidden_size)).astype(np.float32)
w = rng.randn(max(1, num_layers-1), num_directions, hidden_size,
3*(num_directions*hidden_size + hidden_size)).astype(np.float32)

最佳答案

这是一个很好的问题,你已经给出了一个不错的答案。然而,它重新发明了轮子 - 有一个非常优雅的 Pytorch 内部例程,可以让您轻松完成同样的事情 - 并且适用于任何网络。

这里的核心概念是PyTorch的state_dict。状态字典有效地包含由 nn.Modules 及其子模块等的关系给出的树结构组织的参数

简短的回答

如果您只希望代码使用 state_dict 将值加载到张量中,请尝试这一行(其中 dict 包含有效的 state_dict):

`model.load_state_dict(dict, strict=False)`

strict=False 如果您想加载 仅一些参数值 则至关重要。

长答案 - 包括对 PyTorch 的 state_dict 的介绍

这是状态字典如何查找 GRU 的示例(我选择了 input_size = hidden_​​size = 2 以便我可以打印整个状态字典):

rnn = torch.nn.GRU(2, 2, 1)
rnn.state_dict()
# Out[10]:
# OrderedDict([('weight_ih_l0', tensor([[-0.0023, -0.0460],
# [ 0.3373, 0.0070],
# [ 0.0745, -0.5345],
# [ 0.5347, -0.2373],
# [-0.2217, -0.2824],
# [-0.2983, 0.4771]])),
# ('weight_hh_l0', tensor([[-0.2837, -0.0571],
# [-0.1820, 0.6963],
# [ 0.4978, -0.6342],
# [ 0.0366, 0.2156],
# [ 0.5009, 0.4382],
# [-0.7012, -0.5157]])),
# ('bias_ih_l0',
# tensor([-0.2158, -0.6643, -0.3505, -0.0959, -0.5332, -0.6209])),
# ('bias_hh_l0',
# tensor([-0.1845, 0.4075, -0.1721, -0.4893, -0.2427, 0.3973]))])

所以state_dict网络的所有参数。如果我们“嵌套”了 nn.Modules,我们会得到由参数名称表示的树:

class MLP(torch.nn.Module):      
def __init__(self):
torch.nn.Module.__init__(self)
self.lin_a = torch.nn.Linear(2, 2)
self.lin_b = torch.nn.Linear(2, 2)


mlp = MLP()
mlp.state_dict()
# Out[23]:
# OrderedDict([('lin_a.weight', tensor([[-0.2914, 0.0791],
# [-0.1167, 0.6591]])),
# ('lin_a.bias', tensor([-0.2745, -0.1614])),
# ('lin_b.weight', tensor([[-0.4634, -0.2649],
# [ 0.4552, 0.3812]])),
# ('lin_b.bias', tensor([ 0.0273, -0.1283]))])


class NestedMLP(torch.nn.Module):
def __init__(self):
torch.nn.Module.__init__(self)
self.mlp_a = MLP()
self.mlp_b = MLP()


n_mlp = NestedMLP()
n_mlp.state_dict()
# Out[26]:
# OrderedDict([('mlp_a.lin_a.weight', tensor([[ 0.2543, 0.3412],
# [-0.1984, -0.3235]])),
# ('mlp_a.lin_a.bias', tensor([ 0.2480, -0.0631])),
# ('mlp_a.lin_b.weight', tensor([[-0.4575, -0.6072],
# [-0.0100, 0.5887]])),
# ('mlp_a.lin_b.bias', tensor([-0.3116, 0.5603])),
# ('mlp_b.lin_a.weight', tensor([[ 0.3722, 0.6940],
# [-0.5120, 0.5414]])),
# ('mlp_b.lin_a.bias', tensor([0.3604, 0.0316])),
# ('mlp_b.lin_b.weight', tensor([[-0.5571, 0.0830],
# [ 0.5230, -0.1020]])),
# ('mlp_b.lin_b.bias', tensor([ 0.2156, -0.2930]))])

那么 - 如果您不想提取状态指令,而是更改它 - 从而更改网络参数怎么办?使用 nn.Module.load_state_dict(state_dict, strict=True) ( link to the docs )此方法允许您将具有任意值的整个 state_dict 加载到同类实例化模型中,只要键(即参数名称)正确且值(即参数)torch.tensors 正确的形状。如果 strict kwarg 设置为 True(默认值),则您加载的字典必须与原始状态字典完全匹配,参数值除外。也就是说,每个参数都必须有一个新值。

对于上面的 GRU 示例,我们需要为每个 'weight_ih_l0'、'weight_hh_l0'、'bias_ih_l0'、'bias_hh_l0' .由于我们有时只想加载 一些 值(正如我想你想做的那样),我们可以将 strict kwarg 设置为 False - 并且然后我们可以只加载部分状态指令,例如一个只包含 'weight_ih_l0' 的参数值。

作为一个实用的建议,我会简单地创建你想要加载值的模型,然后打印状态字典(或者至少是一个键列表和各自的张量大小)

print([k, v.shape for k, v in model.state_dict().items()])

这会告诉您要更改的参数的确切名称。然后,您只需使用相应的参数名称和张量创建一个状态字典,并加载它:

from dollections import OrderedDict
new_state_dict = OrderedDict({'tensor_name_retrieved_from_original_dict': new_tensor_value})
model.load_state_dict(new_state_dict, strict=False)

关于python - PyTorch:使用 numpy 数组为 GRU/LSTM 手动设置权重参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52945427/

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