Search code examples
tensorflowkerasneural-networkconv-neural-networkmlp

Replacing MLP code with CNN in python using tensorflow and keras


I tried the code below with MLP now I need to replace this MLP code with CNN 8 layers with the following structure: 3×3×32 Convolutional → 3×3×64 Convolutional → 2×2 MaxPool → Dropout → Flatten → 1 × 128 Full connected → Dropout → 128 × 10 Fully connected → Softmax.

//declear path to your mnist data folder
img_path = 'c:/kaggleMNISTdata/trainingSet/trainingSet'
 //get the path list using the path object
image_paths = list(paths.list_images(img_path))
//apply our function
image_list, label_list = load(image_paths, verbose=10000)
// binarize the labels
lb = LabelBinarizer()
label_list = lb.fit_transform(label_list)
// split data into training and test set
X_train, X_test, y_train, y_test = train_test_split(image_list,
                                                    label_list,
                                                    test_size=0.1,
                                                    random_state=42)
data = list(zip(image_list, label_list))
random.shuffle(data)
class SimpleMLP:
    @staticmethod
    def build(shape, classes):
        model = Sequential()
        model.add(Dense(200, input_shape=(shape,)))
        model.add(Activation("relu"))
        model.add(Dense(200))
        model.add(Activation("relu"))
        model.add(Dense(classes))
        model.add(Activation("softmax"))
        return model

I tried following

def build(shape, classes):
        model = Sequential()
        model.add(Conv2D(200, input_shape=(shape,)))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Flatten(1))
        model.add(Dropout(1))
        model.add(Dense(200))
        model.add(Activation("softmax"))
        return model

is it correct?


Solution

  • Try this with your given architecture:

    cnn_model = Sequential()
    cnn_model.add(Conv2D(32, (3, 3), input_shape=(28, 28, 1)))
    cnn_model.add(Conv2D(64, (3, 3)))
    cnn_model.add(MaxPooling2D((2, 2)))
    cnn_model.add(Dropout(0.5))
    cnn_model.add(Flatten())
    cnn_model.add(Dense(128))
    cnn_model.add(Dropout(0.5))
    cnn_model.add(Dense(classes))
    cnn_model.add(Activation("softmax"))