tensorflow踩坑记录
程序员文章站
2024-02-10 08:54:04
...
Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'
tf.reset_default_graph
with cnn_graph.as_default():
with tf.name_scope("placeholders"):
inputs = tf.placeholder(dtype=tf.int32, shape=(None, max_len), name="inputs")
targets = tf.placeholder(dtype=tf.float32, shape=(None, 1), name="targets")
# embeddings
with tf.name_scope("embeddings"):
# 用pre-trained词向量来作为embedding层
embedding_matrix = tf.Variable([vocab_size,embedding_size], trainable=True, name="embedding_matrix")
embed = tf.nn.embedding_lookup(embedding_matrix, inputs, name="embed")
# 相加词向量得到句子向量
sum_embed = tf.reduce_sum(embed, axis=1, name="sum_embed")
# model
with tf.name_scope("model"):
# 隐层权重
W1 = tf.Variable(tf.random_normal(shape=(embedding_size, hidden_size), stddev=0.1), name="W1")
b1 = tf.Variable(tf.zeros(shape=(hidden_size), name="b1"))
# 输出层权重
W2 = tf.Variable(tf.random_normal(shape=(hidden_size, 1), stddev=0.1), name="W2")
b2 = tf.Variable(tf.zeros(shape=(1), name="b2"))
# 结果
z1 = tf.add(tf.matmul(sum_embed, W1), b1)
a1 = tf.nn.relu(z1)
logits = tf.add(tf.matmul(a1, W2), b2)
outputs = tf.nn.sigmoid(logits, name="outputs")
计算z1 tf.matmul时报错,int32和float32不匹配报错。
一开始以为是变量类型不匹配导致的,把sum_embed.shape print出来以后发现和预期的输出不一样,仔细检查后发现是
embedding_matrix定义时出错了,改为:
embedding_matrix = tf.Variable(tf.random_normal(shape=(vocab_size, embedding_size), stddev=0.1), trainable=True, name="embedding_matrix")
就好了,和tf.get_variable混淆了,后续有时间会补上tf.variable_scope,tf.name_scope,tf.get_variable的用法
上一篇: PHP认证码兑现