Search code examples
pythontensorflowkeraskeras-layertensorflow-estimator

Cannot convert keras model to tensorflow: type object 'Dense' has no attribute 'from_config'


I am struggling with converting my Keras model into a TensorFlow estimator. I got the following error:

AttributeError: type object 'Dense' has no attribute 'from_config'

And here is my code:

from tensorflow import keras
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense

classifier = keras.models.Sequential()
classifier.add(tf.layers.Dense(units = 6, kernel_initializer = keras.initializers.he_uniform(), activation = tf.nn.relu, input_shape =(11,)))
classifier.add(tf.layers.Dense(units = 6, kernel_initializer = keras.initializers.he_uniform(), activation = tf.nn.relu))
classifier.add(tf.layers.Dense(units = 1, kernel_initializer = tf.keras.initializers.he_uniform(), activation = tf.nn.softmax))

classifier.compile(optimizer=tf.keras.optimizers.Adam(lr=0.0001),
                      loss=tf.keras.losses.binary_crossentropy,
                      metric=tf.keras.metrics.categorical_accuracy)


my_estimator = tf.keras.estimator.model_to_estimator(keras_model=classifier)

The error comes from the last line of code I guess this is because keras Dense has not the good attribute, but how can I find the equivalent that will have from_config?

Keras==2.1.6
tensorflow==1.7.0

Solution

  • Looks like you're using the Dense layer from the wrong package: it should be tf.keras.layers.Dense rather than tf.layers.Dense.

    Note that though they have the same class name and lots of similar parameters, in fact they have nothing in common: tf.layers.Dense is a high-level tensorflow API, not related to keras. That's why you can't add them to classifier.