实际上我们不能在if语句中使用tf.var作为bool而不是使用tf.cond。我编写了这个代码用于规范化输入数据并得到混淆错误,我做错了吗?
def global_contrast_normalize(X, scale=1., subtract_mean=True,use_std=False,
sqrt_bias=0., min_divisor=1e-8):
mean=tf.reduce_mean(X,axis=1)
if subtract_mean:
X = X - mean[:, numpy.newaxis] # Makes a copy.
else:
X = tf.copy.copy(X)
if X.get_shape()[1]==1:
#ddof = 0
mean, var = tf.nn.moments(X, axes=[1])
normalizers = tf.sqrt(sqrt_bias + var) / scale
else:
normalizers = tf.sqrt(sqrt_bias + tf.reduce_sum((X ** 2),axis=1)) / scale
Normalizers= tf.Variable(normalizers,'float32')
M=tf.Variable(min_divisor,'float32')
tf.cond( tf.less_equal(Normalizers,M),lambda:tf.assign(Normalizers, [1]),lambda:tf.assign(Normalizers,normalizers))
X /= Normalizers[:, tf.newaxis] # Does not make a copy.
return X
错误:
in _call_cpp_shape_fn_impl 提出ValueError(err.message)
ValueError:Shape必须为0级,但对于'cond_11 / Switch'为1级 (op:'Switch')具有输入形状:[1],[1]。
答案 0 :(得分:4)
错误表明预期输入是标量(等级0),但形状为([1],[1])。通常你可以通过将输入重新整形为标量值来解决这个问题(使用tf.reshape(Normalizers, [])
)。
对于这种情况,看起来您希望有条件地设置Normalizers的值,具体取决于它们是否为< = M. tf.where
完全相同。
(注意,您不必将规范化器或min_divisor转换为tf.Variable)
tf.where的使用示例:
def global_contrast_normalize(...):
...
comparison = tf.less_equal(normalizers,M)
normalizers = tf.where(comparison, tf.ones_like(normalizers), normalizers
X /= normalizers[:, tf.newaxis]
return X