我有一个带有两个损失函数的TensorFlow图。我想另外训练我的模型:
我是否必须创建两个图然后加载,训练和保存每一步的权重?还是可以通过一个图形来实现?
答案 0 :(得分:3)
是的,这是可能的:
import tensorflow as tf
x = tf.get_variable('x', initializer=42.)
y = tf.square(x)
optimizer = tf.train.GradientDescentOptimizer(0.1)
train_min = optimizer.minimize(y) # minimize x*x
train_max = optimizer.minimize(-y) # maximize x*x
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(20):
cost, _ = sess.run([y, train_min])
print(cost)
cost, _ = sess.run([y, train_max])
print(cost)
如果您不介意在同一批次上精确地最小化两个成本函数,甚至可以编写
import tensorflow as tf
x = tf.get_variable('x', initializer=42.)
y = tf.square(x)
optimizer = tf.train.GradientDescentOptimizer(0.1)
train_min = optimizer.minimize(y)
with tf.control_dependencies([train_min]):
train_min_then_max = optimizer.minimize(-y)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(20):
cost, _ = sess.run([y, train_min_then_max])
print(cost)
通过一个sess.run调用进行优化。