首页 文章

将模型权重加载到新的张量流图中

提问于
浏览
2

目标

使用张量流,我试图训练LSTM模型对每个样本N步的数据进行一定次数的迭代,然后在模型训练时慢慢增加每个样本的时间步数 .

因此,RNN模型可能首先考虑每个训练样本4个时间步长 . 训练一段时间后,性能水平不断提升 . 我想现在继续训练8个时间步的模型 . 这基本上是RNN微调的一种形式 .

进展

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

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

所以我'm running the model a first time to generate a save file. Then I'm加载保存文件并尝试使用旧(几乎相同)张量流图中的权重填充新图 .

这一直让我发疯,所以任何帮助都非常感激 .

代码

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

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')

关于如何将训练过的模型权重移动到新创建的图形/模型中的任何想法?

1 回答

  • 1

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

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

相关问题