gpt4 book ai didi

tensorflow - 值错误: Shape must be rank 0 but is rank 1 for 'cond_11/Switch' (op: 'Switch' )

转载 作者:行者123 更新时间:2023-12-03 00:37:06 24 4
gpt4 key购买 nike

实际上我们不能在 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 raise ValueError(err.message)

ValueError: Shape must be rank 0 but is rank 1 for 'cond_11/Switch' (op: 'Switch') with input shapes: [1], [1].

最佳答案

错误指出预期输入是标量(等级 0),但形状为 ([1],[1])。通常,您可以通过将输入 reshape 为标量值(使用 tf.reshape(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

关于tensorflow - 值错误: Shape must be rank 0 but is rank 1 for 'cond_11/Switch' (op: 'Switch' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47739707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com