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 numpy as np
from tensorflow import keras
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
# Set path to your dataset and define batch size and image dimensions
data_dir = 'path/to/your/dataset'
batch_size = 32
img_height, img_width = 224, 224
# Load training and validation datasets
train_dataset = keras.utils.image_dataset_from_directory(
data_dir, # directory containing the dataset
validation_split=0.2, # keep 20% of images for validation
subset="training", # use the training subset
seed=123, # for reproducibility
image_size=(img_height, img_width), # resize images to this size
batch_size=batch_size, # number of images to process at once
label_mode='categorical' # one-hot encode the labels
)
validation_dataset = 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
# Load the VGG16 model without the top layer (which is used for 1000-class classification)
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(img_height, img_width, 3))
# Add new layers on top of the base model for our specific classification task
x = base_model.output
x = Flatten()(x) # flatten the output of the last convolutional layer
x = Dense(1024, activation='relu')(x) # add a dense layer with 1024 neurons and ReLU activation
predictions = Dense(len(train_dataset.class_names), activation='softmax')(x) # output layer with softmax activation
# Create the final model by specifying the inputs and outputs
model = Model(inputs=base_model.input, outputs=predictions)
# Freeze the layers of the base model so that they are not trained
for layer in base_model.layers:
layer.trainable = False
# Compile the model with the Adam optimizer and categorical cross-entropy loss for multi-class classification
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Train the model: Train the model using the fit method:
python
# Train the model for 10 epochs, using the training dataset and validating on the validation dataset
model.fit(
train_dataset, # training dataset
epochs=10, # number of times the model will go through the entire training dataset
validation_data=validation_dataset # dataset used for validation after each epoch
)
Evaluate and predict: Evaluate the model on the test dataset and make predictions:
python
# Load the test dataset
test_dataset = keras.utils.image_dataset_from_directory(
'path/to/your/test_data', # directory containing the test dataset
image_size=(img_height, img_width), # resize images to this size
batch_size=batch_size # number of images to process at once
)
# Evaluate the model on the test dataset and print the test accuracy
test_loss, test_acc = model.evaluate(test_dataset)
print(f'Test accuracy: {test_acc}')
# Make a prediction on a single image
img = Image.open('path/to/your/image.jpg') # open the image file
img = img.resize((img_height, img_width)) # resize the image to match the input size of the model
img = np.array(img) / 255.0 # convert the image to a numpy array and scale the pixel values to be between 0 and 1
img = np.expand_dims(img, axis=0) # add a batch dimension to the image
prediction = model.predict(img) # make a prediction using the model
print(f'Predicted class: {np.argmax(prediction)}') # print the index of 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.