按十位数的字符串选择不同的模式

2024-04-23 17:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试建立一个VAE网络,我希望模型以不同的模式做不同的事情。我有三种模式:“train”,“same”和“different”,还有一个名为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

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


Tags: runmodetffeed模式train事情do
1条回答
网友
1楼 · 发布于 2024-04-23 17:28:31

第一种方法:您可以使用本机Tensorflowswitch-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'}))

相关问题 更多 >