Python Machine Learn
Python Machine Learn
@&} : ‘
7 hime,
, i & t
* \
>oY »
Al SCIENCES
Jonathan Adam
Digitized by the Internet Archive
in 2022 with funding from
Kahle/Austin Foundation
[Link]
PYTHON MACHINE LEARNING
FROM SCRATCH
Machine Learning Concepts and
Applications for Beginners
Jonathan Adam
Alo Gi 5
How to contact us
contact([Link]
eel
L
AL SCIENCES
Table of Contents
Pla WerOl CONS once
es cassette
oeyiasiucttes eoesece sesseste: ill
Prom Al Sciences PubMsher, ss. .[Link]« ROCCE EEE 3
DEC
LA CCiiss censesagstvesscooss (ooasescinderdesPiet onss5streaesessasse sans. canys 5
he Bias-Vatiance Utade-Ott.-[Link] 24
11
Common Python Syntax........cccccccccccesssessstcensceceecessersenensneneeneeaeses 31
Example of [Link]
ossesugstanessv atvchcerrassave/uni esse 12
IV
Python Deep Learning Frameworks ...............:cccssscssseecsenencessnees 87
Case Studies with Real Data .......... Sreestea tretee cea eeseees ee LUO
Beatle CHER VOCCIIN Ge no ccscensnnessaspacesonsessepeeesseanroreannetsrssasuccncts 105
Conclusion............... Batitea
iene sesemeaeee TheAwoseueoe saassetee ea 119
DVALASCUSherrece seus ca cones tecees Sees evssseenccoanes cveustecedecatcesavess sess vresasceee’ 121
ISBN-13: 978-1725929982
ISBN-10: 1725929988 ‘
You cannot amend, distribute, sell, use, quote or paraphrase any part
ot the content within this book without the consent of the author.
Disclaimer Notice:
ene.
Learning
Fundamentals
= oe
With Python —
AN INTRODUC TION FOR BEGINNERS : i STEP IBY oFE 2 flu EWI
Wi HERERAS AN DPYTORGH:
ORC
AI SCIENCES
eG
RUS@IPINGCES
BOOKS
At [Link] , you can also read a collection of free
books and received exclusive free eBooks.
Preface
“Some people call this artificial intelligence, but the reality is this technology will enhance us. So
instead ofartifical intelligence, I think we'll augment our intelligence.”
Ginmt Rometty
Book Objectives
Target Users
You can download the source code for the project and
other free books at:
http: / /[Link]/code
Your Free Gift
Alain Kaufmann
http: / /[Link]/free-books
Finally, after going through the contents in this book and the
accompanying examples, you would be well suited to tackle
problems which pique your interests using machine learning
and deep learning models.
For many using machine learning for day to day tasks, Python
is the programming language of choice. They are many reasons
for this bias towards Python. Let’s have a look at some of
them:
10
no longer be a black box and you can peel behind the curtain
to have a look when things don’t work as expected.
1]
Machine Learning
What is Machine Learning?
12
“a
spoken in natural language, mobile keyboards predict the next
word a user is typing based on previous words, email clients
offer a smart reply feature whereby the content of an email is
scanned and appropriate responses are generated, e-commerce
applications offer recommendation to users based on previous
purchases and spending habits etc. Nearly every industry
would be impacted by machine learning as most processes can
be automated given that there is enough training data available.
Machine learning algorithms mostly excel in tasks where there
is a clear relationship between a set of inputs and outputs
which can be modelled by training data. Although machine
learning is a rapidly improving field, there is as of now no
notion of general intelligence of the form displayed by humans.
This is because models trained on one task cannot generalize
the knowledge gleaned to perform another task, that 1s
machine learning algorithms learn narrow verticals of tasks.
13
It would be remembered that we defined machine learning as
making algorithms that learn from data (examples) without
being explicitly programmed. The main intuition to understand
when dealing with supervised learning algorithms is that, they
learn through the use of examples that are clearly annotated to
show them what they are supposed to learn. The algorithms
therefore try to find a mapping representation from inputs to
outputs using the labels as a guide. “Supervised” in the name
of these types of algorithms, point to the fact that the labels or
targets provide supervision throughout the learning process. It
is therefore possible for the algorithm to check its prediction
against actual values stored in the labels. It then uses this error
information (how far off its prediction was from the actual
label) to slowly improve its performance with each iteration.
The targets in a supervised learning problem can be seen as a
supervisor providing feedback to the algorithm on areas where
it can improve its performance. The two main applications of
supervised learning algorithms are classification and
regression.
14
not spam. Depending on what is predicted, appropriate action
could be taken such as shifting spam emails to a spam folder
while relevant emails are sent to a user’s inbox.
15
supervisor in the training loop in form of labels. Unsupervised
learning algorithms are free to explore the underlying data
distribution and come up with patterns that best describe the
entire dataset. The training process is not guided by humans
through labelled examples and as such unsupervised learning
algorithms ate more powerful as they can discover patterns
which domain experts may not have thought of. It is however
still the job of domain experts to understand the patterns so
discovered and explain them because unsupervised learning
algorithms do not truly have the sense of reasoning which we
would ascribe to humans. Unsupervised learning algorithms
merely use the data distribution or its latent (hidden)
representations to unearth insights which may be in the form
clusters, groups or distributions.
16
interests, leading to greater engagement on the platform and
increased revenues.
lig
Semi-supervised learning algorithms are a special case of
supervised learning algorithms. In semi-supervised learning,
while there isn’t an explicit label, there exist an implicit
heuristic which serves as a supervisor in the training loop.
Semi-supervised models do not contain any external source of
labels but only rely on input features. However, the learning
task is set up in such a way that supervision still takes place in
the form of extraction of pseudo-labels from inputs through a
heuristic algorithm. A popular example of semi-supetvised
learning algorithms are autoencoders. Let us look at an
example to expand our understanding.
|
Latent Space |
Representation fou |
|
|
nS)
Observation
Reward Action
Agent
20
perform on new data which it has not seen, that is data it was
not trained on. In other words, how well can a model
generalize the patterns it learnt on the training set to suit real
world examples, so that it can achieve similar or better
performance. This is the crux of learning. A model should be
able to actually learn useful representations from data that
improves test time performance and not merely memorize
features as memorization is not learning.
21
| ta
x - I
XO 0 Xo Oo X0X' 0
iy XO ly: O ~
es Ax 0 Xx 0
| Xoy | anes oe | LX
asm ei. arenecd 7 Rane » a e
eu)
optimized its performance only for the training set. The trick
is to always choose the simplest model that achieves the
greatest performance.
Correctness
pa8
the instances in the actual class (ground truth) while the
columns represents predictions. The order may be reversed in
some cases. It 1s called a confusion matrix because it makes it
easy to see which classes the model is misclassifying for
another, that is which classes confuse the model.
Predicted class
P N
True False
P | Positives Negatives
(TP) (FN)
Actual
Class
False True
N Positives Negatives
(FP) (TN)
24
makes assumptions which are not correlated by the data. This
lead to errors because predictions are usually some way off
from actuals. Variance on the other hand is how susceptible a
model is to noise in the training data. How widely does the
performance on the model vary based on the data it 1s
evaluated on. A good machine learning algorithm should strive
to achieve low bias and low variance. Bias and variance are
related to overfitting and underfitting earlier encountered. A
model with high bias is underfitting the training data because
it has made simplistic assumptions instead of learning from
information available. Similarly, a model with high variance 1s
overfitting, because it has modelled noise and ‘as a result, its
performance would vary widely across the training set,
validation set and test set.
pas
Low Variance High Variance
Low
Bias
Bias
High
The top left image represents a model that has low bias and
low variance. This is the ideal model as it has learnt to hit the
target (produce correct classification) and usually hits the target
most of the time (does not vary with each throw). The image
at the top right shows a model that exhibits high variance and
low bias. Even if it does not make a lot of assumptions, its
ptedictions are spread all over the board which means its
performance varies widely (high variance). The image on the
bottom left depicts a model with high bias and low variance.
The shots are not all over the board but in a specific location.
This location is however far from the target meaning the model
is biased because of simplistic assumptions. Finally, the image
on the bottom right shows a model with high bias and high
variance. The shots on the board vary widely and are far away
26
from the target. This is the worst kind of model as it hasn’t
learnt any useful representation.
27
operations from fraud detection to speech recognition to
recommender systems. It is embedded in products we use
every day. When you buy a product from Amazon and you are
given a list of suggestions of other products that go with it,
that’s machine learning in action. When you open your mailbox
and emails are automatically classified into folders based on
their similarity, those are machine learning models doing the
work behind the scenes. Even when you use your credit card
online and your transaction is successful, a machine learning
model approved your transaction as being normal and not
fraudulent.
It wasn’t always the case that machine learning was the darling
of the computer science community, however in recent years
three factors have conspired to give it an exalted place.
29
production workflows as there is usually no need to switch to
another programming language. In this way, one language can
be used for the entire stack, from prototyping to deployment.
It should be noted however, that this generally depends on the
type of application and Python especially for scientific
computing usually reference lower level extensions in faster
programming languages like C or C++. Python can be seen as
the ideal interface to work across a slew of tasks effectively and
efficiently.
30
download page ( ‘ [Link]/downloads) and
following the installation instructions.
31
4 white spaces. Let us honour traditions and start with a simple
Hello world! example in Python.
a= 3
=) 4
c=at+b
a = 200
b = 33
elif a ==
else:
a is greater than b
=f
by the evaluation of the conditional in line with the declared
variables contained therein.
for x in range(2):
primes)
34
A function is defined using the special keyword def. A function
may accept arguments or return a value. To call a function
(execute it), we type the function name followed by a
parenthesis containing parameters if the function expects
arguments, else we call it with empty parentheses.
my function ('Earth!")
Hello Earth!
A multi-line
comment in Python
Ua
print('Comments in Python!')
35
Python Data Structures
print(my list)
my tuple = (1, 2, 3, 4)
print
(my tuple)
(2, oy oo
sclass: "tuple‘>
print
(my set)
print
(type (my _set) )
{'three', 1, 2}
<class ‘set'>
37
In the example above, notice that all duplicate entries are
removed when the set is created and there is no concept of
ordering.
print(my dict)
le heme ee Se es}
<class ‘dict'>
There are other data types in Python but these are by far the
most commonly used ones. To understand more about these
data structures and which operations that can be performed on
them, read through the official Python documentation.
38
of Python in data science and in the larger scientific community
is because Python is a well designed language and is useful
across several tasks, so users do not need to learn a new
programming language when confronted with a new task but
can tather leverage Python’s rich ecosystem of libraries to
perform their tasks. Python 1s also easy to pick up so users can
learn to extend libraries to support the functionality that they
desire. This forms a virtuous cycle as libraries become more
mature and support a wider range of adopters.
4]
Introduction to Labels and Features
The labels are regarded as the ground truth, the actual outcome
that was observed from a particular data point.
Features
42
features that ate informative in order to arrive at a final
prediction.
43
Boston suburbs given information about such houses in the
form of features.
Import Libraries:
import numpy as np
import pandas as pd
Let’s load the data by using the read_csv method on the Pandas
library and passing it the location of our data.
44
dataset = pd.read_csv('[Link]')
[Link]
(5)
Unnamed:0 crim zn indus chas nox rm age dis rad tax ptratio black Istat medv
0 1 0.00632 180 231 0 0.538 6575 652 4.0900 1 296 3 396.90 498 240
1 2 0.02731 0.0 7.07 0 0.469 6421 78.9 4.9671 2 242 178 306.90 914 216
2 3 0.02729 00 7.07 0 0.469 7.185 611 4.9671 2 242 178 30283 403 347
3 4 0.03237 0.0 218 0 0458 6.998 458 6.0622 3 222 187 304.63 294 334
4 5 0.06905 0.0 218 O 0.458 7.147 54.2 60622 3 222 187 396.90 533 362
Next we run
dataset. shape
45
[Link](['Unnamed: 0', 'medv'], axis=1)
dataset[ 'medv' ]
We would need to split our dataset into train and test splits as
we want to train our model on the train split, then evaluate its
performance on the test split.
regressor = LinearRegression()
46
The above code imports the linear regression model and
instantiates an object from it.
[Link](x_train,y
train)
This line of code fits the data using the fit method. What that
means is that it finds appropriate values for the independent
parameters that explains the data.
y_pred = [Link]
(x test,y test)
47
[Link]("Prices: $Y_i$")
‘Predicted
prices:
Prices:Y;
We can see from the scatter plot above that predictions from
our model are close to the actual house prices hence the
concentration of points.
48
Classification
49
x2 2
eaoe Surviving
2 companies
s o
& Fe Fs) x
& o z
re) x *
eo 9 86 o b
e o a x
x
_ « so «6 a : es
s
20 é ‘ x
¥ x
& o ‘ ‘ . -
2 a. = Ez * x
x x x
Failing ca x = x
companies x x
®
From the plot above we can see that there are two features that
describe the data X;and X2. What a classification task seeks to
do is divide the data into distinct categories such that there is a
decision boundary that best separates classes. In this example
we have two classes - falling companies and surviving
companies, a data point which represents a company can only
belong to one of those categories, falling or surviving. It is as a
result clear that this is a binary classification example because
there are only two classes.
Another point to note from the diagram is that the classes are
linearly separable, that is they can be separated by a straight
line. In other problems, this might not be possible and there
are more robust machine learning algorithms that handle such
instances.
Multi-Class Classification
50
It is important that we have a good understanding of
classification based on the number of classes that we want to
predict as classification has many real world applications. ‘To
further improve out intuition let us analyse the image below:
OM
metric for classification tasks but bear in mind that there are
other metrics such as precision and recall that we may wish to
explore based on how we intend to model our learning task.
D2
a ne
Training instance | Se
a | pees Class 1}
a ia a — i
Distance N\ Ke} |
Class 2)
ata. - iL.
|
\
®
New example
to classify Zo
54
d,(P.q) =» IP,—q,l
|
[Spa
dj([Link]= I> (9g; —P,))?
\ i=]
.\
|
| 5074
39
\\ ——
bse, ar a
\
|
| \ -
\ ———
| |
hel geen au
| |
}
|
-— =
0 10 20 30 40 50 60
K- Value
The optimal value for k is the point where the validation error
is lowest.
// [Link]/uciml/pima-indians-diabetes-
database/data
56
Since we ate dealing with two mutually exclusive classes, a
patient either has diabetes or not, this can be modelled as a
binary classification task and for the purpose of our example
we would use the k-nearest neighbor classifier for
classification.
import numpy as np
import pandas as pd
dataset = pd.read_csv('[Link]')
[Link]
(5)
1 1 85 66 29 0 266 0.351 31 0
3 1 89 66 23 94 28.1 0.167 21 0
a7
‘To know the number of observations in the dataset we run
dataset. shape
dataset. describe()
count —768.000000 768.000000 768,000000 768,000000 768,000000 768,000000 768,000000 768,000000 768.000000
mean 3.845052 120,894531 69.105469 20.536458 79.799479 31.992578 0.471876 33,240885 0.348958
std 3.369578 31.972618 19.355807 15,952218 115.244002 7.884160 0.331329 14.760232 0.476951
min 0.000000 0,000000 0,000000 0.000000 0.000000 0.000000 0.078000 21,000000 0,000000
25% 1.000000 99.000000 62,000000 0,000000 0.000000 27.300000 0.243750 24.000000 0,000000
50% 3.000000 117.000000 72,000000 23,000000 30.500000 32000000 0.372500 29.000000 0.000000
75% 6,000000 140.250000 80,000000 32,000000 127.250000 36,800000 0.626250 41,000000 1.000000
max —17,000000 199.000000 122.000000 99,000000 846,000000 67.100000 2.420000 81.000000 1.000000
58
Before going ahead with classification, we check for
correlation amongst our features so that we do not have any
redundant features
[Link] (range(len([Link])),
[Link]) # draw x tick marks
[Link] (range(len([Link])),
[Link]) # draw y tick marks
Pregnancies
Glucose
BloodPressur €
SkinTivekness
Insulin
DiabetesPedigreeFunction
Outcome
oS
The plot does not indicate any 1 to 1 correlation between
features, so all features are informative and _ provide
discriminability.
labels = dataset['Outcome']
We would once again split our dataset into training set and test
set as we want to train our model on the train split, then
evaluate its performance on the test split.
60
classifier = KNeighborsClassifier()
We fit the classifier using the features and labels from the
training set. To get predictions from the trained model we use
the predict method on the classifier, passing in features from
the test set.
6]
Hete is the code in full:
# import libraries
import numpy as np
import pandas as pd
dataset = pd.read_csv('[Link]')
[Link]
(5)
dataset. shape
[Link]
(range (len([Link])),
[Link]) # draw x tick marks
labels = dataset['Outcome']
classifier = KNeighborsClassifier()
# fit, data
[Link](features
train, labels train)
64
Support Vectors
ene
el =
Margin
Width
x,
# import libraries
import numpy as np
import pandas as pd
labels = dataset['Outcome'"]
66
# import support vector machine classifier
classifier = SVC()
# fit data
[Link](features train, labels train)
classifier = SVC(kernel='linear')
67
sate So ori
eet<a < n
IA te sn |
i a= are 2 em ie,
wool s Ae «4 aii
Shh NS Jae | :
i ane .
ating Dine 6% Kral : a ak “i
ee py ore ge (Ln) et ‘ ;
PI neue emt?dy sh at
SO et eee ae
a teen eis)iteoa) rue of ie 2 rep ae" »
teary —S
eee all me at 7 ; =) 6s _
Nae loa ie WT ie
Bialik
@8 y= .
| nnlindpgenes. G4 Camm
rare tewn) eohiclau@ & & m4
ai - Qe ® : °
aia sth
igs abaea wil wil) ce atyens
591662) &®
aaphlh
dw
ine
7
i A Rete,
Bie Ot Gp hel secs a) 106 PDWer
Fed yetites ‘ae os
EPOiO=
‘ ==
a y
———
as
f= » :
Clustering
Clustering is the most common form of unsupervised learning.
Clustering involves grouping objects or entities into clusters
(groups) based on a similarity metric. What clustering
algorithms aim to achieve is to make all members of a group
as similar as possible but make the cluster dissimilar to other
clusters. At first glance clustering looks a lot like classification
since we ate putting data points into categories, while that may
be the case, the main difference is that in clustering we are
creating categories without the help of a human teacher.
Whereas, in classification, objects were assigned to categories
based on the domain knowledge of a human expert. That is in
classification we had human labelled examples which means
the labels acted as a supervisor teaching the algorithm how to
recognise various categories.
69
cluster, that is the data point is represented across the
distribution of clusters using a probability estimate that assigns
how likely the point belongs to one cluster or the other.
4} " ae 7
| % v %. |
j Ya g ®
©7ob &3 |
2| c ¢ ® Way °
| ie), i
; CE Ty |
j
@eco ®
My ee e, @ 6
4 wo @ % 6 % @ & |
‘ £ & ne oe
| ae) we 3 25, “he 2 |
r- ee
-4|i Fe £ @ se
Che
~§ 4 =~? 0 2 4 6
70
Introduction to Clustering
71
Flat clustering algorithms are intuitive to understand and
feature linear complexity, therefore the time taken to run the
algorithm increases linearly with the number of data points and
because of this flat clustering algorithms scale well to massive
amounts of data. As a rule of thumb, flat clustering algorithms
are generally used for large datasets where a distance metric can
capture similarity while hierarchical algorithms are used for
smaller datasets.
Example of Clustering
(e)
[Link] /itiscsv downloads
[Link]/1
The first step is to load the data and run the head method on
the dataset to know our features
# import libraries
import numpy as np
import pandas as pd
dataset = pd.read_csv('[Link]')
dataset.
head (5)
G 1 wt a5 14 0.2 Iris-setosa
73
xe [Link](['Id', 'Species'], axis=1)
The above line of code selects all our features into x dropping
Id and Species.
kmeans.
fit (x)
[Link] (kmeans.inertia_)
74
# plotting the results onto a line graph,
allowing us to observe 'The elbow'
[Link]('Number of clusters')
plt. show ()
§ Sa
SB
Squares
of
Sum
Cluster
Within
Number of clusters
Ip
Now that we know that the optimal value for k is 3, we create
a K-means object using Scikit-Learn and set the parameter of
n_clusters (number of clusters to generate) to 3.
[Link](x[y
kmeans == 1, 0], x[y_kmeans ==
ie, so= L007 cl= 'tblue!l, label — Virus
versicolour')
76
[Link](kmeans.cluster_centers [:, Oy
[Link] ster
centers [:,1], s = 100, c=
'yellow', label = 'Centroids')
[Link]()
@ Iris-setosa
o ¢ @ lris-versicolour
@ Iris-virginica
Centroids —
al
clusters - 3, which is equal to the number of classes in our
dataset.
78
agi <haph “0
. ae a ae © 1) Coke
om eles os of T : yee oe [Link]>
nits Meno Od ais peta --6
els Thalia at « avon eel
7
oo ee ee
Aapeall jr@peeeses OY ;
yt
-
wit i ONS ae
Ky ee af A
©
& : :
®
- : oe @ i
; - i ae SIG altaT 7
aq , a on -s
80
To get a well-grounded understanding, it is important for us to
take a step back and try to understand the concept of a single
neuron.
oy ineNeuron
dendrites
pes i } ¢—
\b=)
Ye a S24 synapses
nucleus —8 aeons ae
81
think of an artificial neuron firing a signal only when some
condition has been met by its internal calculations. Finally, this
network of neurons learn representations in such a way that
connections between them are either strengthened or
weakened depending on the current task at hand. The
connections between biological neurons are called synapses
and we would see an analogy of synapses in artificial neural
networks known as weights which ate parameters we would
train to undertake a learning problem.
Xi
Threshold
Summer unit
eh OUTUE
82
a feature. That is lower values for the weight means that the
connected feature is not as important and higher values signify
greater significance. All inputs to the artificial neural network
are then summed linearly (added side by side). It is at this point
that we determine whether to a send signal to the next neuron
or not using a condition as a threshold. If the result of the
linear calculation is greater than or equal to the threshold value,
we send a signal else we don’t.
83
Input Layer Hidden Layer Output Layer
Variable - #1 ©
\ : | i “
Variable - #2 ss A
Po Pasar
fo
ony
oN
we, JK — } Output
Gal bad
Variable - #3
we
ay, : ey
Variable - #4 ‘i
ee
An example of a Feed-forward Neural Network with one hidden layer (with 3 neurons )
84
weights. Finally, the above network is said to be a 2-layer neural
network as the input layer is not counted when describing the
number of layers contained in a network.
85
approximation theorem, deep neural networks seem to
improve their performance with more data. They are free from
the plateau effect that traditional machine learning algorithms
suffer from, whereby at some point the performance of the
algorithm does not improve with the availability of additional
data.
Deep learning
®
)&
©
=
Se
fe)
=
a
oO
Amount of data
86
Deep learning has been applied to solve many problems which
have real world applications and are now being transitioned
into commercial products. In the field of computer vision,
deep learning techniques are used for automatic colorization to
transform old black and white photos, automatic tagging of
friends in photos as seen in social networks and grouping of
photos based on content into folders.
87
would see how to install TensorFlow and use it to perform
deep learning tasks through a hands on example.
Install TensorFlow
88
$ pip -V
or
$ pip3 -V
$ pip -V
ot
$ pip3 -V
89
This depends on the version of Python you have, pip for
version 2.7 and p1p3 for version 3.x
90
using placeholders which register on the computation
graph but the values are actually supplied later.
Creation of Session: After we have described the
computation graph and initialised variables, the next
step is to create a session within which the
computation graph would be executed.
Running of Graph in Session: The complete graph
along with values for placeholders is passed to the
session for execution. This is when the mathematical
operations defined in the graph takes place.
Close Session: When the graph, and related
computations have finished executing, we need to
shutdown or end the session.
gem ( + dl
)
~~ 9%. Operation
AX y aay
Variable Constant
9]
The diagram above shows a simple computation graph for a
function. Using TensorFlow we would describe something
similar that defines a neural network in the next chapter.
How to run the Neural Network using
TensorFlow
For our hands on example, we would do image classification
using the MNIST handwritten digits database which contains
pictures of handwritten digits ranging from 0 to 9 in black and
white. The task is to train a neural network that given an input
digit image, it can predict the class of the number contained
therein.
Let’s go ahead and load the data from TensorFlow along with
importing other relevant libraries.
import numpy as np
import tensorflow as tf
import [Link] as plt
[Link]([Link]([Link][8],
[28, 28]), cmap='gray')
[Link]()
0 5 10 uke 20 BJAt
94
# Parameters
learning rate = 0.1
# Network Parameters
n_hidden 1 = 10 # 1st layer number of neurons
# tf Graph input
Vigil, Us
tf£.Variable(tf.random_normal([num_input,
n hidden 1])),
25
ig Wea &
tf. Variable (tf. random_normal([n_hidden
1,
n_ hidden 2])),
ayia! ¢
tf£.Variable
(tf. random_normal([n_hidden 2,
num_classes]) )
f
biases = {
veal Uae
[Link]
(tf. random_normal([n_hidden_1])),
Np Zi:
tf. Variable(tf. random_normal([n_hidden
2])),
VOUle
[Link]
(tf. random_normal([num_classes]) )
# Create model
layer 2 = tf£[Link]([Link]
(layer 1,
weights['h2']), biases['b2'])
96
# Output fully connected layer with a neuron
for each class
Next we call our function, define the loss objective, choose the
optimizer
that would be used to train the model andinitialise
allvariables.
# Construct model ’
logits = neural
_net (X)
Loss op =
[Link] mean([Link].softmax_cross_
entropy with_
logits (
logits=logits, labels=yY) )
optimizer =
tf£.[Link]
(learning rate=learning ra
te)
oT
init = tf£.global_ variables initializer ()
Finally,
we create a session, supply images in batches to the
model for training and print the loss and accuracy for each
mini-batch.
# Start training
with [Link]() as sess:
[Link] (init)
batchx, batch y =
[Link]
batch (batch_ size)
¥: batch y})
98
print ("Optimization Finished!")
print("Testing Accuracy:", \
[Link](accuracy, feed dict={xX:
[Link],
me
[Link]}))
The loss drops to 0.4863 after training for 500 steps and we
achieve an accuracy of 85% on the test set.
# Parameters
num_steps = 500
batch_size = 128
99
display step = 100
# Network Parameters .
# t£ Graph input
X = tf£.placeholder("float", [None, num_input])
weights = {
Weil ys
[Link](tf.random_normal([num_input,
n_ hidden 1])),
Uigia 2
tf£.Variable(tf.random_normal([n_hidden_l,
n_ hidden 2])),
VOU is
[Link](tf.random_normal([n_hidden_ 2,
num_classes]) )
}
biases = {
onlUl
[Link](tf.random_normal([n_hidden_1])),
ep c
[Link](tf.random_normal([n_hidden_2])),
100
Vertes:
[Link](tf.random_normal ([num_classes]) )
# Create model
layer 2 = tf£.add(tf£.matmul
(layer 1,
weights['h2']), biases['b2'])
# Construct model
logits = neural
_net(X)
logits=logits, labels=yY) )
optimizer =
tf£.[Link] (learning rate=learning ra
te)
101
# Evaluate model (with test logits, for dropout
to be disabled)
accuracy = tf.reduce_mean([Link](correct
pred,
iene oveleyewesy™))))
# Start training
with [Link]() as sess:
[Link](init)
batchx, batch_y =
[Link] batch (batch size)
[Link](train_
op, feed dict={xX:
batchx, Y: batch_y})
Y: batch_y})
102
print("Step " + str(step) + ",
Minibatch Loss= " + \
WA cent pa oremeita (LOSS) marten or
Training Accuracy= " + \
"{:.3£}". format (acc))
NEE
[Link]}) )
103
104
Case Studies with Real Data
In this chapter we would work with data that can be used for
real world applications. Two case studies would be performed,
the first involves predicting customer churn which means how
likely is a customer to stop patronage to a business and switch
to its competitor. The second study would involve automatic
sentence classification which can be used by reviews sites to
detect users sentiments based on their review.
105
Here we are presented with a case whereby a bank wants to use
data collected from its customers over several years to predict
which customers are likely to stop using the bank’s services by
switching to a competing bank. The rewards of such an analysis
to the bank is profound as it can target dissatisfied customers
with incentives which would reduce the churn ratio helping the
bank to grow its customer base and solidify its position.
import pandas as pd
import tensorflow as tf
import tflearn
106
# load the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
[Link]()
imber Customerld Sumame CreditScore Geography Gender Age Tenure Balance NumOfProducts HasCrCard IsActiveMember EstimatedSalary Exited
X = [Link][:, 3:13].values
y = [Link][:, 13].values
107
Since we have categorical features 1n the dataset (Geography and
Gender), we have to convert them into a form that a deep
learning algorithm can process. We do that using a one-hot
representation. One-hot representation creates a sparse matrix
with zeros in all positions and a | at the position representing
the category under evaluation. We use Scikit-Learn’s
pteprocessing model to first create a label encoder, then create
a one-hot representation from it.
labelencoder
X 1 = LabelEncoder
()
x[:, 1] = labelencoder
x [Link] transform(xX[:,
tj)
labelencoder
X 2 = LabelEncoder()
X[:, 2] = labelencoder
X 2.fit_transform(X[:,
2])
onehotencoder =
OneHotEncoder (categorical features = [1])
X = [Link]
transform (X) . toarray ()
eX sy ee]
We split our data into training and test set. One would be used
to train the model while the other would be use to test
performance.
108
X_ train, X_test, y_ train, y_test
train_test_split(X, y, test_size = ORrz a
random state = 0)
# feature scaling
sc = Standardscaler()
X_test = [Link](X
test)
activation='relu')
activation='relu')
activation='tanh')
109
net = [Link]
(net)
# define model
show_metric=True,
run_id="dense model")
We train the model for 10 epochs with a batch size of 16. The
model achieves an accuracy of 0.7885 on the test set which we
used to validate the performance of the model.
Sentiment Analysis
For this real world use case we tackle a problem from the field
of Natural Language Processing (NLP). The task is to classify
movie reviews into classes expressing positive sentiment about
a movie or negative sentiment. ‘l’o perform a task like this, the
model must be able to understand natural language, that 1s it
110
must know the meaning of an entire sentence as expressed by
its class prediction. Recurrent Neural Networks (RNNs) are
usually well suited for tasks involving sequential data like
sentences however, we would apply a _ 1-dimensional
Convolutional Neural Network (CNN) model to this task as it
is easier to train and produces comparable results.
import tensorflow as tf
import tflearn
from [Link]
ops import merge
The next step is to actually load the dataset into the train and
test splits
dd
# load IMDB dataset
valid _portion=0.1)
# data preprocessing
# sequence padding
trainX = pad_sequences(trainX, maxlen=100,
value=0.)
network = [Link]
dims (network, 2)
import tensorflow as tf
import tflearn
from [Link]
ops import merge
114
train, test; — = imdb.load_data(path='[Link]',
n_words=10000,
valid portion=0.1)
# data preprocessing
# sequence padding
trainX = pad_ sequences (trainx, maxlen=100,
value=0.) :
# converting labels
to binary vectors
A
network = tf£.expand_ dims (network, 2)
# training
model = [Link] (network,
tensorboard_ verbose=0)
116
ie Gee wae,
ipev-ine l fsa Oe | imate
Sy eh aied) paquae ©
$s Lei YSine 4
is cer Cam! Was.
oa | fa rd nf pankeegesel’ “anes.
ae 7 : = 7
—SHeatwy Pipseiuhoet.
: iy a? es mr Ot? tween
Conclusion
Dip
Thank you!
Thank you for buying this book! It is intended to help you
understanding machine learning using Python. If you enjoyed
this book and felt that it added value to your life, we ask that
you please take the time to review It.
a
a
AL SCIENCES
We are a very small publishing company and our
sutvival depends on your reviews.
Please, take a minute to write us your review.
120
Sources & References
Software, libraries, & programming language
Python (https:
Anaconda (https: Lb
Virtualenv (https:
Numpy ( www. [Link]
Pandas (https:/
Matplotlib ([Link]
Scikit-learn (http: [Link] fi/
TensorFlow (ht [Link]/
TFLearn ([Link]
Datasets
[Link] / 1)
e@ Bank Churn Modelling
[Link]/aakash50897
modellingcsv /data)
ea
Coursera Deep Learning Specialization
(https: [Link], /specializations /deep-
learning)
[Link] - Deep Learning for Coders
([Link]
Overfitting
(https: [Link]/wiki/Overfitting)
A Neural Network Program
(https: //[Link]
TensorFlow Examples
(https: //[Link] ‘aymericdamien /TensorFlow-
Examples)
TFLearn Examples
/master/exa
mples)
Machine Learning Crash Course by Google
(https: //[Link]
Choosing the Right Estimator ([Link]
[Link]/stable/tutorial/machine learning ma
ex. html)
Cross-validation: evaluating estimator performance
(http: //sctkit-
[Link]/stable/modules/cross_ validation. html )
122
n> a nee airtel
——s 7ear
roe
perf nbarrod. ee a
Apatite Tye) -
2 ” : 7 \yeeto4s- Pf a
‘— i me 28). stah-
uni? mh ae, hy -?
ep blysati er :
eames.=" We. ©
: newsedia ass
or
=, >~i52 A < ' =) t= ”
ry « 4 : mye lk” i z
, ~
‘ = «
v 7 cs ia a » er bi
Thank you!
Thank you for buying this book! It is intended to help you
understanding machine learning using Python. If you enjoyed
this book and felt that it added value to your life, we ask that
you please take the time to review it.
a
ae
Al SCIENCES
We are avery small publishing company and our
survival depends on your reviews.
Please, take a minute to write us your review.
[Link]/dp/BO7F193447
124
oe :
Al SCIENCES
NNN
33852192R00076
een
Middletown, DE
18 January 2019
Wi
Python Machine
Learning
from Scratch
If you are looking for a practical book to help you understand Machine
Learning step by step by using Python, then this is a good book for you.
Is this book for me?
oe
SBN 9781725929982
Zov-zN
9°781725°9 AU
UEIUA
CU
UOSOS
QEQUT
ATH
HAUS
A