仅仅出现在tf2.1中,在tf2.4中已经不存在该问题。
这个问题查询了很多教程都没有很好的解决,其中有一个比较有启发的解决方案是这样的。
https://blog.csdn.net/dldldl0/article/details/79089074
ValueError: The last dimension of the inputs to
Dense
should be defined. FoundNone
. 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
即可