- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试使用 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
如果您想加载 仅一些参数值 则至关重要。
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/
我有几个系统,其中包含用户表以及某种形式的业力/权重/声誉。有时是用户发布的帖子数量,有时是用户在网站上的所有事件中收到的赞成/反对票数。 USER { id int name str
我需要能够使用填充的相对大小 - 根据设备的分辨率和 dpi 变大或变小。 例如,如果我的 View 宽度为 100 像素,我希望左侧填充 10 像素,右侧填充 10 像素。但是,如果它在更高密度的屏
我目前正在使用由大约 10 个字段组成的 Solr 索引数据。当我执行搜索时,我希望某些字段的权重更高。谁能帮我指出正确的方向? 例如,在所有字段中搜索“超人”等术语时,应在“Description”
我正在使用 igraph 模拟网络随时间的变化在 r并且我正在寻找一种有效且可扩展的方式来对此进行编码以用于业务。 网络变化的主要驱动因素是: 新增节点 新领带 新节点权重 在第一阶段,在 100 个
我一直在寻找一种使用OpenVINO框架上的C++ API获取网络每一层权重/参数和偏差张量的方法。我在文档中找不到任何内容,在示例中也找不到任何示例。我如何提取这些张量? 谢谢, 塞萨尔 编辑: 分
我的问题与 PHP Memcache 扩展的 addServer 函数中的“weight”参数有关。 在过去的几个月里,我一直在为所有服务器使用“weight = 1”。我现在正在尝试应用以下配置以最
我应该使用哪种数据结构来保持元素按给定权重排序?我需要在集合中添加元素,其中每个元素都会生成特定的权重,但该权重不包含(也不计算)在元素本身内部;它是由元素之外的其他人计算的。而且,权重不需要存储(但
我正在尝试在 keras/tensorflow 中使用具有多个类的焦点损失,这导致使用我猜的分类焦点损失。我找到了一些实现here和 there或there 。 据我了解,焦点损失中的参数a主要用于二
我有一个像这样的 Pandas 数据框: df = pd.DataFrame({'id': [121, 34324, 111, 12, 45, 232], 'weight'
我有一个带有输出神经元的神经网络,我想在软最大化之前使用经过训练的权重进行线性缩放。 我有 10 个输出,我想要 10 个权重,在输出被软最大化之前乘以每个输出。因此每个输出的权重为 1。 但我不断收
我有这样的布局: 我希望它看起来像: TextView - 宽度的 40%,带 ImageView 的布局
这让我彻底疯了。我想在 android 中使用有点复杂的布局。我正在尝试使用权重而不是固定事物的大小。也许我应该放弃…… 这是我想做的: 我想要 3 个 ScrollView (里面有 TextVie
我正在尝试开发类似于网格但使用 LinearLayout。我想在单行中有 3 张图像和图像后的确切底部文本。 我尝试过的: LinearLayout layout = new LinearLayout
我想在同一行添加一个 EditText 和一个 Button,我想将 80% 的行给 editText,20% 给 Button。 这是我的代码:
我有一个 mysql 表,其中存储一列(称为 tickets),并且 tickets 值可以是任意数字。 我想要做的是有一个mysql查询,从列中选择所有行,按降序对它们进行排序,然后使用PHP对查询
我搜索了一段时间,但结果让我很困惑,因为我对 MySQL 还很陌生。 我有一个包含这 4 列的表:AUTO_INCREMENT ID、NAME、TYPE、CHANCE 所以行看起来像这样: 1, NO
我不完全是 JS 专业人士,虽然不漂亮或高效,但这是有效的。 实际上,我在表单中有重复的字段组,并允许用户根据需要将数据从第一个字段复制到所有 5 个字段。 如何使这段代码更高效? function
我正在使用xgboost库来训练二元分类器。我想通过向权重添加噪声(例如集合中树的叶节点的值)来防止训练算法的数据泄漏。为此,我需要检索每棵树的权重并修改它们。 我可以通过在 Booster 对象上使
我正在尝试让 LinearLayout 中的 View 填充宽度。我尝试使用 LayoutParams 设置它,但它给了我一个错误: 我的代码: EditText et = new EditText(
我想改变 ScrollView 的权重,但找不到实现它的方法。 这是我的 XML: **other layout.. 从代码中只能设置scrollView的高度或者宽度,weigh
我是一名优秀的程序员,十分优秀!