In this blog, we discuss how beginners (from High School students to professionals) can get started with simple TensorFlow coding.
First, let’s answer some basic questions.
What is TensorFlow?
TensorFlow is an open-source packaged originally developed by Google, which enables users to create and train powerful deep learning models in Python.
Why should I learn TensorFlow?
TensorFlow is one of the most popular packages available for Deep Learning. It is used by both students and professionals. It can be used to create both simple and complex neural networks, so if you learn it you can do a lot of things with it. Since it is used for both High School projects and in companies - the skill will serve you well in the future.
Does TensorFlow need coding?
Yes and No. In this blog, we will show you how to generate TensorFlow code automatically for different situations. This does not require any coding. However, you can also change this code. If you want to do that, you will need to code.
What can I use TensorFlow for?
TensorFlow has been used for many types of neural networks and applications, too many to mention here. In this blog, we will focus on its use for Image Classification.
Is TensorFlow a type of AI?
No. TensorFlow is a platform. You can program it to create many different types of AIs. In this blog, we will show you how to use TensorFlow to create image classification AIs using a particular type of Neural Network called MobileNetV2. MobileNetV2 is a great deep learning network because it is very recent (introduced by Google in 2019) and so state of the art, and it is also very efficient and can run on both servers and mobile devices.
Let’s get to it!
In the video below we show how you can use Navigator to generate TensorFlow code for image classification. You can upload different categories of images and then ask Navigator to train an image AI to classify them. You can then use code generate to get a simple version of the TensorFlow code, and download it you your local computer or open it directly in Google Colab.
Now that you know how to generate this code - what does the code itself look like? It is listed below:
# Please replace the brackets below with the location of your folder which included the subfolders for images
PATH = '<>'
def create_model(base_model, num_classes):
# Grab the last layer and add a few extra layers to it
x=base_model.output
x=GlobalAveragePooling2D()(x)
# Dense layer 1
x=tf.keras.layers.Dense(1024,activation='relu')(x)
# Final layer with softmax activation
preds=tf.keras.layers.Dense(num_classes,activation='softmax')(x)
# Create the final model
model=Model(inputs=base_model.input,outputs=preds)
return model
# Import packages needed to create a imaage classification model
import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
from keras.applications.resnet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dense,GlobalAveragePooling2D
from keras.models import Model
from tensorflow.keras.preprocessing import image_dataset_from_directory
BATCH_SIZE = 32
IMG_SIZE = (224, 224)
# Create the data generation pipeline for training and validation
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input, validation_split=0.2) # set validation split
train_generator = train_datagen.flow_from_directory(PATH,
target_size=IMG_SIZE,
color_mode='rgb',
batch_size=BATCH_SIZE,
class_mode='categorical',
shuffle=True,
subset = 'training')
validation_generator = train_datagen.flow_from_directory(PATH,
target_size=IMG_SIZE,
color_mode='rgb',
batch_size=BATCH_SIZE,
class_mode='categorical',
shuffle=True,
subset = 'validation')
# Download the model
base_model = tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights='imagenet')
for layer in base_model.layers:
layer.trainable=False
# If we want to set the first 20 layers of the network to be non-trainable
for layer in base_model.layers[:150]:
layer.trainable=False
for layer in base_model.layers[150:]:
layer.trainable=True
# Specify the number of classes
num_classes = 2
# Create the base model
model = create_model(base_model,num_classes)
print(len(base_model.layers))
base_learning_rate = 0.000005 #decrease for different results; use excel sheet to note down results from each change to learning rate and epochs
model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
# Adam optimizer
# loss function will be categorical cross entropy
# evaluation metric will be accuracy
step_size_train=train_generator.n//train_generator.batch_size
history_fine = model.fit(train_generator,
steps_per_epoch=step_size_train,
epochs=1, #<-- increase for higher accuracy
validation_data = validation_generator)
# Populating matrics -> accuracy & loss
acc = history_fine.history['accuracy']
val_acc = history_fine.history['val_accuracy']
loss = history_fine.history['loss']
val_loss = history_fine.history['val_loss']
print('Training Accuracy: ', acc)
print('Validation Accuracy: ', acc)
print('Training Loss: ', loss)
print('Validation Loss: ', val_loss)
# Predicting code for an image
from tensorflow.keras.preprocessing import image
# Please replace the brackets below with the location of your image which need to predict
img_path = '<>'
img = image.load_img(img_path, target_size=IMG_SIZE)
img_array = image.img_to_array(img)
img_batch = np.expand_dims(img_array, axis=0)
img_preprocessed = preprocess_input(img_batch)
prediction = model.predict(img_preprocessed)
print(prediction)
You can run this code directly on your computer or in Google Colab Notebook. The comments show you exactly what each code block does and how to change it.
What kinds of projects can you do in High School with TensorFlow?
You can see an example of Detecting Diabetic Retinopathy and an example of Detecting Disease in Tomato Plants here. Both use Deep Learning and TensorFlow.
Do I need an AIClub account to use TensorFlow Code Generator?
You can sign up for a free account at https://corp.aiclub.world. Once you have signed up, click on your avatar and select Go To Navigator. You can follow the instructions in the video from there.
コメント