Deep Learning Image Classifier
Abstract
Deep Learning Image Classifier is a Python project that uses deep learning to classify images. The application features data preprocessing, model training, and evaluation, demonstrating best practices in computer vision and AI.
Prerequisites
- Python 3.8 or above
- A code editor or IDE
- Basic understanding of deep learning and computer vision
- Required libraries:
tensorflow
tensorflow
,keras
keras
,numpy
numpy
,matplotlib
matplotlib
Before you Start
Install Python and the required libraries:
Install dependencies
pip install tensorflow keras numpy matplotlib
Install dependencies
pip install tensorflow keras numpy matplotlib
Getting Started
Create a Project
- Create a folder named
deep-learning-image-classifier
deep-learning-image-classifier
. - Open the folder in your code editor or IDE.
- Create a file named
deep_learning_image_classifier.py
deep_learning_image_classifier.py
. - Copy the code below into your file.
Write the Code
⚙️ Deep Learning Image Classifier
Deep Learning Image Classifier
"""
Deep Learning Image Classifier
Features:
- Image classification using deep learning
- Training and prediction modules
- Modular design
- CLI interface
- Error handling
"""
import sys
import os
import numpy as np
try:
import tensorflow as tf
from tensorflow.keras import layers, models
except ImportError:
tf = None
layers = None
models = None
class ImageClassifier:
def __init__(self, input_shape=(64,64,3), num_classes=2):
self.model = models.Sequential([
layers.Conv2D(32, (3,3), activation='relu', input_shape=input_shape),
layers.MaxPooling2D(2,2),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D(2,2),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes, activation='softmax')
]) if models else None
if self.model:
self.model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
def train(self, train_dir, epochs=5):
if self.model:
datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_data = datagen.flow_from_directory(train_dir, target_size=(64,64), batch_size=32, class_mode='categorical')
self.model.fit(train_data, epochs=epochs)
self.model.save('image_classifier.h5')
def predict(self, img_path):
if self.model:
img = tf.keras.preprocessing.image.load_img(img_path, target_size=(64,64))
x = tf.keras.preprocessing.image.img_to_array(img)/255.0
x = np.expand_dims(x, axis=0)
preds = self.model.predict(x)
return np.argmax(preds)
return None
class CLI:
@staticmethod
def run():
print("Deep Learning Image Classifier")
while True:
cmd = input('> ')
if cmd.startswith('train'):
parts = cmd.split()
if len(parts) < 2:
print("Usage: train <train_dir>")
continue
clf = ImageClassifier()
clf.train(parts[1])
elif cmd.startswith('predict'):
parts = cmd.split()
if len(parts) < 2:
print("Usage: predict <img_path>")
continue
clf = ImageClassifier()
clf.model.load_weights('image_classifier.h5')
label = clf.predict(parts[1])
print(f"Predicted class: {label}")
elif cmd == 'exit':
break
else:
print("Unknown command")
if __name__ == "__main__":
try:
CLI.run()
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
Deep Learning Image Classifier
"""
Deep Learning Image Classifier
Features:
- Image classification using deep learning
- Training and prediction modules
- Modular design
- CLI interface
- Error handling
"""
import sys
import os
import numpy as np
try:
import tensorflow as tf
from tensorflow.keras import layers, models
except ImportError:
tf = None
layers = None
models = None
class ImageClassifier:
def __init__(self, input_shape=(64,64,3), num_classes=2):
self.model = models.Sequential([
layers.Conv2D(32, (3,3), activation='relu', input_shape=input_shape),
layers.MaxPooling2D(2,2),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D(2,2),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes, activation='softmax')
]) if models else None
if self.model:
self.model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
def train(self, train_dir, epochs=5):
if self.model:
datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_data = datagen.flow_from_directory(train_dir, target_size=(64,64), batch_size=32, class_mode='categorical')
self.model.fit(train_data, epochs=epochs)
self.model.save('image_classifier.h5')
def predict(self, img_path):
if self.model:
img = tf.keras.preprocessing.image.load_img(img_path, target_size=(64,64))
x = tf.keras.preprocessing.image.img_to_array(img)/255.0
x = np.expand_dims(x, axis=0)
preds = self.model.predict(x)
return np.argmax(preds)
return None
class CLI:
@staticmethod
def run():
print("Deep Learning Image Classifier")
while True:
cmd = input('> ')
if cmd.startswith('train'):
parts = cmd.split()
if len(parts) < 2:
print("Usage: train <train_dir>")
continue
clf = ImageClassifier()
clf.train(parts[1])
elif cmd.startswith('predict'):
parts = cmd.split()
if len(parts) < 2:
print("Usage: predict <img_path>")
continue
clf = ImageClassifier()
clf.model.load_weights('image_classifier.h5')
label = clf.predict(parts[1])
print(f"Predicted class: {label}")
elif cmd == 'exit':
break
else:
print("Unknown command")
if __name__ == "__main__":
try:
CLI.run()
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
Example Usage
Run image classifier
python deep_learning_image_classifier.py
Run image classifier
python deep_learning_image_classifier.py
Explanation
Key Features
- Data Preprocessing: Prepares image data for training.
- Model Training: Trains a deep learning model to classify images.
- Evaluation: Assesses model performance.
- Error Handling: Validates inputs and manages exceptions.
Code Breakdown
- Import Libraries and Setup Data
deep_learning_image_classifier.py
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
deep_learning_image_classifier.py
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
- Data Preprocessing and Model Training Functions
deep_learning_image_classifier.py
def preprocess_images(images):
# Dummy preprocessing (for demo)
return np.array(images) / 255.0
def build_model(input_shape, num_classes):
model = keras.Sequential([
keras.layers.Flatten(input_shape=input_shape),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(num_classes, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return model
deep_learning_image_classifier.py
def preprocess_images(images):
# Dummy preprocessing (for demo)
return np.array(images) / 255.0
def build_model(input_shape, num_classes):
model = keras.Sequential([
keras.layers.Flatten(input_shape=input_shape),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(num_classes, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return model
- Evaluation and Error Handling
deep_learning_image_classifier.py
def evaluate_model(model, X_test, y_test):
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
def main():
print("Deep Learning Image Classifier")
# images, labels = ... # Load image data
# X = preprocess_images(images)
# model = build_model(X.shape[1:], len(set(labels)))
# model.fit(X, labels, epochs=5)
# evaluate_model(model, X, labels)
print("[Demo] Classification logic here.")
if __name__ == "__main__":
main()
deep_learning_image_classifier.py
def evaluate_model(model, X_test, y_test):
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
def main():
print("Deep Learning Image Classifier")
# images, labels = ... # Load image data
# X = preprocess_images(images)
# model = build_model(X.shape[1:], len(set(labels)))
# model.fit(X, labels, epochs=5)
# evaluate_model(model, X, labels)
print("[Demo] Classification logic here.")
if __name__ == "__main__":
main()
Features
- Image Classification: Data preprocessing, model training, and evaluation
- Modular Design: Separate functions for each task
- Error Handling: Manages invalid inputs and exceptions
- Production-Ready: Scalable and maintainable code
Next Steps
Enhance the project by:
- Integrating with real image datasets
- Supporting advanced deep learning architectures
- Creating a GUI for classification
- Adding real-time prediction
- Unit testing for reliability
Educational Value
This project teaches:
- Computer Vision: Image classification and deep learning
- Software Design: Modular, maintainable code
- Error Handling: Writing robust Python code
Real-World Applications
- Medical Imaging
- Security Systems
- AI Platforms
Conclusion
Deep Learning Image Classifier demonstrates how to build a scalable and accurate image classification tool using Python. With modular design and extensibility, this project can be adapted for real-world applications in AI, healthcare, and more. For more advanced projects, visit Python Central Hub.
Was this page helpful?
Let us know how we did