第一种方法:您可以使用原生 Tensorflow 选择不同的模式开关盒 https://www.tensorflow.org/api_docs/python/tf/case。例如,我假设你有三种情况,那么你可以这样做:
import tensorflow as tf
mode = tf.placeholder(tf.string, shape=[], name="mode")
def cond1():
return tf.constant('same')
def cond2():
return tf.constant('train')
def cond3():
return tf.constant('diff')
def cond4():
return tf.constant('default')
y = tf.case({tf.equal(mode, 'same'): cond1,
tf.equal(mode, 'train'): cond2,
tf.equal(mode, 'diff'): cond3},
default=cond4, exclusive=True)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(y, feed_dict={mode: "train"}))
print(sess.run(y, feed_dict={mode: "same"}))
第二种方法:这是用 new 来做到这一点的另一种方法自动图谱API https://www.tensorflow.org/guide/autograph:
import tensorflow as tf
from tensorflow.contrib import autograph as ag
m = tf.placeholder(dtype=tf.string, name='mode')
def interpolation(mode):
if mode == "train":
return 'I am train'
elif mode == "same":
return 'I am same'
else:
return 'I am different'
cond_func = ag.to_graph(interpolation)(m)
with tf.Session() as sess:
print(sess.run(cond_func, feed_dict={m: 'same'}))