Image classification- Machine learning in python keras and tensorflow



Image classification with keras and tensorflow in python|machine learning using python keras

In this tutorial we will discuss about Image classification with keras and tensorflow in python|machine learning using python keras.This example shows how to do image classification from scratch, starting from JPEG image files on disk, without leveraging pre-trained weights or a pre-made Keras Application model. We demonstrate the workflow on the Kaggle Cats vs Dogs binary classification dataset.We use the image_dataset_from_directory utility to generate the datasets, and we use Keras image preprocessing layers for image standardization and data augmentation.

image-classification-keras-tensorflow-python-machine-learning.png


step:-1 Import following libraries:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

step-2: download and extract data:

!curl -O https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip
!unzip -q kagglecatsanddogs_3367a.zip
!ls

step-3:Get dataset


image_size=(180, 180)
batch_size=32

train_ds=tf.keras.preprocessing.image_dataset_from_directory(
"PetImages",
validation_split=0.2,
subset="training",
seed=1337,
image_size=image_size,
batch_size=batch_size,
)
val_ds=tf.keras.preprocessing.image_dataset_from_directory(
"PetImages",
validation_split=0.2,
subset="validation",
seed=1337,
image_size=image_size,
batch_size=batch_size,
)

step-4:visualize the dataset using matplotlib

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
for i in range(9):
ax=plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(int(labels[i]))
plt.axis("off")

step-5:perform image augmentation

data_augmentation=keras.Sequential(
[
layers.RandomFlip("horizontal"),
layers.RandomRotation(0.1),
]
)

step-6:visualize the augmented data


plt.figure(figsize=(10, 10))
for images, _ in train_ds.take(1):
for i in range(9):
augmented_images=data_augmentation(images)
ax=plt.subplot(3, 3, i + 1)
plt.imshow(augmented_images[0].numpy().astype("uint8"))
plt.axis("off")


step-7:dataset performance

train_ds=train_ds.prefetch(buffer_size=32)
val_ds=val_ds.prefetch(buffer_size=32)

step-8:make mechine model


def make_model(input_shape, num_classes):
inputs=keras.Input(shape=input_shape)
x=data_augmentation(inputs)

# Entry block
x=layers.Rescaling(1.0 / 255)(x)
x=layers.Conv2D(32, 3, strides=2, padding="same")(x)
x=layers.BatchNormalization()(x)
x=layers.Activation("relu")(x)

x=layers.Conv2D(64, 3, padding="same")(x)
x=layers.BatchNormalization()(x)
x=layers.Activation("relu")(x)

previous_block_activation=x

for size in [128, 256, 512, 728]:
x=layers.Activation("relu")(x)
x=layers.SeparableConv2D(size, 3, padding="same")(x)
x=layers.BatchNormalization()(x)

x=layers.Activation("relu")(x)
x=layers.SeparableConv2D(size, 3, padding="same")(x)
x=layers.BatchNormalization()(x)

x=layers.MaxPooling2D(3, strides=2, padding="same")(x)


residual=layers.Conv2D(size, 1, strides=2, padding="same")(
previous_block_activation
)
x=layers.add([x, residual])
previous_block_activation=x

x=layers.SeparableConv2D(1024, 3, padding="same")(x)
x=layers.BatchNormalization()(x)
x=layers.Activation("relu")(x)

x=layers.GlobalAveragePooling2D()(x)
if num_classes==2:
activation="sigmoid"
units=1
else:
activation="softmax"
units=num_classes

x=layers.Dropout(0.5)(x)
outputs=layers.Dense(units, activation=activation)(x)
return keras.Model(inputs, outputs)


model=make_model(input_shape=image_size + (3,), num_classes=2)
keras.utils.plot_model(model, show_shapes=True)


step-9:train a model

epochs=50

callbacks=[
keras.callbacks.ModelCheckpoint("save_at_{epoch}.h5"),
]
model.compile(
optimizer=keras.optimizers.Adam(1e-3),
loss="binary_crossentropy",
metrics=["accuracy"],
)
model.fit(
train_ds, epochs=epochs, callbacks=callbacks, validation_data=val_ds,
)

step-10:Execute inference on new dataset:


img=keras.preprocessing.image.load_img(
"PetImages/Cat/6779.jpg", target_size=image_size
)
img_array=keras.preprocessing.image.img_to_array(img)
img_array=tf.expand_dims(img_array, 0)

predictions=model.predict(img_array)
score=predictions[0]
print(
"This image is %.2f percent cat and %.2f percent dog."
% (100 * (1 - score), 100 * score)
)



Comments