The last dimension of the inputs to `Dense` should be defined. Found `None`.

仅仅出现在tf2.1中,在tf2.4中已经不存在该问题。

这个问题查询了很多教程都没有很好的解决,其中有一个比较有启发的解决方案是这样的。

https://blog.csdn.net/dldldl0/article/details/79089074

ValueError: The last dimension of the inputs to Dense should be defined. Found None. ppp2.shape: (10, ?)

这种情况是由于 tf.reshape ()时,设定大小时存在张量,而不是确切的常数: 如:tf.reshape (x,[-1,y.shape[0]]) ,有时因 y.shape[0],导致识别不了,这种情况,只需中途找个变量(转化为 int )过渡一下(v =int(y.shape[0])),然后再 tf.reshape (x,[-1,v]) 就可以了

再来看看笔者代码:

   def build_model():
       input_a = Input(shape=(28, 28,), name='input_1')
       input_b = Input(shape=(28, 28,), name="input_2")
       ra = Reshape((-1,), name="reshape")(input_a)
       rb = Reshape((-1,),name="reshape_1")(input_b)

       d1 = Dense(500,activation='relu', name="dense")
       d2 = Dense(10, activation="softmax", name="dense_1")

       hidden_a = d2(d1(ra))
       hidden_b = d2(d1(rb))

       distance = K.sqrt(K.sum(tf.square(hidden_a - hidden_b)+0.00001, axis=1))

       model = tf.keras.Model(inputs=[input_a, input_b], outputs=distance)

       return model

上面这段代码在tf24中可以正常运行,并且通过,但是在tf2.1中无法通过,会报错: The last dimension of the inputs to Dense should be defined. Found None.

而问题的关键就在于-1,这个需要运行时决定,所以为了解决这个报错,我们人工计算这个值。

def build_model():
    input_a = Input(shape=(28, 28,), name='input_1')
    input_b = Input(shape=(28, 28,), name="input_2")
    ra = Reshape((784,), name="reshape")(input_a)
    rb = Reshape((784,),name="reshape_1")(input_b)

    d1 = Dense(500,activation='relu', name="dense")
    d2 = Dense(10, activation="softmax", name="dense_1")

    hidden_a = d2(d1(ra))
    hidden_b = d2(d1(rb))

    # 注意,为防止梯度爆炸,对distance添加保护措施
    distance = K.sqrt(K.sum(tf.square(hidden_a - hidden_b)+0.00001, axis=1))

    model = tf.keras.Model(inputs=[input_a, input_b], outputs=distance)

    return model

即可

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

*pprp*

如果有帮助可以打赏一杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值