我正试图通过拾取TensorFlow中的模型训练来重新开始.我想使用最近添加的(0.12 +我认为)import_meta_graph()
,以便不重建图形.
我见过这方面的解决方案,例如Tensorflow:如何保存/恢复模型?,但是我遇到了AdamOptimizer的问题,特别是我得到了一个ValueError: cannot add op with name <my weights variable name>/Adam as that name is already used
错误.这可以通过初始化来修复,但我的模型值会被清除!
还有其他答案和一些完整的例子,但它们似乎总是较旧,因此不包括较新的import_meta_graph()
方法,或者没有非张量优化器.我能找到的最接近的问题是tensorflow:保存和恢复会话,但没有最终的明确解决方案,这个例子非常复杂.
理想情况下,我想要一个简单的可运行示例从头开始,停止,然后再次拾起.我有一些有用的东西(下图),但也想知道我是否遗漏了什么.当然,我不是唯一一个这样做的人吗?
以下是我从阅读文档,其他类似解决方案以及反复试验中得出的结果.它是随机数据的简单自动编码器.如果跑,然后再跑,它将从它停止的地方继续(即首次运行的成本函数从~0.5 - > 0.3秒运行开始~0.3).除非我遗漏了一些东西,所有的存储,构造函数,模型构建,add_to_collection都需要并且按照精确的顺序,但可能有一种更简单的方法.
是的,加载图形import_meta_graph
并不是真的需要在这里,因为代码就在上面,但是在我的实际应用程序中是我想要的.
from __future__ import print_function
import tensorflow as tf
import os
import math
import numpy as np
output_dir = "/root/Data/temp"
model_checkpoint_file_base = os.path.join(output_dir, "model.ckpt")
input_length = 10
encoded_length = 3
learning_rate = 0.001
n_epochs = 10
n_batches = 10
if not os.path.exists(model_checkpoint_file_base + ".meta"):
print("Making new")
brand_new = True
x_in = tf.placeholder(tf.float32, [None, input_length], name="x_in")
W_enc = tf.Variable(tf.random_uniform([input_length, encoded_length],
-1.0 / math.sqrt(input_length),
1.0 / math.sqrt(input_length)), name="W_enc")
b_enc = tf.Variable(tf.zeros(encoded_length), name="b_enc")
encoded = tf.nn.tanh(tf.matmul(x_in, W_enc) + b_enc, name="encoded")
W_dec = tf.transpose(W_enc, name="W_dec")
b_dec = tf.Variable(tf.zeros(input_length), name="b_dec")
decoded = tf.nn.tanh(tf.matmul(encoded, W_dec) + b_dec, name="decoded")
cost = tf.sqrt(tf.reduce_mean(tf.square(decoded - x_in)), name="cost")
saver = tf.train.Saver()
else:
print("Reloading existing")
brand_new = False
saver = tf.train.import_meta_graph(model_checkpoint_file_base + ".meta")
g = tf.get_default_graph()
x_in = g.get_tensor_by_name("x_in:0")
cost = g.get_tensor_by_name("cost:0")
sess = tf.Session()
if brand_new:
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()
sess.run(init)
tf.add_to_collection("optimizer", optimizer)
else:
saver.restore(sess, model_checkpoint_file_base)
optimizer = tf.get_collection("optimizer")[0]
for epoch_i in range(n_epochs):
for batch in range(n_batches):
batch = np.random.rand(50, input_length)
_, curr_cost = sess.run([optimizer, cost], feed_dict={x_in: batch})
print("batch_cost:", curr_cost)
save_path = tf.train.Saver().save(sess, model_checkpoint_file_base)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9743 次 |
最近记录: |