【问题标题】:Select different modes by string in Tensorflow在Tensorflow中按字符串选择不同的模式
【发布时间】:2019-05-17 13:32:27
【问题描述】:

我正在尝试构建一个 VAE 网络,我希望模型在其中以不同的模式做不同的事情。我有三种模式:“训练”、“相同”和“不同”以及一个名为 interpolation(mode) 的函数,它根据模式执行不同的操作。我的代码如下:

import tensorflow as tf

### some code here

mode = tf.placeholder(dtype = tf.string, name = "mode")

def interpolation(mode):
  if mode == "train":
    # do something
    print("enter train mode")
  elif mode == "same":
    # do other things
    print("enter same mode")
  else:
    # do other things
    print("enter different mode")

# some other code here

sess.run(feed_dict = {mode: "train"})
sess.run(feed_dict = {mode: "same"})
sess.run(feed_dict = {mode: "different"})

但输出看起来像:

enter different mode
enter different mode
enter different mode

这意味着传入的模式不会改变条件。我做错了什么?如何通过字符串参数选择模式?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    第一种方法:您可以使用原生 Tensorflow switch-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"}))
    

    第二种方法:这是使用新AutoGraph API 的另一种方法:

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

    【讨论】:

    • @StevenChan 我将第一种方法更改为两个以上的条件。将“m”更改为“mode”会导致局部变量和全局变量之间发生冲突。为此,我应该更改变量名。
    • 似乎在初始化框架时,tf.case 函数访问了所有四个条件,这实际上导致了一些维度冲突,因为在我初始化它们时,存在维度定义为 None 的张量。有没有办法初始化模式,使 tf.case 只访问默认模式?
    • 试用 tf.placeholder_with_default
    猜你喜欢
    • 1970-01-01
    • 2015-02-21
    • 2014-03-12
    • 1970-01-01
    • 2021-10-03
    • 2021-04-01
    • 2010-10-18
    • 1970-01-01
    • 2022-07-12
    相关资源
    最近更新 更多