Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Introduction to TensorFlow for Artificial Intelligence,

Machine Learning, and Deep Learning


An Industrial Internship Report

Submitted by

SUNIL KUMAR SAH

(18BCE2470)

in partial fulfilment for the award of the degree of

Bachelor Of Engineering (B. Tech)

in

Computer Science & Engineering

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING

April-2021

DECLARATION

I hereby declare that the Industrial Internship report entitled “Introduction to


TensorFlow for Artificial Intelligence, Machine Learning, and Deep
Learning” submitted by me to Vellore Institute of Technology, Vellore in partial
fulfilment of the requirement for the award of the degree of Bachelor of
Engineering (B. Tech) in Computer Science & Engineering is a record of
bonafide industrial training undertaken by me under the supervision of Laurence
Moroney, Coursera.com (online Course). I further declare that the work
reported in this report has not been submitted and will not be submitted, either in
part or in full, for the award of any other degree or diploma in this institute or any
other institute or university.

Signature of the student

Name: Sunil Kumar Sah

Reg.Number: 18BCE2470

ACKNOWLEDGEMENT

I wish to express my sincere gratitude to my guide Andrew Ng, Coursera for providing me an
opportunity to do my internship and Lab work in “Coursera”. It was a great learning
experience to exercise the theoretical knowledge in real life design and to explore the domain
of Artificial Intelligence and Machine Learning to expand my knowledge and utilize the same
to give something

back to the field I sincerely thank the Other Guide and Mentors over there for their guidance
and encouragement in carrying out this internship. I also wish to express my gratitude to the
officials who rendered their help during the period of my internship. I also thank the
chancellor of VIT University, Vellore for providing me this opportunity to embark on this.

CERTIFICATES
TABLE OF CONTENTS

CHAPTER NO. TITLE PAGE NO.


LIST OF TABLES

LIST OF FIGURES

1 INTRODUCTION
1.1 INTRODUCTION 3
1.2 ABSTRACT 4
1.1.1 TENSORFLOW 5
1.1.2 ARTIFICIAL INTELLEGENCE 6
1.1.3 MACHINE LEARNING 7
1.1.4 DEEP LEARNING 7
2 ABOUT COURESERA (deeplearning.ai) 8
3 EXPERIENCE AT COURSERA 10
4 SUMMARY OF PROJECT 11
6 WEEKLY REPORT 14
6.1 WEEK - 1 14
6.2 WEEK - 2 18
6.3 WEEK - 3 21
6.4WEEK - 4 25
7 LAB WORK EXPALANATION 28
8 CONCLUSION 39
9 REFRENCE 40

INTRODUCTION

If anyone is a software developer who wants to build scalable AI-powered algorithms, you
need to understand how to use the tools to build them. This course is part of the upcoming
Machine Learning in TensorFlow Specialization and will teach you best practices for using
TensorFlow, a popular open-source framework for machine learning.

The Machine Learning course and Deep Learning Specialization from Andrew Ng teach the
most important and foundational principles of Machine Learning and Deep Learning. This new
deeplearning.ai TensorFlow Specialization teaches you how to use TensorFlow to implement
those principles so that you can start building and applying scalable models to real-world
problems. To develop a deeper understanding of how neural networks work, as it recommends
that you take the Deep Learning Specialization. You will gain from this course are Learn best
practices for using TensorFlow, a popular open-source machine learning framework Build a
basic neural network in TensorFlow Train a neural network for a computer vision application
Understand how to use convolutions to improve your neural network. Skills to Know

• Computer Vision
• TensorFlow
• Machine Learning

As I have learned this Course from Coursera.com Online Study platform but the Vendor
provided is DEEPLEARNING.AI. DeepLearning.AI is an education technology company that
develops a global community of AI talent.

DeepLearning.AIs expert-led educational experiences provide AI practitioners and non-


technical professionals with the necessary tools to go all the way from foundational basics to
advanced application, empowering them to build an AI-powered future.

Abstract

Today world is Transforming the digital world by using Artificial Intelligence and Deep
learning as it also by Machine Learning. The people still can’t imagine about the future world.
how the world universe is transforming the according to the nature as same like the computer
or digital world is also transforming it by Artificial Intelligence and Deep Learning. As Neural
Network and CNN Model CovNet etc. are major part of this subject. That makes the more
reliable use in the Real world. The Machine Learning course and Deep Learning Specialization
from Andrew Ng teach the most important and foundational principles of Machine Learning
and Deep Learning. This new deeplearning.ai TensorFlow Specialization teaches you how to
use TensorFlow to implement those principles so that you can start building and applying
scalable models to real-world problems. To develop a deeper understanding of how neural
networks work, as it recommends that you take the Deep Learning.

TENSORFLOW

TensorFlow is a free and open-source software library for machine learning. It can be used
across a range of tasks but has a particular focus on training and inference of deep neural
networks. TensorFlow is Google Brain's second-generation system. Version 1.0.0 was released
on February 11, 2017. While the reference implementation runs on single devices, TensorFlow
can run on multiple CPUs and GPUs (with optional CUDA and SYCL extensions for general-
purpose computing on graphics processing units). TensorFlow is available on 64-bit Linux,
macOS, Windows, and mobile computing platforms including Android and iOS.

Its flexible architecture allows for the easy deployment of computation across a variety of
platforms (CPUs, GPUs, TPUs), and from desktops to clusters of servers to mobile and edge
devices. In May 2016, Google announced its Tensor processing unit (TPU), an application-
specific integrated circuit (ASIC, a hardware chip) built specifically for machine learning and
tailored for TensorFlow. A TPU is a programmable AI accelerator designed to provide high

Figure-1 Image or LOGO of Tensor Flow By Google.

throughput of low-precision arithmetic (e.g., 8-bit), and oriented toward using or running
models rather than training them. Google announced they had been running TPUs inside their
data centers for more than a year, and had found them to deliver an order of magnitude better-
optimized performance per watt for machine learning. Its Transforming day y day new
technology.

Why TensorFlow

Whether you’re an expert or a beginner, TensorFlow is an end-to-end platform that makes it


easy for you to build and deploy ML models

• Easy model building


• Robust ML production anywhere
• Powerful experimentation for research

Explore how various companies from a wide variety of industries implement ML to solve their
biggest problems. From healthcare to social networks and even ecommerce, ML can be
integrated into your industry and company.Interested in utilizing ML in your own business?
Connect with one of our AI Service Partners to learn more.

A short Code For install TensorFlow

import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()


x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)


model.evaluate(x_test, y_test)

TensorFlow offers multiple levels of abstraction so you can choose the right one for your needs.
Build and train models by using the high-level Keras API, which makes getting started with
TensorFlow and machine learning easy.

If you need more flexibility, eager execution allows for immediate iteration and intuitive
debugging. For large ML training tasks, use the Distribution Strategy API for distributed
training on different hardware configurations without changing the model definition.

ARTIFICIAL INTELLIGENCE
It is the science and engineering of making intelligent machines, especially intelligent computer
programs. It is related to the similar task of using computers to understand human intelligence,
but AI does not have to confine itself to methods that are biologically observable. “the birth of
the artificial intelligence conversation was denoted by Alan Turing's seminal work,
"Computing Machinery and Intelligence"
Human approach:
Systems that think like humans
Systems that act like humans
Ideal approach:
Systems that think rationally
Systems that act rationally
Alan Turing’s definition would have fallen under the category of “systems that act like
humans.”

Figure – 2 Relations between AI ML Deep Learning.


At its simplest form, artificial intelligence is a field, which combines computer science and
robust datasets, to enable problem-solving. It also encompasses sub-fields of machine learning
and deep learning, which are frequently mentioned in conjunction with artificial intelligence.
These disciplines are comprised of AI algorithms which seek to create expert systems which
make predictions or classifications based on input data.
Figure -3 Deep Neural Network

MACHINE LEARNING
Machine learning is a branch of artificial intelligence (AI) and computer science which focuses
on the use of data and algorithms to imitate the way that humans learn, gradually improving its
accuracy. Machine learning is an important component of the growing field of data science.
Through the use of statistical methods, algorithms are trained to make classifications or
predictions, uncovering key insights within data mining projects. These insights subsequently
drive decision making within applications and businesses, ideally impacting key growth
metrics. As big data continues to expand and grow, the market demand for data scientists will
increase, requiring them to assist in the identification of the most relevant business questions
and subsequently the data to answer them.
Why Machine Learning Matters
With the rise in big data, machine learning has become a key technique for solving problems
in areas, such as:
• Computational finance, for credit scoring and algorithmic trading
• Image processing and computer vision, for face recognition, motion detection, and
object detection
• Computational biology, for tumor detection, drug discovery, and DNA sequencing
• Energy production, for price and load forecasting
• Automotive, aerospace, and manufacturing, for predictive maintenance
• Natural language processing, for voice recognition applications

Figure -4 ML Model and works


When Should You Use Machine Learning?
Consider using machine learning when you have a complex task or problem involving a large
amount of data and lots of variables, but no existing formula or equation. For example, machine
learning is a good option if you need to handle situations like these:
• Hand-written rules and equations are too complex—as in face recognition and speech
recognition.
• The rules of a task are constantly changing—as in fraud detection from transaction
records.
• The nature of the data keeps changing, and the program needs to adapt—as in
automated trading, energy demand forecasting, and predicting shopping trends.

DEEP LEARNING
Deep learning is a machine learning technique that teaches computers to do what comes
naturally to humans: learn by example. Deep learning is a key technology behind driverless
cars, enabling them to recognize a stop sign, or to distinguish a pedestrian from a lamppost. It
is the key to voice control in consumer devices like phones, tablets, TVs, and hands-free
speakers. Deep learning is getting lots of attention lately and for good reason. It’s achieving
results that were not possible before. In deep learning, a computer model learns to perform
classification tasks directly from images, text, or sound. Deep learning models can achieve
state-of-the-art accuracy, sometimes exceeding human-level performance. Models are trained
by using a large set of labeled data and neural network architectures that contain many layers.
Why Deep Learning Matters
In a word, accuracy. Deep learning achieves recognition accuracy at higher levels than ever
before. This helps consumer electronics meet user expectations, and it is crucial for safety-
critical applications like driverless cars. Recent advances in deep learning have improved to
the point where deep learning outperforms humans in some tasks like classifying objects in
images. While deep learning was first theorized in the 1980s, there are two main reasons it has
only recently become useful:
• Deep learning requires large amounts of labeled data. For example, driverless car
development requires millions of images and thousands of hours of video.
• Deep learning requires substantial computing power. High-performance GPUs have a
parallel architecture that is efficient for deep learning. When combined with clusters or
cloud computing, this enables development teams to reduce training time for a deep
learning network from weeks to hours or less.
How it works
Most deep learning methods use neural network architectures, which is why deep learning
models are often referred to as deep neural networks. The term “deep” usually refers to the
number of hidden layers in the neural network. Traditional neural networks only contain 2-3
hidden layers, while deep networks can have as many as 150. Deep learning models are trained
by using large sets of labeled data and neural network architectures that learn features directly
from the data without the need for manual feature extraction. One of the most popular types of
deep neural networks is known as convolutional neural networks (CNN or ConvNet). A CNN
convolves learned features with input data, and uses 2D convolutional layers, making this
architecture well suited to processing 2D data, such as images.

CNNs eliminate the need for manual feature extraction, so you do not need to identify features
used to classify images. The CNN works by extracting features directly from images. The
relevant features are not pretrained; they are learned while the network trains on a collection
of images. This automated feature extraction makes deep learning models highly accurate for
computer vision tasks such as object classification.
Figure – 5 Example of a network with many convolutional layers. Filters are applied to each
training image at different resolutions, and the output of each convolved image serves as the
input to the next layer.
CNNs learn to detect different features of an image using tens or hundreds of hidden layers.
Every hidden layer increases the complexity of the learned image features. For example, the
first hidden layer could learn how to detect edges, and the last learns how to detect more
complex shapes specifically catered to the shape of the object we are trying to recognize.

ABOUT COURSERA
Coursera is Online Education Platform Which is used is wide range of different country and
top universities. Many Top universities give their instructor and courses here for free of cost
or some paid course. This also provide Distance Learning Courses like Undergraduate, Post
Graduates and Training Courses. Coursera Inc. is an American massive open online course
provider founded in 2012 by Stanford University computer science professors Andrew Ng and
Daphne Koller. Coursera works with universities and other organizations to offer online
courses, certifications, and degrees in a variety of subjects. According to CNBC "more than
150 universities offered upwards of 4,000 courses through Coursera, which features over two
dozen degree programs at prices that are lower than many in-person school offerings.
• Coursera offers products at a wide range of prices, from free-to-audit courses to
$30,000-degree programs.
• As of 2020, Coursera raised $464 million in multiple rounds of fundraising.
• Coursera went public on March 31, 2021, offering more than 15 million shares at $33
each.
• Coursera is partnered with over 200 universities, businesses, and nonprofits.
• Coursera plans to expand in Latin America, and most recently, partnered with
universities in Mexico, Colombia, and Argentina to expand its reach.
As of 2020, Coursera raised over $464 million, after injecting over $130 million in a Series F
round led by NEA. 2 It's also worth noting that on April 25, 2019, Coursera secured a $103
million investment in a round led by SEEK Group, an online employment marketplace and a
global leader in investing, scaling, and operating online employment and education businesses.
Other Coursera investors include Kleiner Perkins, Learn Capital, SuRo Capital Corp., and G
Squared. 2

Figure – 6 Logo Of Coursera


On March 31, 2021, Coursera issued 15. 73 million shares at $33 per share in its IPO. 3 The
offering raised more than $520 million, pushing the company's valuation to $4.3 billion.
The lectures for the majority of the courses Coursera offers are free. However, students who
wish to earn a certificate of completion can opt to pay a per-course fee to participate in the
"Signature Track."4 This feature, which Coursera launched in January 2013 and that became a
platform-wide norm in 2015, gives paying students access to graded assignments, homework,
and examinations. If completed satisfactorily, Signature Track students earn a verified
certificate at the end of the course, which is emblazoned with the name of the course and the
university that provided its content. Coursera will have to continue demonstrating high revenue
growth. New features and a quickly growing user base is one thing, but the ability to monetize
these things effectively is another.
Approximately 40% of paying students finish the courses they enroll in. Coursera needs to find
ways to boost this number because more completed courses means more additional courses
purchased. According to Dil Sidhu, the company’s Chief Content Officer, Coursera is planning
on employing more data analytics tools to study why students don’t complete courses and
adding behavioural sciences lessons to coach students to be more disciplined. During its 2019
partner's conference, several panellists also urged those offering courses to "break the fourth
wall" by adding more personal touches to lessons. By making online education a more accurate
simulation of classroom learning, it will become more engaging. To the same aim, speakers
spoke about the need for more interaction between teachers and students. This would mean that
universities would have to make more professors available to interface with online students.
Coursera is expanding its footprint in Latin America by partnering with Universidad Autónoma
Metropolitana (UAM) in Mexico, Universidad de Palermo (UP) in Argentina, and Universidad
Nacional de Colombia (UNAL) in Colombia, which offers Coursera's first Spanish-language
degree program: an online software engineering master's program.

With these additions, Coursera has 15 Latin American university and institution partners and
more than 530 courses available in Spanish. It also is exponentially increasing the number of
learners in this region. From 2019 to 2020 alone, it added more than 5 million learners.

DEEPLEARNING .AI

DeepLearning.AI is an education technology company that is empowering the global


workforce to build an AI-powered future through world-class education, hands-on training, and
a collaborative community.

• Gain world-class education to expand your technical knowledge


• Get hands-on training to acquire practical skills
• Learn from a collaborative community of peers and mentors

DeepLearning.AI has created high-quality AI programs on Coursera that have gained an


extensive global following. By providing a platform for education and fostering a tight-knit
community, DeepLearning.AI has become the pathway for anyone looking to build an AI
career.

SUMMARY OF THE PROJECT

I have done many projects in the topic of Convolution Neural Network Using CNN model,
TensorFlow and Machine Learning, This is not in Course But also for my Practice I have
completed the this project. My projet Name is A Realistic Image Formation Using CNN model.

Its Form the Realistic image.

EXPERIENCE AT COURSERA

I Using Coursera snice past two Years Ago 2019, from that online education platform I have
gained many more certificate around 10 certificates online Course Form Different Universities
like Rice University, Sandford University, Princeton University, Intel, etc.

Now for internship Courses also I have chosen Coursera course From Deep learning. Ai course
name is Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep
Learning. From this Platform I have made many more friends with different country and I have
reached different professor. In this there is a section Discussion Group which makes more
effectively to solve any problems and ask questions with any source. It is too reliable to used
you may directly post ask any questions related to topics and get efficient solutions quickly
There also facility of offline Professor and Mentor. From this Topic Of deep learning, I gained
many clearer concepts of AI, ML and Neural Network. I gained more knowledge about Google
Colab to use and more about tensor flow.

WEEKLY REPORT

WEEK – 1

A New Programming Paradigm

In First week there is soft introduction to what Machine Learning and Deep Learning are, and
how they offer a new programming paradigm, giving you a new set of tools to open previously
unexplored scenarios. All i need to know is some very basic programming skills, and I’ll pick
the rest up as you go along.
I’ll be working with code that works well across both TensorFlow 1.x and the TensorFlow 2.0
alpha. To get started, check out the first video, a conversation between Andrew and Laurence
that sets the theme for what Study.

I saw some details behind the concept and paradigms of machine learning. I saw how it was a
change from rules-based expression using code to getting data, labelling that data, and then
having a neural network figure out the patterns that bring about the rules. . I looked through a
very simple example that took some x and y values and figured out the relationship between
them. Okay, now you're going to get hands-on with writing this code for yourself. Now you
don't need a development environment to do it, and one way that you can use it is to use it right
in the browser with something called Google Collaboratory. If you're familiar with Jupyter
Notebooks in Python, you'll be right at home, and of course you can use Jupyter Notebooks
too. Otherwise, consider Colab to be an environment that runs in the browser that lets you run,
edit, and inspect your Python code. It's really cool for learning with. If you want more details
about it, check out this video on YouTube. Here is the Colab environment that I'm using with
the Notebook for this lesson loaded into it. I'll step through the lesson first, and then you can
go and try it out for yourself. You can run the code by clicking the play button in a code block.
Make sure you run each block in order or you might get some bugs. In this block, I am
importing and setting up TensorFlow, Keras, and NumPy. Next, I'll define the neural network
as we discussed. It's one layer, with one neuron, and one input value. Now I'm going to compile
the neural network using the loss function and the optimizer. Remember, these help the neural
network guess the pattern, measure how well or how badly the guess performed, before trying
again on the next epoch, and slowly getting more accurate. Here's where we give it the data,
where we have a known x and unknown corresponding y, and we want to figure out the
relationship between them. These are fed in using NumPy arrays.
Figure – 7 Machine Learning model works

Here's where we do the training and the machine learns the patterns. We're asking the model
to fit the x's to the y's and it will try for 500 epochs. Each epoch is where it makes a guess, uses
the loss function to figure out how well or how badly it did, and then use the optimizer to make
another guess. When it's run, keep an eye on the loss on the right-hand side. Remember, it
knows the correct answer for the values we've fed in, so it can compare it's guess against them.
When I start, my loss is quite high, i.e the guess wasn't that great. But epoch by epoch, you can
see the loss getting lower and lower. So the neural network is getting closer to spotting the
relationship. By the time 500 epochs have transpired, the loss is really, really small, meaning
that for this data, it has come really close to figuring out the relationship between x and y. So
let's see what happens if we give it an x that it hadn't previously seen.

Finally, I Scored the 100% in week 1 quiz. And pass the assignments

HOUSING PRICE ASSINGMENTS


I EXPLAINED ALL THE CODE AND PROGRAMMING ASSINGMENTS IN LAB WORK
EXPALNATION SECTION BELOW

WEEK 2

Introduction to Computer Vision

This week I learnedto take that to the next level by beginning to solve problems of computer
vision with just a few lines of code! And conversation between Laurence and Andrew where
they discuss it and introduce you to Computer Vision!

I saw a scenario for training a system to recognize fashion images. The data comes from a
dataset called Fashion MNIST, and I can learn more about it and explore it in GitHub. And see
how to load that data and prepare it for training.

Figure- 9 Code To train the data MINST


Figure 10 Using Call Back Function

Let's take a look at the code for callbacks, and see how it works. I saw the code here. Here's
the notebook with the code already written, and here's the class that we defined to handle the
callback, and here is where we instantiate the callback class itself. Finally, here's where we
set up the callback to be called as part of the training loop. As we begin training, note that we
asked it to train for five epochs. Now, keep an eye on the losses that trains. We want to break
when it goes below 0.4, and by the end of the first epoch we're actually getting close already.
As the second epoch begins, it has already dropped below 0.4, but the callback hasn't been hit
yet. That's because we set it up for on epoch end. It's good practice to do this, because with
some data and some algorithms, the loss may vary up and down during the epoch, because all
of the data hasn't yet been processed. So, I like to wait for the end to be sure. Now the epoch
has ended, and the loss is 0.3563, and we can see that the training ends, even though we've
only done two epochs.
I have Passed the week-2 Quiz Scoring 100% and Pass the Assignments.

HAND RECOGINATION ASSINGMENTS

WEEK – 3

Enhancing Vision with Convolutional Neural Networks

I saw a basic Neural Network for Computer Vision. It did the job nicely, but it was a little
naive in its approach. This week we’ll see how to make it better, as discussed by Laurence
and Andrew here.

Figure 11 Data POOLING


How to implement Convolution Layers

Let's explore how convolutions work by creating a basic convolution on a 2D Grey Scale
image. First we can load the image by taking the 'ascent' image from scipy. It's a nice, built-in
picture with lots of angles and lines.

In [0]:
import cv2
import numpy as np
from scipy import misc
i = misc.ascent()
Next, we can use the pyplot library to draw the image so we know what it looks like.

In [0]:
import matplotlib.pyplot as plt
plt.grid(False)
plt.gray()
plt.axis('off')
plt.imshow(i)
plt.show()
<Figure size 640x480 with 1 Axes>
The image is stored as a numpy array, so we can create the transformed image by just
copying that array. Let's also get the dimensions of the image so we can loop over it later.

In [0]:
i_transformed = np.copy(i)
size_x = i_transformed.shape[0]
size_y = i_transformed.shape[1]
Now we can create a filter as a 3x3 array.

In [0]:
# This filter detects edges nicely
# It creates a convolution that only passes through sharp edges and straight
# lines.

#Experiment with different values for fun effects.


#filter = [ [0, 1, 0], [1, -4, 1], [0, 1, 0]]

# A couple more filters to try for fun!


filter = [ [-1, -2, -1], [0, 0, 0], [1, 2, 1]]
#filter = [ [-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]

# If all the digits in the filter don't add up to 0 or 1, you


# should probably do a weight to get it to do so
# so, for example, if your weights are 1,1,1 1,2,1 1,1,1
# They add up to 10, so you would set a weight of .1 if you want to normalize them
weight = 1
Now let's create a convolution. We will iterate over the image, leaving a 1 pixel margin, and
multiply out each of the neighbors of the current pixel by the value defined in the filter.
i.e. the current pixel's neighbor above it and to the left will be multiplied by the top left item
in the filter etc. etc. We'll then multiply the result by the weight, and then ensure the result is
in the range 0-255

Finally we'll load the new value into the transformed image.

In [0]:
for x in range(1,size_x-1):
for y in range(1,size_y-1):
convolution = 0.0
convolution = convolution + (i[x - 1, y-1] * filter[0][0])
convolution = convolution + (i[x, y-1] * filter[0][1])
convolution = convolution + (i[x + 1, y-1] * filter[0][2])
convolution = convolution + (i[x-1, y] * filter[1][0])
convolution = convolution + (i[x, y] * filter[1][1])
convolution = convolution + (i[x+1, y] * filter[1][2])
convolution = convolution + (i[x-1, y+1] * filter[2][0])
convolution = convolution + (i[x, y+1] * filter[2][1])
convolution = convolution + (i[x+1, y+1] * filter[2][2])
convolution = convolution * weight
if(convolution<0):
convolution=0
if(convolution>255):
convolution=255
i_transformed[x, y] = convolution
Now we can plot the image to see the effect of the convolution!

In [0]:
# Plot the image. Note the size of the axes -- they are 512 by 512
plt.gray()
plt.grid(False)
plt.imshow(i_transformed)
#plt.axis('off')
plt.show()
This code will show a (2, 2) pooling. The idea here is to iterate over the image, and look at
the pixel and it's immediate neighbors to the right, beneath, and right-beneath. Take the
largest of them and load it into the new image. Thus the new image will be 1/4 the size of the
old -- with the dimensions on X and Y being halved by this process. You'll see that the
features get maintained despite this compression!

In [0]:
new_x = int(size_x/2)
new_y = int(size_y/2)
newImage = np.zeros((new_x, new_y))
for x in range(0, size_x, 2):
for y in range(0, size_y, 2):
pixels = []
pixels.append(i_transformed[x, y])
pixels.append(i_transformed[x+1, y])
pixels.append(i_transformed[x, y+1])
pixels.append(i_transformed[x+1, y+1])
newImage[int(x/2),int(y/2)] = max(pixels)
# Plot the image. Note the size of the axes -- now 256 pixels instead of 512
plt.gray()
plt.grid(False)
plt.imshow(newImage)
#plt.axis('off')
plt.show()

I have Completed the week 3 Quiz scoring 100% and Passed the lab Assignments.
WEEK – 4

Using Real-world Images

In this Last week I saw how to improve the results from deep neural network using
convolutions. It was a good start, but the data used was very basic. What happens when your
images are larger, or if the features aren’t always in the same place? Andrew and Laurence
discuss this to prepare for what i’ll learn this week: handling complex images.

This is how an Image Generator can flow images from a directory and perform operations
such as resizing them on the fly, the next thing to do is design the neural network to handle
these more complex images. i’ll see that in the next video.
Figure – 12 Define Cov Net to use Complex Network

Now that i’ve designed the neural network to classify Horses or Humans, the next step is to train
it from data that’s on the file system, which can be read by generators. To do this, i don’t use
model.fit as earlier, but a new method call: model.fit_generator
Figure 13 CovNet with Fit Generator

I have reached the end of course 1! I've come a long way from looking at the most basic of
neural networks to building a basic computer vision neural network that classified clothing. I
took this a little further by using Convolutions that spot features in an image, and then
classify and learn based on those features. In course 2, I'll go a little deeper into
Convolutions, learning how can go into depth with real-world images, and learn many of the
techniques used in challenges such as those run by Kaggle.

LAB WORK EXPLANATON

• CONVULATION NEURAL NETWORK


• DATA TRAIN POOLING
• MACHINE LEARNING
• TENSOR FLOW

Tensor Flow
import tensorflow as tf
import numpy as np
from tensorflow import keras

model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

model.compile(optimizer='sgd', loss='mean_squared_error')

xs = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 10.0], dtype=float)


ys = np.array([100.0, 150.0, 200.0, 250.0, 300.0, 350.0, 550.0], dtype=float)

model.fit(xs, ys, epochs=500)

print(model.predict([7.0]))

Output
import tensorflow as tf

class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('accuracy')>0.99):
print("\nReached 99% accuracy so cancelling training!")
self.model.stop_training = True

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()


x_train, x_test = x_train / 255.0, x_test / 255.0

callbacks = myCallback()

model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10, callbacks=[callbacks])

Output
import tensorflow as tf

# YOUR CODE STARTS HERE


class StopTrainingCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if (logs.get('acc') >= 0.998):
print('\nReached 99.8% accuracy so cancelling training!')
self.model.stop_training = True

mCallback = StopTrainingCallback()
# YOUR CODE ENDS HERE

mnist = tf.keras.datasets.mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()

# YOUR CODE STARTS HERE


training_images = training_images.reshape([60000, 28, 28, 1])
training_images = training_images / 255.0;
test_images = test_images.reshape([10000, 28, 28, 1])
test_images = test_images / 255.0;
# YOUR CODE ENDS HERE

model = tf.keras.models.Sequential([
# YOUR CODE STARTS HERE
tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
# YOUR CODE ENDS HERE
])
# YOUR CODE STARTS HERE
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.summary()

model.fit(training_images, training_labels, epochs=20, callbacks=[mCallback])


test_loss = model.evaluate(test_images, test_labels)

Output
import tensorflow as tf
import os
import zipfile

DESIRED_ACCURACY = 0.999

!wget --no-check-certificate \
"https://storage.googleapis.com/laurencemoroney-blog.appspot.com/happy-or-sad.zip" \
-O "/tmp/happy-or-sad.zip"

zip_ref = zipfile.ZipFile("/tmp/happy-or-sad.zip", 'r')


zip_ref.extractall("/tmp/h-or-s")
zip_ref.close()

class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if (logs.get('acc') > DESIRED_ACCURACY):
print('\nDesired Accuracy is met, Stopping training...')
self.model.stop_training = True

callbacks = myCallback()

Output
# This Code Block should Define and Compile the Model
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])

from tensorflow.keras.optimizers import RMSprop

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc'])

Output
# This code block should call model.fit_generator and train for
# a number of epochs.
history = model.fit_generator(
train_generator,
steps_per_epoch=1,
epochs=30,
verbose=1,
callbacks=[callbacks])

# Expected output: "Reached 99.9% accuracy so cancelling training!""


Output
CONCLUSION

I have gained the Knowledge of Artificial Intelligence, Machine Learning, Deep Learning. I know now
how to use the Tensor Flow, Cov Net, Data Train, POOLING, Image Generator etc.
The people still can’t imagine about the future world. how the world universe is transforming
the according to the nature as same like the computer or digital world is also transforming it by
Artificial Intelligence and Deep Learning. As Neural Network and CNN Model CovNet etc.
are major part of this subject. That makes the more reliable use in the Real world. The Machine
Learning course and Deep Learning Specialization from Andrew Ng teach the most important
and foundational principles of Machine Learning and Deep Learning. This new deeplearning.ai
TensorFlow Specialization teaches you how to use TensorFlow to implement those principles
so that you can start building and applying scalable models to real-world problems. To develop
a deeper understanding of how neural networks work, as it recommends that you take the Deep
Learning
REFRENCE

https://www.coursera.org/learn/introduction-tensorflow?#syllabus
https://www.coursera.org/account/accomplishments/verify/QM2Y3GRG3VDV
https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/Exercises/Exercise%20
1%20-%20House%20Prices/Exercise_1_House_Prices_Question.ipynb

You might also like