How to Train a Neural Network with Your Own Images using TensorFlow, CNN, and Keras: A Step-by-Step Tutorial

Posted by


In this tutorial, we will learn how to train a neural network using images by loading them into TensorFlow with the help of Keras and Convolutional Neural Networks (CNN).

Step 1: Import necessary libraries
First, we need to import the necessary libraries for working with TensorFlow, Keras, and other image processing tasks:

import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
import matplotlib.pyplot as plt

Step 2: Load and preprocess the dataset
Next, we need to load and preprocess the dataset. For this tutorial, we will use the CIFAR-10 dataset which contains 60,000 32×32 color images in 10 different classes.

We can load the dataset using the following code:

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
x_train, x_test = x_train / 255.0, x_test / 255.0

Step 3: Define the CNN model
Now, we can define our CNN model using Keras. We will create a simple CNN with convolutional layers, pooling layers, and fully connected layers.

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)
])

Step 4: Compile and train the model
Next, we need to compile and train our model using the training data. We will use the Adam optimizer and sparse categorical cross-entropy loss function for this task.

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

history = model.fit(x_train, y_train, epochs=10, 
                    validation_data=(x_test, y_test))

Step 5: Evaluate the model
Finally, we can evaluate the performance of our model on the test dataset and visualize the results using the following code:

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print('Test accuracy:', test_acc)

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0, 1])
plt.legend(loc='lower right')
plt.show()

And that’s it! You have successfully trained a neural network using images by loading them into TensorFlow with the help of CNN and Keras. Feel free to experiment with different model architectures, hyperparameters, and datasets to improve the performance of your model.

0 0 votes
Article Rating
23 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@whenmathsmeetcoding1836
1 month ago

if you liked the content please support by subscribing 😇

1. here is the video for multiclass:—- https://youtu.be/1Gbcp66yYX4
2. here is video for object detection with tensorflow:—– https://youtu.be/_TCUPl3j2kI
3. here is video for object detection with YoloV3:—— https://youtu.be/zm9h4mYymk0

@jerrymavashev9885
1 month ago

Hey, I like your video a lot. However, at 4:30, how exactly did you call this image from your folder? I can't quite seem to figure it out as you didn't show exactly how you called it. Also, when I type in "img = image.load_img("basedata/train/happy/3.PNG"), it's telling me that the file isn't found and there is no such file, even though there is since I created it. Lastly, when I type in "plt.imshow(img)", it's telling me that the name 'img' is not defined. Please help…I'm following your video and this is throwing me off. Thanks

@inhibited44
1 month ago

this is very helpful. I bet if you were picking sad and happy from pictures of friends, the error goes up because too much variation in the photos

@techgenius614
1 month ago

Can u please share the link of notebook

@rohinimahadevan6954
1 month ago

Pls tell how to create classification report for this? @whenmathsmeetcoding1836

@monarch6t9
1 month ago

🥰🥰 bhai maja agya thank you vmro

@-DivyaR
1 month ago

What if we have a multiple label…what should i give in class_mode ?

@gserpentzx188
1 month ago

are these using mobilenet architecture?

@TechnoArky
1 month ago

awesome

@peterslater2914
1 month ago

Excellent video thanks alot.

@nishitachaudhary-e4m
1 month ago

we need to use new images for validation??

@TrendingHashtags-bt7tz
1 month ago

Crystal clear implementation of CNN

@mamunhasan8898
1 month ago

thanks a lot for your help

@adamcalleja9815
1 month ago

great job explaining it, you're a great teacher

@JeevaSivalingam
1 month ago

Excellent ji.Really very good explanation with real time image's 🎉🎉🎉

@guilhermepereira163
1 month ago

You are awesome

@fatihbanana
1 month ago

thanks brother

@nekuneko6823
1 month ago

for class mode what if you have multiple modes instead of only 2?

@jameslucas8369
1 month ago

this is the best video ,cong2ln broo

@AdvaithRamakrishnan
1 month ago

I am getting this error: [Errno 21] Is a directory:
I don't know why, my test folder is empty