Skip to main content
 首页 » 编程设计

python之将模型权重加载到新的 tensorflow 图中

2025年02月15日28youxin

目标

我尝试使用 tensorflow 训练 LSTM 模型,以对每个样本 N 个时间步长的数据进行一定次数的迭代,然后随着模型训练慢慢增加每个样本的时间步数。

所以也许 RNN 模型一开始会查看每个训练样本的 4 个时间步长。经过一段时间的训练后,表现趋于平稳。我现在想继续用 8 个时间步训练模型。这基本上是 RNN 微调的一种形式。

进度

看似最直接的方法是在训练一段时间后保存模型,然后使用定义了更多时间步长的新变量 X 重建新图。

不幸的是,我找不到不将时间步数硬编码到我的模型中的方法。但这没关系,因为如果我重新创建模型并用保存的权重填充它,模型形状的形状应该相同,所以它应该可以工作。

所以我第一次运行模型以生成一个保存文件。然后我正在加载该保存文件并尝试使用旧的(几乎相同的) tensorflow 图的权重填充一个新图。

这让我发疯,所以非常感谢任何帮助。

代码

到目前为止,这是我的代码:

if MODEL_FILE is not None: 
    # load from saved model file 
    new_saver = tf.train.import_meta_graph(MODEL_FILE + '.meta') 
 
weights = { 
        'out': tf.Variable(tf.random_uniform([LSTM_SIZE, n_outputs_sm])) 
        } 
biases = { 
        'out': tf.Variable(tf.random_uniform([n_outputs_sm])) 
        } 
 
# setup input X and output Y graph variables 
x = tf.placeholder('float', [None, NUM_TIMESTEPS, n_input], name='input_x') 
y = tf.placeholder('float', [None, n_outputs_sm], name='output_y') 
 
# Feed forward function to get the RNN output. We're using a fancy type of LSTM cell. 
def TFEncoderRNN(inp, weights, biases): 
    # current_input_shape: (batch_size, n_steps, n_input 
    # required shape: 'n_steps' tensors list of shape (batch_size, n_input) 
    inp = tf.unstack(inp, NUM_TIMESTEPS, 1) 
    lstm_cell = tf.contrib.rnn.LayerNormBasicLSTMCell(LSTM_SIZE, dropout_keep_prob=DROPOUT) 
    outputs, states = tf.contrib.rnn.static_rnn(lstm_cell, inp, dtype=tf.float32) 
    return tf.matmul(outputs[-1], weights['out']) + biases['out'] 
 
# we'll be able to call this to get our model output 
pred = TFEncoderRNN(x, weights, biases) 
# define loss and optimizer 
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) 
 
# I define some more stuff here I'll leave out for brevity 
 
init = None 
if new_saver: 
    new_saver.restore(sess, './' + MODEL_FILE) 
    init = tf.initialize_variables([global_step]) 
else: 
    init = tf.global_variables_initializer() 
sess.run(init) 
 
###### 
### TRAIN AND STUFF 
###### 
 
print "Optimization finished!" 
 
# save the current graph, you can just run this script again to 
# continue training 
if SAVE_MODEL: 
    print "Saving model" 
    saver = tf.train.Saver() 
    saver.save(sess, 'tf_model_001') 

关于如何将我训练的模型权重移动到新创建的图形/模型中有什么想法吗?

请您参考如下方法:

The seemingly most straightforward way to do this would be to save the model after training it for a while, then rebuild a new graph with a new Variable X with more timesteps defined.

实际上,这就是 tf.nn.dynamic_rnn 的用途——相同的模型适用于任何序列长度。