9951 explained code solutions for 126 technologies


python-kerasHow can I use Python and Keras to build a convolutional neural network?


To build a convolutional neural network (CNN) with Python and Keras, you need to follow a few steps:

  1. Import the necessary libraries:
import keras
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
  1. Create the model:
model = keras.models.Sequential()
  1. Add convolutional layers:
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
  1. Add flattening layer:
model.add(Flatten())
  1. Add a fully connected layer:
model.add(Dense(128, activation='relu'))
  1. Add output layer:
model.add(Dense(1, activation='sigmoid'))
  1. Compile the model:
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

For further information, please refer to the following links:

Edit this code on GitHub