当我尝试使用 TensorFlow 1.x 以最大似然拟合 softmax 概率时,我遇到了错误消息:
“TypeError:应为 int32,但没有得到类型为‘_Message’的错误。”
错误来自函数 p(x) 中的 x.get_shape().as_list()[0]。我在将 x = tf.placeholder(tf.int32, [None]) 更改为 x = tf.placeholder(tf.int32, [BATCH_SIZE]) 后修复了错误,其中 BATCH_SIZE 是一个固定的数字。
如果我想坚持使用 x = tf.placeholder(tf.int32, [None]) 如何解决这个错误?
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)
...
请您参考如下方法:
使用 tf.shape() 获取张量的动态形状。 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)
