import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
train_generator = train_datagen.flow_from_directory(
'your training_dataset path',
target_size=(128, 128),
batch_size=32,
class_mode='binary'
)
test_datagen = ImageDataGenerator(rescale=1./255)
validation_generator = test_datagen.flow_from_directory(
'your test_dataset path',
target_size=(128, 128),
batch_size=32,
class_mode='binary'
)
cnn_model = tf.keras.models.Sequential()
# Convolution layer
cnn_model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=[128, 128, 3]))
# Pooling
cnn_model.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
# Adding another layer
cnn_model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'))
cnn_model.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
# Flatten
cnn_model.add(tf.keras.layers.Flatten())
# Fully connected layer
cnn_model.add(tf.keras.layers.Dense(units=128, activation='relu'))
# Output layer
cnn_model.add(tf.keras.layers.Dense(units=1, activation='softmax'))
cnn_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Training the model
cnn_model.fit(x=train_generator, validation_data=validation_generator, epochs=8)