tensorflow踩坑记录

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的用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值