Train Neural Network by loading your images |TensorFlow, CNN, Keras tutorial
Table of Contents
Introduction
In this tutorial, you will learn how to create and train a neural network using your own images with TensorFlow and Keras. By leveraging the ImageDataGenerator for data labeling, you'll build a Convolutional Neural Network (CNN) that can process images effectively. This guide will walk you through each step to ensure you can replicate the process and understand the underlying concepts.
Step 1: Set Up Your Environment
Before you begin, ensure you have the necessary software installed:
- Install Python (preferably version 3.6 or above).
- Install TensorFlow and Keras using pip. Run the following command in your terminal or command prompt:
pip install tensorflow keras
Step 2: Organize Your Image Dataset
Prepare your dataset by organizing your images into folders. Each folder should represent a different class of images. For example:
dataset/class_a/image1.jpgimage2.jpg
class_b/image3.jpgimage4.jpg
Step 3: Import Necessary Libraries
In your Python script or Jupyter Notebook, import the required libraries:
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
Step 4: Set Up Image Data Generators
Use ImageDataGenerator to preprocess your images. This will help in augmenting and normalizing the dataset:
train_datagen = ImageDataGenerator(
rescale=1./255,
validation_split=0.2
)
train_generator = train_datagen.flow_from_directory(
'dataset/',
target_size=(150, 150),
batch_size=32,
class_mode='categorical',
subset='training'
)
validation_generator = train_datagen.flow_from_directory(
'dataset/',
target_size=(150, 150),
batch_size=32,
class_mode='categorical',
subset='validation'
)
Step 5: Build the CNN Model
Create a Convolutional Neural Network model by adding layers:
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(len(train_generator.class_indices), activation='softmax'))
Step 6: Compile the Model
Compile the model with an appropriate optimizer, loss function, and evaluation metric:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Step 7: Train the Model
Start training your model using the training and validation datasets:
history = model.fit(
train_generator,
steps_per_epoch=train_generator.samples // train_generator.batch_size,
validation_data=validation_generator,
validation_steps=validation_generator.samples // validation_generator.batch_size,
epochs=10
)
Step 8: Evaluate the Model
After training, evaluate the model’s performance on the validation set:
model.evaluate(validation_generator)
Conclusion
Congratulations! You have successfully created and trained a neural network using your own images. By following these steps, you can adapt the model for various image classification tasks. Consider experimenting with different architectures, data augmentations, and training parameters to improve your model's performance. Happy coding!