Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用两个tensorflow模型,其中一个用于推理,另一个用于训练_Tensorflow - Fatal编程技术网

使用两个tensorflow模型,其中一个用于推理,另一个用于训练

使用两个tensorflow模型,其中一个用于推理,另一个用于训练,tensorflow,Tensorflow,我是tensorflow的新手,我尝试将两个模型合并到一个图中,因为我需要一个模型的推理结果来修改另一个模型的损失函数。我写了代码,它运行时没有错误,但我不确定我写的是否正确,所以我正在写这个线程 在代码中,我加载了两个这样的图 with tf.variable_scope("modelA"): new_saver = tf.train.import_meta_graph('modelA-1000.meta') new_saver.restore(sess, tf.train.lates

我是tensorflow的新手,我尝试将两个模型合并到一个图中,因为我需要一个模型的推理结果来修改另一个模型的损失函数。我写了代码,它运行时没有错误,但我不确定我写的是否正确,所以我正在写这个线程

在代码中,我加载了两个这样的图

with tf.variable_scope("modelA"):
  new_saver = tf.train.import_meta_graph('modelA-1000.meta')
  new_saver.restore(sess, tf.train.latest_checkpoint('./'))

with tf.variable_scope("modelB"):
  new_saver = tf.train.import_meta_graph('modelB-1000.meta')
  new_saver.restore(sess, tf.train.latest_checkpoint('./'))
我使用modelA的结果修改modelB的损失函数,如下所示

output_A = tf.get_default_graph().get_tensor_by_name("modelA_output:0")
output_B = tf.get_default_graph().get_tensor_by_name("modelB_output:0")
loss = tf.reduce_mean(-tf.reduce_sum(output_A * tf.log(output_B ), reduction_indices=[1])) 
然后对于训练,我只包括了要训练的modelB变量,因为我只想让ModelA用于推理

model_vars = tf.trainable_variables()
var_B = [var for var in model_vars if 'modelB' in var.name]
gradient = tf.gradients(loss,var_B)
trainer = tf.train.GradientDescentOptimizer(0.1)
train_step = trainer.apply_gradients(zip(gradient ,var_B))

... declare session and prepare batch for training ...

for i in range(10000):
    loss_ = train_step.run(loss, feed_dict={x: batch[0]})

我运行了它,代码也运行了,但是损失并没有减少。我做错了什么?谢谢你的阅读

我不确定这段代码是如何运行的<代码>训练步骤是一种
操作
Operation.run()
方法接受
feed\u dict
和可选的
会话。我不知道
train\u step.run(loss,feed\u dict={x:batch[0]})
如何运行。一般来说,您会这样做:

with tf.Session() as sess:
   _, _loss = sess.run([train_step, loss], feed_dict=...)
作为旁注,如果您有最初生成modelA和modelB的代码。最好(即不那么脆弱)重新运行该代码以重新创建图形。创建图形后,可以使用
Saver
从检查点恢复变量值。这样可以避免像这样进行脆性提取

output_A = tf.get_default_graph().get_tensor_by_name("modelA_output:0")