0

The following code

from tensorflow import keras
from keras.layers import Conv2D

model = keras.Sequential()
model.add(Conv2D(1, (3, 3), padding='same', input_shape=(28, 28, 1)))

when executed throws an error:

TypeError: The added layer must be an instance of class Layer. Found: <keras.layers.convolutional.Conv2D object at 0x7fea0c002d10>

I also tried using the Convolutional2D but got the same error. Why?

mercury0114
  • 1,341
  • 2
  • 15
  • 29

2 Answers2

4

Try this:

from tensorflow import keras
from tensorflow.keras.layers import Conv2D

model = keras.Sequential()
model.add(Conv2D(1, (3, 3), padding='same', input_shape=(28, 28, 1)))

You are mixing a tf.keras Sequential model with a keras Conv2D layer (instead of a tf.keras Conv2D layer.)

Or, as remarked below, use actual Keras:

import keras
from keras.models import Sequential
from keras.layers import Conv2D

model = Sequential()
model.add(Conv2D(1, (3, 3), padding='same', input_shape=(28, 28, 1)))
sdcbr
  • 7,021
  • 3
  • 27
  • 44
  • 1
    It would be probably better not use keras from tensorflow since actual keras is installed. Just `import keras` instead of `from tensorflow`. – Daniel Möller Dec 17 '18 at 20:07
  • I read that "Keras is a model-level library, and does not handle low-level operations, which is the job of tensor manipulation libraries,or backends". So if we use actual Keras as you said, then who does these low-level operations. If keras itself can do that then whats the extra addition/usage of Tensorflow. Thanks. – Neo Apr 04 '19 at 21:39
  • Keras will use a backend, which will be TensorFlow for most people, but can be another library as well. It's just a matter of being consistent in the API implementation that you use: either you use the Keras implementation (and choose your backend, which can be TF), or you use the tf.keras implementation to build your model. You cannot mix both within one script. – sdcbr Apr 09 '19 at 07:23
1

You should import Sequential from keras models

from keras.models import Sequential
from keras.layers import Conv2D

model = Sequential()
model.add(Conv2D(1, (3, 3), padding='same', input_shape=(28, 28, 1)))
Amin Golnari
  • 151
  • 1
  • 7