Home > database >  How to create a Keras model with output Dense layer that have shape 2D?
How to create a Keras model with output Dense layer that have shape 2D?

Time:06-22

The output of my model is (None, 2) and I need it to be (None, 2, 14). With the following model, what should I change to get the desired output shape?

model = Sequential()
model.add(Dense(32, activation='relu', input_shape=(211,)))
model.add(Dropout(0.25))
model.add(Dense(32, activation='relu'))
model.add(Dense(2,activation='softmax'))

CodePudding user response:

How about instead two neurons in the last layer use 28 neurons then use tf.keras.layer.Reshape() to reshape (28,) to (2, 14) and get what you want:

import tensorflow as tf
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(32, activation='relu', input_shape=(211,)))
model.add(tf.keras.layers.Dropout(0.25))
model.add(tf.keras.layers.Dense(32, activation='relu'))
model.add(tf.keras.layers.Dense(28,activation='softmax'))
model.add(tf.keras.layers.Reshape((2,14)))
model.summary()

Output:

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense (Dense)               (None, 32)                6784      
                                                                 
 dropout (Dropout)           (None, 32)                0         
                                                                 
 dense_1 (Dense)             (None, 32)                1056      
                                                                 
 dense_2 (Dense)             (None, 28)                924       
                                                                 
 reshape (Reshape)           (None, 2, 14)             0         
                                                                 
=================================================================
Total params: 8,764
Trainable params: 8,764
Non-trainable params: 0
_________________________________________________________________
  • Related