Convolutional Neural Network
1. Base
I'm going to present you how to create a convolutional neural network, who recognize you with my className in python.
You can retrieve this code on github :
https://github.com/regismeyssonnier/NeuralNetwork/tree/main/MyCamNetworkFirst, you have to make some import in your code:
import cv2
import sys
import numpy as np
# TensorFlow and tf.keras
import tensorflow as tf
# Helper libraries
import matplotlib.pyplot as plt
print(tf.__version__)
import os
import PIL
import PIL.Image
import pathlib
import matplotlib.pyplot as plt
This import can allow you to import the useful library to create this CNN.
2. Initialization
You have to use my className MyNetwork.
className MyNetwork:
def __init__(self, className_name, imw, imh, dataset_url):
self.classNamename = className_name
self.w = imw
self.h = imh
self.dataset_url = dataset_url
self.model = 0
def init_model(self, bsz, valid_sp):
self.batch_size = bsz
self.validation_rate = valid_sp
self.train_ds = tf.keras.utils.image_dataset_from_directory(
pathlib.Path(self.dataset_url),
validation_split=self.validation_rate,
subset="training",
seed=123,
image_size=(self.h, self.w),
batch_size=self.batch_size)
self.val_ds = tf.keras.utils.image_dataset_from_directory(
pathlib.Path(self.dataset_url),
validation_split=self.validation_rate,
subset="validation",
seed=123,
image_size=(self.h, self.w),
batch_size=self.batch_size)
The method __init__(...) is the constructor of the className, and the method init_model() initialize the data useful for creating the CNN like the training and validation data.
3. Creation
After that, you have to create the CNN with the function create_model().
def create_model(self):
self.model = tf.keras.Sequential([
tf.keras.layers.Rescaling(1./255),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(32, 3, activation='relu'),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(2)
])
self.model.compile(
optimizer='adam',
loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
After initializing the model(CNN), you create the model like that. There is some convolution and pooling operation on the image before enter the layers of the CNN. For more info, go to the tensorflow documentation
4. Use the CNN
This is the total code to use the className MyNetwork in order to create the CNN and save it in some files.
# To create and save the CNN
mynet = MyNetwork("regis", 180, 180, "image/copy")
mynet.init_model(25, 0.2)
mynet.create_model()
mynet.train_model(10)
mynet.get_history()
mynet.save_model("model/regismodel")
# To load the model and predict if it's you on the image.
mynet.load_model("model/regismodel")
mynet.predict("image/test.png")
This piece of code like you see, create an object MyNetwork, initialize, create, train the model. After that, we get and show some information about the history of the accuracy and loss of the model. Then, we save the model.
5. The project
Finally, the className MyNetwork is a part of the project MyCamNetwork. This is a project which use the webcam to detect you, your face with other className, and play some games. This project is accessible via the link give at the beginning of this article.
To use the total project, run the command python3 mycam.py on your pc.