Home > Mobile >  Importing Keras for a CNN
Importing Keras for a CNN

Time:04-07

I am getting a TypeErrir due to the added layer, BatchNormalization, not being the same as the class layer. I'm unsure why, I've tried to correctly import the layers, and have tried multiple different ways.

My imports are currently:

import copy
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from tqdm import tqdm

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import BatchNormalization,Dense, Conv2D, Flatten, Reshape
from tensorflow.keras.layers import Activation
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Input

I use the imports in the following section of code:

    model = Sequential()
    model.add(Input(shape=(9, 9, 1)))
    model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))
    model.add(BatchNormalization)
    model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))
    model.add(BatchNormalization)
    model.add(Conv2D(128, kernel_size=(1, 1), activation='relu', padding='same'))

    model.add(Flatten())
    model.add(Dense(81 * 9))
    model.add(Reshape((-1, 9)))
    model.add(Activation('softmax'))

    adam = Adam(lr=.001)
    model.compile(loss='sparse_categorical_crossentropy', optimizer=adam)
    model.fit(x_train, y_train, batch_size=32, epochs=2)

The error I am getting is:

  File "**/train.py", line 24, in <module>
    x_train, x_test, y_train, y_test = get_data('sudoku.csv')
  File "**/data_preprocess.py", line 124, in get_data
    model.add(BatchNormalization)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/training/tracking/base.py", line 457, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tensorflow/python/keras/engine/sequential.py", line 180, in add
    raise TypeError('The added layer must be '
TypeError: The added layer must be an instance of class Layer. Found: <class 'tensorflow.python.keras.layers.normalization_v2.BatchNormalization'>

I also tried the following but am getting the same error. enter image description here

Could the error be related to something else in the project? apart from the imports

CodePudding user response:

You are almost there. Batchnorm is a class so you need to instantiate it by adding ()

model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))
model.add(BatchNormalization())
  • Related