在使用Tensorflow 1.x时,如何避免静态形状导致的类型错误,同时仍然坚持使用“[None]”形状?

2024-04-26 10:35:14 发布

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

当我试图使用TensorFlow 1.x将softmax概率与最大似然进行拟合时,我遇到了错误消息:

"TypeError: Expected int32, got None of type '_Message' instead."

错误来自函数p(x)中的x.get_shape().as_list()[0]。我修复了将x = tf.placeholder(tf.int32, [None])更改为x = tf.placeholder(tf.int32, [BATCH_SIZE])后的错误,其中BATCH_SIZE是一个固定数字

如果我想坚持使用^{,我该如何解决这个错误

tf.reset_default_graph()
with tf.variable_scope('param'):
    theta = tf.Variable(tf.zeros(100), dtype=tf.float32, name='theta')


with tf.variable_scope('loss'):
    def p(x):
        softmax = tf.ones([x.get_shape().as_list()[0], 1]) * tf.math.softmax(theta)
        idx_x = tf.stack([tf.range(x.get_shape().as_list()[0], dtype=tf.int64), x-1], axis=1)
        return tf.gather_nd(softmax,idx_x)

    def softmaxLoss(x):
        return tf.reduce_mean(-tf.math.log(p(x)))

var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'param')
x = tf.placeholder(tf.int32, [None])
prob_op = p(x)
log_loss = softmaxLoss(x)
...


Tags: nonesizegettfas错误withbatch
1条回答
网友
1楼 · 发布于 2024-04-26 10:35:14

使用tf.shape()获得张量的动态形状^{}以张量对象的形式返回形状。在您的情况下,请这样使用:

tf.shape(x)[0]

所以你的代码应该是:

def p(x):
    softmax = tf.ones([tf.shape(x)[0], 1]) * tf.math.softmax(theta)
    idx_x = tf.stack([tf.range(tf.shape(x)[0], dtype=tf.int64), x-1], axis=1)
    return tf.gather_nd(softmax,idx_x)

相关问题 更多 >