Python | Image Classification using Keras

Python | Image Classification using Keras

Image classification is a common task in deep learning where you train a model to predict the class or label of an input image. Keras, which is an open-source neural network library written in Python, provides a convenient way to build and train deep learning models.

Here's a basic guide to image classification using Keras:

1. Setup:

You'll first need to install the necessary libraries. Typically, TensorFlow 2.x includes Keras as its high-level API:

pip install tensorflow 

2. Import Necessary Modules:

import numpy as np import tensorflow as tf from tensorflow.keras import layers, models, datasets 

3. Load Data:

For simplicity, we'll use the CIFAR-10 dataset, which is a set of 60,000 32x32 color images in 10 classes, with 6,000 images per class.

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data() # Normalize pixel values between 0 and 1 train_images, test_images = train_images / 255.0, test_images / 255.0 

4. Define the Model:

Let's define a simple convolutional neural network (CNN) model:

model = models.Sequential([ layers.Conv2D(32, (3,3), activation='relu', input_shape=(32, 32, 3)), layers.MaxPooling2D((2,2)), layers.Conv2D(64, (3,3), activation='relu'), layers.MaxPooling2D((2,2)), layers.Conv2D(64, (3,3), activation='relu'), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(10) ]) 

5. Compile the Model:

model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) 

6. Train the Model:

history = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels)) 

7. Evaluate the Model:

After training, you can evaluate the model's performance on the test dataset:

test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\nTest accuracy:', test_acc) 

8. Make Predictions:

To make predictions on new images, you can use:

predictions = model.predict(test_images) predicted_labels = np.argmax(predictions, axis=1) 

This basic example demonstrates how to build, train, and evaluate a CNN for image classification using Keras. Depending on your specific needs, you might want to augment the data, use a more complex architecture, employ transfer learning, or fine-tune the model.


More Tags

my.cnf datatemplate beautifulsoup pagedlist binary-tree liquid oracle-call-interface structure isnullorempty sparse-checkout

More Programming Guides

Other Guides

More Programming Examples