Arthos
Arthos

Reputation: 453

Converting tflearn model to keras

I am trying to convert my old tflearn model into a keras model, as I have migrated from TF 1.15 to TF 2.0, where tflearn isn't supported anymore. My keras model is:

model = tf.keras.Sequential([
    tf.keras.layers.Dense(8, input_shape=(None, len(train_x[0]))),
    tf.keras.layers.Dense(8),
    tf.keras.layers.Dense(len(train_y[0]), activation="softmax"),
])

model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(train_x, train_y, epochs=epochs, batch_size=batch_size)

test_loss, test_acc = model.evaluate(train_x, train_y)
print("Tested Acc:", test_acc)

When I run it, I get the following error:

ValueError: Error when checking input: expected dense_input to have 3 dimensions, but got array with shape (49, 51)

I have no clue how to fix this error. Do I need to redimensionate the model somehow? What am I doing wrong?

For reference, my old tflearn model was:

tf.reset_default_graph()

net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')
net = tflearn.regression(net)

model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
model.fit(train_x, train_y, n_epoch=epochs, batch_size=batch_size, show_metric=True)

Upvotes: 1

Views: 1355

Answers (1)

IonicSolutions
IonicSolutions

Reputation: 2599

As we uncovered in the comments, there are two issues with your code.

First, you must not give the batch dimension in the input_shape parameter, cf. the Keras documentation for Dense.

Second, since train_y.shape = (?, 6), you need to use categorical_crossentropy and not sparse_categorical_crossentropy. There is a note in the Keras documentation which describes the difference in detail.

Here is the corrected code:

model = tf.keras.Sequential([
    tf.keras.layers.Dense(8, input_shape=(len(train_x[0]))),
    tf.keras.layers.Dense(8),
    tf.keras.layers.Dense(len(train_y[0]), activation="softmax"),
])

model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
model.fit(train_x, train_y, epochs=epochs, batch_size=batch_size)

Upvotes: 3

Related Questions