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.
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
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
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
Can u please share the link of notebook
Pls tell how to create classification report for this? @whenmathsmeetcoding1836
🥰🥰 bhai maja agya thank you vmro
What if we have a multiple label…what should i give in class_mode ?
are these using mobilenet architecture?
awesome
Excellent video thanks alot.
we need to use new images for validation??
Crystal clear implementation of CNN
thanks a lot for your help
great job explaining it, you're a great teacher
Excellent ji.Really very good explanation with real time image's 🎉🎉🎉
You are awesome
thanks brother
for class mode what if you have multiple modes instead of only 2?
this is the best video ,cong2ln broo
I am getting this error: [Errno 21] Is a directory:
I don't know why, my test folder is empty