N
N
nasdi2020-12-30 02:45:30
Python
nasdi, 2020-12-30 02:45:30

Why does functional api code work but Sequential doesn't?

After reading 1 article, I decided to write a simple autoencoder. The example written using the functional api works, and mine, using the Sequential api, swears at the input dimension. So the next question. How to rewrite the code in Sequential api so that it works and what was the error
. Working code:

input_dim = X_train.shape[1]
encoding_dim = 14
input_layer = Input(shape=(input_dim, ))
encoder = Dense(encoding_dim, activation="tanh", 
                activity_regularizer=regularizers.l1(10e-5))(input_layer)
encoder = Dense(int(encoding_dim / 2), activation="relu")(encoder)
decoder = Dense(int(encoding_dim / 2), activation='tanh')(encoder)
decoder = Dense(input_dim, activation='relu')(decoder)
autoencoder = Model(inputs=input_layer, outputs=decoder)
nb_epoch = 100
batch_size = 32
autoencoder.compile(optimizer='adam', 
                    loss='mean_squared_error', 
                    metrics=['accuracy'])

history = autoencoder.fit(X_train, X_train,
                    epochs=nb_epoch,
                    batch_size=batch_size,
                    shuffle=True,
                    validation_data=(X_test, X_test),
                    verbose=1)

Not working:
keras_model = Sequential()
keras_model.add(Dense(14, activity_regularizer=regularizers.l1(10e-5), input_shape=(1,)))
keras_model.add(Activation('tanh'))
keras_model.add(Dense(7))
keras_model.add(Activation('relu'))
keras_model.add(Dense(7))
keras_model.add(Activation('tanh'))
keras_model.add(Dense(14))
keras_model.add(Activation('relu'))
keras_model.compile(optimizer='adam', loss = 'mean_squared_error', metrics=['accuracy'])
keras_model.fit(x_train, x_train,
                    epochs=nb_epoch,
                    batch_size=batch_size,
                    shuffle=True,
                    validation_data=(x_test, x_test),
                    verbose=1)

Mistake:
Error when checking target: expected activation_140 to have shape (14,) but got array with shape (1,)

x_train.shape - (2800, 1)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Danil, 2020-12-30
@DanilBaibak

Try like this:

input_dim = X_train.shape[1]
keras_model.add(Dense(14, activity_regularizer=regularizers.l1(10e-5), input_shape=(input_dim,)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question