我需要创建一个变量epsilon_n
,它根据当前step
更改定义(和值)。由于我有两个以上的案例,似乎我不能使用tf.cond
。我正在尝试使用tf.case
,如下所示:
import tensorflow as tf
####
EPSILON_DELTA_PHASE1 = 33e-4
EPSILON_DELTA_PHASE2 = 2.5
####
step = tf.placeholder(dtype=tf.float32, shape=None)
def fn1(step):
return tf.constant([1.])
def fn2(step):
return tf.constant([1.+step*EPSILON_DELTA_PHASE1])
def fn3(step):
return tf.constant([1.+step*EPSILON_DELTA_PHASE2])
epsilon_n = tf.case(
pred_fn_pairs=[
(tf.less(step, 3e4), lambda step: fn1(step)),
(tf.less(step, 6e4), lambda step: fn2(step)),
(tf.less(step, 1e5), lambda step: fn3(step))],
default=lambda: tf.constant([1e5]),
exclusive=False)
但是,我不断收到此错误消息:
TypeError: <lambda>() missing 1 required positional argument: 'step'
我尝试了以下内容:
epsilon_n = tf.case(
pred_fn_pairs=[
(tf.less(step, 3e4), fn1),
(tf.less(step, 6e4), fn2),
(tf.less(step, 1e5), fn3)],
default=lambda: tf.constant([1e5]),
exclusive=False)
我仍然会犯同样的错误。 Tensorflow文档中的示例权衡了没有输入参数传递给可调用函数的情况。我在网上找不到关于tf.case的足够信息!请帮忙吗?
答案 0 :(得分:4)
您需要进行一些更改。 为了保持一致性,您可以将所有返回值设置为变量。
# Since step is a scalar, scalar shape [() or [], not None] much be provided
step = tf.placeholder(dtype=tf.float32, shape=())
def fn1(step):
return tf.constant([1.])
# Here you need to use Variable not constant, since you are modifying the value using placeholder
def fn2(step):
return tf.Variable([1.+step*EPSILON_DELTA_PHASE1])
def fn3(step):
return tf.Variable([1.+step*EPSILON_DELTA_PHASE2])
epsilon_n = tf.case(
pred_fn_pairs=[
(tf.less(step, 3e4), lambda : fn1(step)),
(tf.less(step, 6e4), lambda : fn2(step)),
(tf.less(step, 1e5), lambda : fn3(step))],
default=lambda: tf.constant([1e5]),
exclusive=False)