Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Intelligent Projects Using Python
Intelligent Projects Using Python

Intelligent Projects Using Python: 9 real-world AI projects leveraging machine learning and deep learning with TensorFlow and Keras

eBook
$20.98 $29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Intelligent Projects Using Python

Transfer Learning

Transfer learning is the process of transferring the knowledge gained in one task in a specific domain to a related task in a similar domain. In the deep learning paradigm, transfer learning generally refers to the reuse of a pre-trained model as the starting point for another problem. The problems in computer vision and natural language processing require a lot of data and computational resources, to train meaningful deep learning models. Transfer learning has gained a lot of importance in the domains of vision and text, since it alleviates the need for a large amount of training data and training time. In this chapter, we will use transfer learning to solve a healthcare problem.

Some key topics related to transfer learning that we will touch upon in this chapter are as follows:

  • Using transfer learning to detect diabetic retinopathy conditions in the human...

Technical requirements

Introduction to transfer learning

In a traditional machine learning paradigm (see Figure 2.1), every use case or task is modeled independently, based on the data at hand. In transfer learning, we use the knowledge gained from a particular task (in the form of architecture and model parameters) to solve a different (but related) task, as illustrated in the following diagram:

Figure 2.1: Traditional machine learning versus transfer learning

Andrew Ng, in his 2016 NIPS tutorial, stated that transfer learning would be the next big driver of machine learning's commercial success (after supervised learning); this statement grows truer with each passing day. Transfer learning is now used extensively in problems that need to be solved with artificial neural networks. The big question, therefore, is why this is the case.

Training an artificial neural network from scratch is a difficult...

Transfer learning and detecting diabetic retinopathy

In this chapter, using transfer learning, we are going to build a model to detect diabetic retinopathy in the human eye. Diabetic retinopathy is generally found in diabetic patients, where high blood sugar levels cause damage to the blood vessels in the retina. The following image shows a normal retina on the left, and one with diabetic retinopathy on the right:

Figure 2.2: A normal human retina versus a retina with diabetic retinopathy

In healthcare, diabetic retinopathy detection is generally a manual process that involves a trained physician examining color fundus retina images. This introduces a delay in the process of diagnosis, often leading to delayed treatment. As a part of our project, we are going to build a robust artificial intelligence system that can take the color fundus images of the retina and classify the...

The diabetic retinopathy dataset

The dataset for the building the Diabetic Retinopathy detection application is obtained from Kaggle and can be downloaded from following the link: https://www.kaggle.com/c/ classroom-diabetic-retinopathy-detection-competition/data.

Both the training and the holdout test datasets are present within the train_dataset.zip file, which is available at the preceding link.

We will use the labeled training data to build the model through cross-validation. We will evaluate the model on the holdout dataset.

Since we are dealing with class prediction, accuracy will be a useful validation metric. Accuracy is defined as follows:

Here, c is the number of correctly classified samples, and N is the total number of evaluated samples.

We will also use the quadratic weighted kappa statistics to determine the quality of the model, and to have a benchmark as to how...

Formulating the loss function

The data for this use case has five classes, pertaining to no diabetic retinopathy, mild diabetic retinopathy, moderate diabetic retinopathy, severe diabetic retinopathy, and proliferative diabetic retinopathy. Hence, we can treat this as a categorical classification problem. For our categorical classification problem, the output labels need to be one-hot encoded, as shown here:

  • No diabetic retinopathy: [1 0 0 0 0]T
  • Mild diabetic retinopathy: [0 1 0 0 0]T
  • Moderate diabetic retinopathy: [0 0 1 0 0]T
  • Severe diabetic retinopathy: [0 0 0 1 0]T
  • Proliferative diabetic retinopathy: [0 0 0 0 1]T

Softmax would be the best activation function for presenting the probability of the different classes in the output layer, while the sum of the categorical cross-entropy loss of each of the data points would be the best loss to optimize. For a single data point...

Taking class imbalances into account

Class imbalance is a major problem when it comes to classification. The following diagram depicts the class densities of the five severity classes:

Figure 2.4: Class densities of the five severity classes

As we can see from the preceding chart, nearly 73% of the training data belongs to Class 0, which stands for no diabetic retinopathy condition. So if we happen to label all data points as Class 0, then we would have 73% percent accuracy. This is not desirable in patient heath conditions. We would rather have a test say a patient has a certain heath condition when it doesn't (false positive) than have a test that misses detecting a certain heath condition when it does (false negative). A 73% accuracy may mean nothing if the model learns to classify all points as belonging to Class 0.

Detecting the higher severity classes are more important...

Preprocessing the images

The images for the different classes will be stored in different folders, so it will be easy to label their classes. We will read the images using Opencv functions, and will resize them to different dimensions, such as 224 x 224 x 3. We'll subtract the mean pixel intensity channel-wise from each of the images, based on the ImageNet dataset. This means subtraction will bring the diabetic retinopathy images to the same intensity range as that of the processed ImageNet images, on which the pre-trained models are trained. Once each image has been prepossessed, they will be stored in a numpy array. The image preprocessing functions can be defined as follows:

def get_im_cv2(path,dim=224):
img = cv2.imread(path)
resized = cv2.resize(img, (dim,dim), cv2.INTER_LINEAR)
return resized

def pre_process(img):
img[:,:,0] = img[:,:,0] - 103...

Additional data generation using affine transformation

We will use the keras ImageDataGenerator to generate additional data, using affine transformation on the image pixel coordinates. The transformations that we will primarily use are rotation, translation, and scaling. If the pixel spatial coordinate is defined by x = [x1x2]T ∈ R2, then the new coordinate of the pixel can be given by the following:

Here, M = R2x2 is the affine transformation matrix, and b = [b1 b2]T ∈ R2 is a translation vector.

The term b1 specifies the translation along one of the spatial directions, while b2 provides the translation along the other spatial dimension.

These transformations are required, because neural networks are not, in general, translational invariant, rotational invariant, or scale invariant. Pooling operations do provide some translational invariance, but it is generally...

Network architecture

We will now experiment with the pre-trained ResNet50, InceptionV3, and VGG16 networks, and find out which one gives the best results. Each of the pre-trained models' weights are based on ImageNet. I have provided the links to the original papers for the ResNet, InceptionV3, and VGG16 architectures, for reference. Readers are advised to go over these papers, to get an in-depth understanding of these architectures and the subtle differences between them.

The VGG paper link is as follows:

The ResNet paper link is as follows:

The InceptionV3 paper link is as follows:

  • Title: Rethinking the Inception Architecture for Computer Vision
  • Link: https://arxiv...

The optimizer and initial learning rate

The Adam optimizer (adaptive moment estimator) is used in training that implements an advanced version of stochastic gradient descent. The Adam optimizer takes care of the curvature in the cost function, and at the same time, it uses momentum to ensure steady progress toward a good local minima. For the problem at hand, since we are using transfer learning and want to use as many of the previously learned features from the pre-trained network as possible, we will use a small initial learning rate of 0.00001. This will ensure that the network doesn't lose the useful features learned by the pre-trained networks, and fine-tunes to an optimal point less aggressively, based on the new data for the problem at hand. The Adam optimizer can be defined as follows:

adam = optimizers.Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay...

Cross-validation

Since the training dataset is small, we will perform five-fold cross-validation, to get a better sense of the model's ability to generalize to new data. We will also use all five of the models built in the different folds of cross-validation in training, for inference. The probability of a test data point belonging to a class label would be the average probability prediction of all five models, which is represented as follows:

Since the aim is to predict the actual classes and not the probability, we would select the class that has the maximum probability. This methodology works when we are working with a classification-based network and cost function. If we are treating the problem as a regression problem, then there are a few alterations to the process, which we will discuss later on.

Model checkpoints based on validation log loss

It is always a good practice to save the model when the validation score chosen for evaluation improves. For our project, we will be tracking the validation log loss, and will save the model as the validation score improves over the different epochs. This way, after the training, we will save the model weights that provided the best validation score, and not the final model weights from when we stopped the training. The training will continue until the maximum number of epochs defined for the training is reached, or until the validation log loss hasn't reduced for 10 epochs in a row. We will also reduce the learning rate when the validation log loss doesn't improve for 3 epochs. The following code block can be used to perform the learning rate reduction and checkpoint operation:

reduce_lr = keras.callbacks.ReduceLROnPlateau...

Python implementation of the training process

The following Python code block shows an end-to-end implementation of the training process. It consists of all of the functional blocks that were discussed in the preceding sections. Let's start by calling all of the Python packages that are required, as follows:

import numpy as np
np.random.seed(1000)

import os
import glob
import cv2
import datetime
import pandas as pd
import time
import warnings
warnings.filterwarnings("ignore")
from sklearn.model_selection import KFold
from sklearn.metrics import cohen_kappa_score
from keras.models import Sequential,Model
from keras.layers.core import Dense, Dropout, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers import GlobalMaxPooling2D,GlobalAveragePooling2D
from keras.optimizers import SGD
from keras.callbacks import EarlyStopping
from...

Results from the categorical classification

The categorical classification is performed by using all three of the neural network architectures: VGG16, ResNet50, and InceptionV3. The best results were obtained using the InceptionV3 version of the transfer learning network for this diabetic retinopathy use case. In case of categorical classification we are just converting the class with the maximum predicted class probability as the predicted severity label. However since the classes in the problem has an ordinal sense one of the ways in which we can utilize the softmax probabilities is to take the expectation of the class severity with respect to the softmax probabilities and come up with an expected score as follows:

We can rank order the scores and determine three thresholds to determine which class the image belongs to. These thresholds can be chosen by training a secondary...

Inference at testing time

The following code can be used to carry out inference on the unlabeled test data:

import keras
import numpy as np
import pandas as pd
import cv2
import os
import time
from sklearn.externals import joblib
import argparse

# Read the Image and resize to the suitable dimension size
def get_im_cv2(path,dim=224):
img = cv2.imread(path)
resized = cv2.resize(img, (dim,dim), cv2.INTER_LINEAR)
return resized

# Pre Process the Images based on the ImageNet pre-trained model Image transformation
def pre_process(img):
img[:,:,0] = img[:,:,0] - 103.939
img[:,:,1] = img[:,:,0] - 116.779
img[:,:,2] = img[:,:,0] - 123.68
return img


# Function to build test input data
def read_data_test(path,dim):
test_X = []
test_files = []
file_list = os.listdir(path)
for f in file_list:
img = get_im_cv2(path + '/' + f)
img = pre_process...

Performing regression instead of categorical classification

One of the things that we discussed in the Formulating the loss function section, was the fact that the class labels are not independent categorical classes, but do have an ordinal sense with the increasing severity of the diabetic retinopathy condition. Hence, it would be worthwhile to perform regression through the defined transfer learning networks, instead of classification, and see how the results turned out. The only thing that we would need to change would be the output unit, from a softmax to a linear unit. We will, in fact, change it to be a ReLU, since we want to avoid negative scores. The following code block shows the InceptionV3 version of the regression network:

def inception_pseudo(dim=224,freeze_layers=30,full_freeze='N'):
model = InceptionV3(weights='imagenet',include_top=False...

Using the keras sequential utils as generator

Keras has a good batch generator named keras.utils.sequence() that helps you customize batch creation with great flexibility. In fact, with keras.utils.sequence() one can design the whole epoch pipeline. We are going to use this utility in this regression problem to get accustomed to this utility. For the transfer learning problem we can design a generator class using keras.utils.sequence() as follows:

class DataGenerator(keras.utils.Sequence):
'Generates data for Keras'
def __init__(self,files,labels,batch_size=32,n_classes=5,dim=(224,224,3),shuffle=True):
'Initialization'
self.labels = labels
self.files = files
self.batch_size = batch_size
self.n_classes = n_classes
self.dim = dim
self.shuffle = shuffle
self.on_epoch_end()

def __len__(self):
...

Summary

In this chapter, we went over the practical aspects of transfer learning, to solve a real-world problem in the healthcare sector. The readers are expected to further build upon these concepts by trying to customize these examples wherever possible.

The accuracy and the kappa score that we achieved through both the classification and the regression-based neural networks are good enough for production implementation. In Chapter 3, Neural Machine Translation, we will work on implementing intelligent machine translation systems, which is a much more advanced topic than what was presented in this chapter. I look forward to your participation.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • A go-to guide to help you master AI algorithms and concepts
  • 8 real-world projects tackling different challenges in healthcare, e-commerce, and surveillance
  • Use TensorFlow, Keras, and other Python libraries to implement smart AI applications

Description

This book will be a perfect companion if you want to build insightful projects from leading AI domains using Python. The book covers detailed implementation of projects from all the core disciplines of AI. We start by covering the basics of how to create smart systems using machine learning and deep learning techniques. You will assimilate various neural network architectures such as CNN, RNN, LSTM, to solve critical new world challenges. You will learn to train a model to detect diabetic retinopathy conditions in the human eye and create an intelligent system for performing a video-to-text translation. You will use the transfer learning technique in the healthcare domain and implement style transfer using GANs. Later you will learn to build AI-based recommendation systems, a mobile app for sentiment analysis and a powerful chatbot for carrying customer services. You will implement AI techniques in the cybersecurity domain to generate Captchas. Later you will train and build autonomous vehicles to self-drive using reinforcement learning. You will be using libraries from the Python ecosystem such as TensorFlow, Keras and more to bring the core aspects of machine learning, deep learning, and AI. By the end of this book, you will be skilled to build your own smart models for tackling any kind of AI problems without any hassle.

Who is this book for?

This book is intended for data scientists, machine learning professionals, and deep learning practitioners who are ready to extend their knowledge and potential in AI. If you want to build real-life smart systems to play a crucial role in every complex domain, then this book is what you need. Knowledge of Python programming and a familiarity with basic machine learning and deep learning concepts are expected to help you get the most out of the book

What you will learn

  • Build an intelligent machine translation system using seq-2-seq neural translation machines
  • Create AI applications using GAN and deploy smart mobile apps using TensorFlow
  • Translate videos into text using CNN and RNN
  • Implement smart AI Chatbots, and integrate and extend them in several domains
  • Create smart reinforcement, learning-based applications using Q-Learning
  • Break and generate CAPTCHA using Deep Learning and Adversarial Learning

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 31, 2019
Length: 342 pages
Edition : 1st
Language : English
ISBN-13 : 9781788994866
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 31, 2019
Length: 342 pages
Edition : 1st
Language : English
ISBN-13 : 9781788994866
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 137.97
Mobile Artificial Intelligence Projects
$38.99
Hands-On Artificial Intelligence for Beginners
$54.99
Intelligent Projects Using Python
$43.99
Total $ 137.97 Stars icon
Banner background image

Table of Contents

11 Chapters
Foundations of Artificial Intelligence Based Systems Chevron down icon Chevron up icon
Transfer Learning Chevron down icon Chevron up icon
Neural Machine Translation Chevron down icon Chevron up icon
Style Transfer in Fashion Industry using GANs Chevron down icon Chevron up icon
Video Captioning Application Chevron down icon Chevron up icon
The Intelligent Recommender System Chevron down icon Chevron up icon
Mobile App for Movie Review Sentiment Analysis Chevron down icon Chevron up icon
Conversational AI Chatbots for Customer Service Chevron down icon Chevron up icon
Autonomous Self-Driving Car Through Reinforcement Learning Chevron down icon Chevron up icon
CAPTCHA from a Deep-Learning Perspective Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(3 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Placeholder Mar 19, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am working in retail, especially "fast fashion" industry. Chapter 4: Style transfers using GAN is one of the use cases I am working on. This book talks about different variants of GAN such as DiscoGAN and CycleGAN in-depth. Really helpful for me.
Amazon Verified review Amazon
victor seletsky Jan 12, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great
Amazon Verified review Amazon
AnirbaN Jul 27, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really good
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.