'Exception encountered when calling layer "dense_6" (type Dense). Dimensions must be equal

I don't understand this error, i want to make the tranfer learning. it is the classification party, and i would like to have not linear classification party, and on my other programs there is not this error.In the frist time, the program seemed to work. could you help me?

that is my script:

global_average_layer = tf.keras.layers.GlobalAveragePooling2D()

feature_batch_average = global_average_layer(feature_batch)

print(feature_batch_average.shape)

prediction_layer = tf.keras.layers.Dense(3, activation = 'relu')

prediction_layer2 = tf.keras.layers.Dense(256, activation='relu')

prediction_layer3 = tf.keras.layers.Dense(128, activation='relu')

prediction_batch = prediction_layer(feature_batch_average)

print(prediction_batch.shape)

inputs = tf.keras.Input(shape=(160, 160, 3))

x = data_augmentation(inputs)

x = preprocess_input(x)

x = base_model(x, training=False)

x = global_average_layer(x)

x = tf.keras.layers.Dropout(0.4)(x)

x = prediction_layer2(x)

x = prediction_layer3(x)

outputs = prediction_layer (x)

model = tf.keras.Model(inputs, outputs)

that is error :

ValueError                                Traceback (most recent call last)

<ipython-input-36-2e1e1a4cbc58> in <module>()
      7 x = prediction_layer2(x)
      8 x = prediction_layer3(x)
----> 9 outputs = prediction_layer (x)
     10 model = tf.keras.Model(inputs, outputs)

1 frames

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs, op_def)
   2011   except errors.InvalidArgumentError as e:
   2012     # Convert to ValueError for backwards compatibility.
-> 2013     raise ValueError(e.message)
   2014 
   2015   return c_op

ValueError: Exception encountered when calling layer "dense_6" (type Dense).

Dimensions must be equal, but are 128 and 1280 for '{{node dense_6/MatMul}} = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false](Placeholder, dense_6/MatMul/ReadVariableOp)' with input shapes: [?,128], [1280,3].

Call arguments received:
  • inputs=tf.Tensor(shape=(None, 128), dtype=float32)


Solution 1:[1]

Dimension mismatch is due to the additional layers after the Dropout layer. Removing those layers will help. I could replicate the issue with the Alzeihmer's dataset. Please find the code below.

inputs = tf.keras.Input(shape=(160, 160, 3))
x = data_augmentation(inputs)
x = preprocess_input(inputs)
x = base_model(x, training=False)
x = global_average_layer(x)
x = tf.keras.layers.Dropout(0.4)(x)
outputs = prediction_layer (x)
model = tf.keras.Model(inputs, outputs)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tfer3