CIFAR-10 Image Classification in TensorFlow

CIFAR-10 Image Classification in TensorFlow

The CIFAR-10 dataset consists of 60,000 32x32 color images in 10 classes, with 6,000 images per class. The dataset is split into 50,000 training images and 10,000 testing images. The classes are airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck.

Let's build a simple convolutional neural network (CNN) for CIFAR-10 image classification using TensorFlow:

1. Import Libraries:

import numpy as np import tensorflow as tf from tensorflow.keras.datasets import cifar10 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout from tensorflow.keras.utils import to_categorical 

2. Load and Preprocess the Data:

# Load the data (train_images, train_labels), (test_images, test_labels) = cifar10.load_data() # Normalize pixel values to be between 0 and 1 train_images = train_images.astype('float32') / 255.0 test_images = test_images.astype('float32') / 255.0 # Convert labels to one-hot encoded vectors train_labels = to_categorical(train_labels, 10) test_labels = to_categorical(test_labels, 10) 

3. Define the CNN Model:

model = Sequential([ Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), MaxPooling2D((2, 2)), Conv2D(64, (3, 3), activation='relu'), MaxPooling2D((2, 2)), Conv2D(64, (3, 3), activation='relu'), Flatten(), Dense(64, activation='relu'), Dropout(0.5), # Add dropout to reduce overfitting Dense(10, activation='softmax') ]) 

4. Compile the Model:

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) 

5. Train the Model:

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

6. Evaluate the Model:

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

The above code provides a simple CNN-based approach for CIFAR-10 image classification. There's plenty of room for improving this model, such as using more advanced architectures, data augmentation, regularization, etc. If you're aiming for higher accuracy on this dataset, consider exploring deeper architectures like ResNet or techniques like transfer learning.


More Tags

nullpointerexception ssrs-expression pipenv ionic-native sql-server-2000 bloburls multi-tenant azure-cosmosdb powermock sql-server-2005

More Programming Guides

Other Guides

More Programming Examples