To perform image classification on a Jupyter notebook, you can use popular deep-learning libraries such as TensorFlow and Keras. Here's a step-by-step guide to help you get started:
Install required libraries: First, ensure you have the necessary libraries installed. You can install them using pip or conda. Here's how to install them using pip:
bash
!pip install tensorflow pillow
Import necessary libraries: In your Jupyter notebook, import the required libraries:
python
# Import necessary libraries
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.applications import VGG16
from PIL import Image
Prepare your dataset: Organize your image dataset into separate folders for each class. For example, if you're classifying cats and dogs, create two folders named 'cats' and 'dogs' containing the respective images.
Load and preprocess the dataset: Use tf.keras.utils.image_dataset_from_directory to load and preprocess the dataset. Ensure that the labels are one-hot encoded by specifying label_mode='categorical'. Here's an example:
python
data_dir = 'path/to/your/dataset'
batch_size = 32
img_height, img_width = 224, 224 # Standard size for VGG16
# Split the dataset into training and validation data
train_dataset = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2, # 20% of the data to be used for validation
subset="training",
seed=123, # For reproducibility
image_size=(img_height, img_width),
batch_size=batch_size, # Number of images processed before updating weights
label_mode='categorical'
)
validation_dataset = tf.keras.utils.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size,
label_mode='categorical'
)
Create a model: You can create a simple convolutional neural network (CNN) or use a pre-trained model like VGG16. Here's an example using VGG16:
python
# Use VGG16 as the base model
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(img_height, img_width, 3))
# weights='imagenet': Load weights pretrained on ImageNet
# include_top=False: Exclude the fully connected layers which classifies classes on ImageNet,
# allowing the model to detect general image features and classify new models.
# Add custom layers on top of the pretrained model
x = base_model.output # 3D tensor of feature maps
x = Flatten()(x) # Flatten to 1D because dense layers need 1D input
x = Dense(1024, activation='relu')(x) # 1024 neurons with ReLU activation function
# Output layer with the number of neurons equal to the number of classes in the data
# Softmax activation is a function applied to the output layer that converts raw scores
# to probabilities that sum to 1. The class with the highest probability is chosen as the predicted class.
predictions = Dense(len(train_dataset.class_names), activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions) # Final model
# Freeze the layers of the base model to prevent updates during training
for layer in base_model.layers:
layer.trainable = False
# Compile the model using Adam optimizer for adaptive learning rate, categorical cross entropy loss
# function for multi-class classification, and the accuracy metric to evaluate the model's performance.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Train the model: Train the model using the fit method:
python
model.fit(
train_dataset,
epochs=10, # number of complete passes through the dataset
validation_data=validation_dataset
)
Evaluate and predict: Evaluate the model on the test dataset and make predictions:
Load and preprocess the test dataset
python
test_dataset = tf.keras.utils.image_dataset_from_directory(
'path/to/your/test_data',
image_size=(img_height, img_width),
batch_size=batch_size
)
# Evaluate the model's performance
test_loss, test_acc = model.evaluate(test_dataset)
print(f'Test accuracy: {test_acc}')
# Predict class of a single image
img = Image.open('path/to/your/image.jpg')
img = img.resize((img_height, img_width))
img = np.array(img) / 255.0 # Normalize pixel value for an 8-bit image
img = np.expand_dims(img, axis=0) # Add a batch size dimension of 1
prediction = model.predict(img) # Predict probabilities of each class
print(f'Predicted class: {np.argmax(prediction)}') # Output the class with the highest probability
This should give you a good starting point for image classification on a Jupyter notebook. You can further customize the model architecture, preprocessing, and training parameters to improve the performance.