手动从 Tensorflow 导入 LSTM 到 PyTorch

     2023-02-16     265

关键词:

【中文标题】手动从 Tensorflow 导入 LSTM 到 PyTorch【英文标题】:Import LSTM from Tensorflow to PyTorch by hand 【发布时间】:2019-08-09 07:25:51 【问题描述】:

我正在尝试将预训练模型从 tensorflow 导入 PyTorch。它接受单个输入并将其映射到单个输出。 当我尝试导入 LSTM 权重时,出现了混乱

我使用以下函数从文件中读取权重及其变量:

def load_tf_model_weights():        

    modelpath = 'models/model1.ckpt.meta'

    with tf.Session() as sess:        
        tf.train.import_meta_graph(modelpath) 
        init = tf.global_variables_initializer()
        sess.run(init)  
        vars = tf.trainable_variables()        
        W = sess.run(vars)

    return W,vars

W,V = load_tf_model_weights()

然后我正在检查权重的形状

In [33]:  [w.shape for w in W]
Out[33]: [(51, 200), (200,), (100, 200), (200,), (50, 1), (1,)]

此外,变量定义为

In [34]:    V
Out[34]: 
[<tf.Variable 'rnn/multi_rnn_cell/cell_0/lstm_cell/kernel:0' shape=(51, 200) dtype=float32_ref>,
<tf.Variable 'rnn/multi_rnn_cell/cell_0/lstm_cell/bias:0' shape=(200,) dtype=float32_ref>,
<tf.Variable 'rnn/multi_rnn_cell/cell_1/lstm_cell/kernel:0' shape=(100, 200) dtype=float32_ref>,
<tf.Variable 'rnn/multi_rnn_cell/cell_1/lstm_cell/bias:0' shape=(200,) dtype=float32_ref>,
<tf.Variable 'weight:0' shape=(50, 1) dtype=float32_ref>,
<tf.Variable 'FCLayer/Variable:0' shape=(1,) dtype=float32_ref>]

所以我可以说W 的第一个元素定义了 LSTM 的内核,第二个元素定义了它的偏差。根据this post,内核的形状定义为 [input_depth + h_depth, 4 * self._num_units] 偏差为[4 * self._num_units]。我们已经知道input_depth1。所以我们得到,h_depth_num_units 都有 50 的值。

在 pytorch 中,我想要为其分配权重的 LSTMCell 如下所示:

In [38]: cell = nn.LSTMCell(1,50)
In [39]: [p.shape for p in cell.parameters()]
Out[39]: 
[torch.Size([200, 1]),
torch.Size([200, 50]),
torch.Size([200]),
torch.Size([200])]

前两个条目可以被W 的第一个值覆盖,其形状为(51,200)。但是来自 Tensorflow 的 LSTMCell 只产生一个形状偏差 (200) 而 pytorch 想要其中两个

通过排除偏差,我还剩下了权重:

cell2 = nn.LSTMCell(1,50,bias=False)
[p.shape for p in cell2.parameters()]
Out[43]: [torch.Size([200, 1]), torch.Size([200, 50])]

谢谢!

【问题讨论】:

【参考方案1】:

pytorch 使用 CuDNN 的 LSTM 底层(即使你没有 CUDA,它仍然使用兼容的东西)因此它有一个额外的偏置项。

因此,您可以选择两个总和等于 1 的数字(0 和 1、1/2 和 1/2 或其他任何值),并将您的 pytorch 偏差设置为这些数字乘以 TF 的偏差。

pytorch_bias_1 = torch.from_numpy(alpha * tf_bias_data)
pytorch_bias_2 = torch.from_numpy((1.0-alpha) * tf_bias_data)

【讨论】:

Tensorflow:如何将预训练模型已经嵌入的数据输入到 LSTM 模型中?

】Tensorflow:如何将预训练模型已经嵌入的数据输入到LSTM模型中?【英文标题】:Tensorflow:Howtoinputdataalreadyembeddedbypre-trainmodelintoaLSTMmodel?【发布时间】:2022-01-2003:06:37【问题描述】:我是TensorFlow的新手。我正在构建一个简单的LSTM... 查看详情

使用 tensorflow 理解 LSTM 模型进行情感分析

】使用tensorflow理解LSTM模型进行情感分析【英文标题】:UnderstandingLSTMmodelusingtensorflowforsentimentanalysis【发布时间】:2017-11-0706:06:23【问题描述】:我正在尝试学习使用Tensorflow进行情感分析的LSTM模型,我已经通过了LSTMmodel。以下... 查看详情

TensorFlow LSTM 预测相同的值

】TensorFlowLSTM预测相同的值【英文标题】:TensorFlowLSTMpredictingsamevalue【发布时间】:2021-06-1300:17:23【问题描述】:我想要做的是向我的LSTM模型输入一个数字列表,并让我的LSTM模型输出它自己的数字列表。我的项目是一个程序,... 查看详情

TensorFlow Serving - 有状态的 LSTM

】TensorFlowServing-有状态的LSTM【英文标题】:TensorflowServing-StatefulLSTM【发布时间】:2017-09-2808:55:42【问题描述】:是否有规范的方式来使用TensorflowServing维护有状态的LSTM等?直接使用TensorflowAPI这很简单-但我不确定在将模型导出到... 查看详情

tensorflow1.4之lstm的使用(代码片段)

TensorFlowDataFlowGraph一:层的理解为了形象的理解神经网络,我们提出了层的概念,虽然这更加的形象了,但同时也给初学者带来了很多困扰和不太理解的地方,主要就是在涉及到代码的时候。层的责任可以理解为三个,一是从某... 查看详情

TensorFlow:为下一批记住 LSTM 状态(有状态 LSTM)

】TensorFlow:为下一批记住LSTM状态(有状态LSTM)【英文标题】:TensorFlow:RememberLSTMstatefornextbatch(statefulLSTM)【发布时间】:2016-11-0912:46:39【问题描述】:给定一个训练有素的LSTM模型,我想对单个时间步执行推理,即以下示例中的se... 查看详情

如何将 keras LSTM 层的输出输入到输入层?

...putlayer?【发布时间】:2020-03-1219:03:53【问题描述】:我对tensorflow和keras还很陌生,有一个问题。我想使用LSTM层进行时间序列预测,并进行一些修改。我从tensorflow教程中给出的示例开始defbuild_LSTM(neurons,batch_size,h 查看详情

注意力机制/Tensorflow 教程

】注意力机制/Tensorflow教程【英文标题】:AttentionMechanism/TensorflowTutorials【发布时间】:2020-10-0800:35:18【问题描述】:我正在尝试改进我的注意力机制代码草案,其中我基本上对解码器步骤进行了迭代,并且LSTM解码器单元在每个... 查看详情

学习tensorflow的lstm的rnn例子

 学习Tensorflow的LSTM的RNN例子 基于TensorFlow一次简单的RNN实现 极客学院-递归神经网络 如何使用TensorFlow构建、训练和改进循环神经网络 查看详情

tensorflow 如何确定将选择哪些 LSTM 单元作为输出?

】tensorflow如何确定将选择哪些LSTM单元作为输出?【英文标题】:HowdoestensorflowdeterminewhichLSTMunitswillbeselectedasoutputs?【发布时间】:2021-06-1213:31:33【问题描述】:我使用以下代码创建了一个LSTM模型:model=tensorflow1.keras.Sequential()model... 查看详情

Tensorflow 中 LSTM 层的门权重顺序

】Tensorflow中LSTM层的门权重顺序【英文标题】:GateweightsorderforLSTMlayersinTensorflow【发布时间】:2021-10-2100:58:57【问题描述】:我有一个包含一些LSTM层的Keras模型。我知道我可以通过get_weights()方法得到LSTM层的权重,结果是一个由三... 查看详情

从 pyspark 导入 TensorFlow 数据

】从pyspark导入TensorFlow数据【英文标题】:ImportTensorFlowdatafrompyspark【发布时间】:2018-04-3013:52:36【问题描述】:我想基于数百GB的数据创建一个预测模型。数据需要一些不密集的预处理,我可以在pyspark中进行,但在tensorflow中则... 查看详情

使用 Tensorflow 进行 LSTM 单步预测

】使用Tensorflow进行LSTM单步预测【英文标题】:LSTMone-step-aheadpredictionwithTensorflow【发布时间】:2017-09-1414:16:42【问题描述】:我正在使用Tensorflow的GRUCell+MultiRNNCell+dynamic_rnn组合来生成多层LSTM来预测一系列元素。在我见过的几个例... 查看详情

tensorflow笔记:多层lstm代码分析(代码片段)

tensorflow笔记:多层LSTM代码分析标签(空格分隔):tensorflow笔记tensorflow笔记系列:(一)tensorflow笔记:流程,概念和简单代码注释(二)tensorflow笔记:多层CNN代码分析 查看详情

第二十一节,使用tensorflow实现lstm和gru网络(代码片段)

本节主要介绍在TensorFlow中实现LSTM以及GRU网络。关于LSTM的详细内容推荐阅读以下博客:LSTM模型与前向反向传播算法深度学习笔记(五):LSTMtensorflow笔记:多层LSTM代码分析 一LSTM网络LongShortTerm网络——一般就叫做LSTM——是一种... 查看详情

未能在 tensorflow 中训练玩具 LSTM

】未能在tensorflow中训练玩具LSTM【英文标题】:FailedtotraintoyLSTMintensorflow【发布时间】:2018-09-0419:52:44【问题描述】:我正在尝试使用一个用于序列分类的玩具问题来熟悉tensorflow中的循环网络。数据:half_len=500pos_ex=[1,2,3,4,5]#Positi... 查看详情

tensorflow如何入门?

1.TensorFlow是什么是一个深度学习库,由Google开源,可以对定义在Tensor(张量)上的函数自动求导。Tensor(张量)意味着N维数组,Flow(流)意味着基于数据流图的计算,TensorFlow即为张量从图的一端流动到另一端。它的一大亮点是支持异构... 查看详情

在 Tensorflow 中运行 LSTM 时出现 ResourceExhausted 错误或 OOM

】在Tensorflow中运行LSTM时出现ResourceExhausted错误或OOM【英文标题】:ResourceExhaustedErrororOOMwhenrunningLSTMinTensorflow【发布时间】:2018-10-1423:53:53【问题描述】:我正在使用以下代码在Tensorflow中训练我的LSTM网络:importpandasaspdimportnumpyasn... 查看详情