Python Programming and Maching Learning 2 in 1 B08Y5DPX32
Python Programming and Maching Learning 2 in 1 B08Y5DPX32
Introduction
Characteristics of python programming
History of Python language
What is Python?
The advantages of Python
The disadvantages of Python language
The design limitations
Common Terms You Should Know with Python
Python Language Structure
Getting Started with Python
Learning the Basics of Python Programming
Flow of Control
Comments
Escape sequences
Variables and What They Do in Python
Understanding the scope of a variable
Modifying values
Python programming 2
How does Python Execute a Program
Survey of a Simple Program
Some of the Basic Commands, Variables, Statements, and Other Things that you can do
Allocating values to your variables
Multiple assignments
Keywords
Operands and operators
Understanding the decision control structure
Loop Control Statements
Functions
Lifetime and scope variables
List comprehension
What is machine learning?
Sorts of Systems of Machine Learning
What is Supervised Machine Learning?
Classification:
Unsupervised Learning
Association
Semi-Supervised Machine Learning
System Testing
System classification
Line Plot
Images
How to train a model
Gradient descent
Batch gradient descent
Stochastic gradient descent
Mini-batch gradient descent
Regularized Linear models
Mass function of a binomial distribution:
Introduction
Most computer language seems terrible to programmers that are yet to
start coding, you might have taken a look at a couple of the popular
programming languages, for example, C++ or Java and been somewhat
humiliated by what you saw. The pages may have been filled to the edge with
letters and images that you simply didn't comprehend, and you got
disappointed and just needed to leave. Numerous individuals are scared of
programming and feel like it is just unreasonably hard for them. In any case,
with the Python programming language which is known as home for all, as it
is recommended by programmers around the globe as a good language for
beginners to learn, you will find out that it doesn’t take much for one to read
and understand programming. This book is going to give you the
fundamentals that you need to acquire for a smooth Python programming
journey.
The world of computer has acquired various kinds of people. Some are
keen on bringing in cash by creating their own programs to offer to other
people. Why few do play and learn various things about how the system will
work. Also, many have dedicated their lives to programming, making it the
item that brings home their salary every month whether they work at fixing
systems, work in a company to protect the computer, or doing some other
types of computer technology. With regards to computer technology, nothing
will be straightforward. Previously you can even get a program to chip away
at the computer; it needs to get the right code to make it work. There are a
few choices for program creation that a programmer may choose including
Java, C++ and Python. Here we will investigate some things about Python
and why it is regularly favored over the other programming alternatives.
Before you can begin using Python to assume control over your programming
needs, it is essential to begin studying it and the whole incredible advantages
you will get when utilizing this program. Python is an elevated level
programming device, which implies that it is always simple to utilize and
peruse, even as a learner. The way of thinking behind the code is lucidness
and it has a kind of sentence structure that permits the developer to
communicate their ideas without having pages of code alongside it.
Readability and simplicity are python’s top priorities, which is an
extraordinary language for amateurs to begin on the grounds that they will
really have the option to read and comprehend the code they are placing in.
With different alternatives to programming, they may need to invest a great
deal of effort trying to get the code just right, including numerous different
objects to get it to work. Be that as it may, with Python, it is kept simple and
you will find that it is easy to understand what you are doing.
1. Well designed syntax: python has a rich grammar which will make
the projects so natural to peruse, the language is simply English
which makes it work without a great deal of bugs. Python has as a
huge library that will work with other programming tasks, for
example, evolving documents, scanning for text, and connecting
with web servers.
2. Python is extremely intuitive. This makes it simpler for you to try
out little bits of code to check whether they work. You can
likewise organize it with a development environment called IDLE.
On the off chance that you might want to extend the programming
language, it is extend into different modules like C or C++.
3. Availability: Python programming can be run on any unit
including Unix, Linux, Windows, and Mac OS X.
4. Programming for all: Python is free. You won't need to pay
anything to download and install Python in any device. You can
likewise make alterations and redistribute this software. It is under
a license, however it is an open source license so others can utilize
it as well.
5. Pro features: Despite the fact that Python is a straightforward
programming language, it contains some advanced features such as
list comprehensions and generators. The software is sensitive to
mistakes (errors are easily detected), since instructions are
progressively composed, when you combine types that don't
coordinate, it will raise an exception for you to take note. You can
arrange the codes into bundles and modules if necessary. There is a
wide assortment of fundamental data types that you can browse
like dictionary, strings, lists and numbers
History of Python language
The Python language was created in 1990 by Guido Von Rossum at
Stichting Mathematisch Centrium in the Netherlands. The language itself has
been actually developed by a large team of volunteers and is open sourced.
At that point, van Rossum was dealing on a project with the Dutch CWI
research foundation, that was later closed. Van Rossum used some basics of
this new computer language (ABC language) had the option to utilize a
portion of the basics of this new language, known as the ABC language, so as
to deal with Python.
In early 2000, Guido and some of the key python development team
went beopen.come to form the BeOpen PythonLabs team. In the same year,
the PythonLabs team moved to Digital Creations which is now known as
Zope Corporation.
Python 2.0 was released on the 16th of October in the year 2000 with features
including a garbage collector which helps maintain memory handling related
issues in programming. The great thing about Python was that it is backed by
a community and it has a transparency behind the users that utilize the Python
language.
Python 3.0 which was a major backwards-incompatible version was released
on December 3rd 2008 after a long time of testing. The major features of
Python 3.0 also have been backported to backwards-compatible Python 2.6
and 2.7.
Python Version Release Dates:
Python 1.0.0 (series) - January 1994- September 5, 2000
Python 2.0.0 (series) - October 16, 2000- July 3, 2010
Python 3.0.0 (series) - December 3, 2008-till date
The fundamental quality of this language is that it is extremely simple to
reach out upon to make progressively complex, or keep basic, and it has the
option to help various levels of intelligence. Both of these were significant
during the days when individual computers were getting into the mainstream.
Furthermore, since Python was made to interact with various file formats and
libraries, it turned into a hit also. Python has developed a considerable
amount since its commencement and more tools have been added to make the
programming all the more working. Notwithstanding making Python simple
to utilize, van Rossum team has been working at various stages to see that
python meets everybody’s need. Using Python language to code can make
things simpler and assists with disposing of a portion of the feelings of
unease related with the unpredictable computer codes since it doesn't look so
alarming. Throughout the years, van Rossum chose to make Python open to
all. This permitted all to get entrance and make changes to Python so that if
something happened to van Rossum, all would not be lost. On account of
having Python open sourced, Python 2.0 was released during 2000 to make it
community based and to have a straightforward improvement process. There
are a couple more up to date forms of Python 2.0 despite everything being
utilized, however Python 3 the latest release stormed the world. Python 3 was
released in 2008. It isn't just an update to the program, however a total
change. While there are a ton of incredible features that accompany this
version, non is compatible with other so you will need to settle on a decision
between Python 2 and Python 3. To make things simpler, the software
engineers made a little marker inside the program that would demonstrate a
programmer what should have been changed between the two programs when
uploading. In spite of this, most have stayed with Python 2.0 for the time
being.
What is Python?
Python is generally an object-oriented, high-level programming language
with dynamic syntax. Python has been distinguished because of the increased
efficiency that it provides since the edit-test-debug cycle is incredibly fast
compared to other programming languages.
The Python language has a simple, easy to learn syntax which is empowered
with many English words for easier readability and assists for increased
productivity and efficiency. When programming in Python, it feels more like
you are writing out the solution to a problem in your own thoughts rather
than trying to refer to ambiguous symbols that are needed in the language to
give to certain functionalities. Python language can be used to automate
measurements and process data interactively. Python is able to handle large
databases and compute large numbers with much ease compared to many
other programming languages. It can be used as an internal scripting
language so that it is executed for certain functions by other programs. By
learning Python, you will be able to write complex software like intricate web
crawlers. It is truly an all-purpose language. The great thing about Python is
that it has a giant library for web crawling and is used a lot for its capability
in scraping the web. A web crawler is simply a program that can navigate the
web depending on the parameters set out for it and scrapes content that you
would like for it to scrape. All in all, Python can be easy to pick up whether
you’re a beginner in programming or an expert on other languages. It’s a fast,
friendly and easy to learn language but don’t mistake that for its powerful
nature.
Triple quoted string: this is a string that has three occasions of either the
single statement or the double statement. It could have something like '''I love
tacos'''. They are utilized for some reasons. They can assist you with having
double and single statements in a string and they make it simpler to go over a
not many lines of code without issues.
Tuple: this is a datatype that has been incorporated with Python. This
datatype is an immutable arranged sequence of values. The sequence is the
main part that is immutable. It can contain some variable qualities, for
example, having a dictionary inside it, where the value’s can change.
Type: this is a classification of data that is represented in the programming
languages. These sorts will vary in their properties, they have mutable and
immutable option, just as in their capacities and techniques. Python
incorporates a couple of these including dictionary, types, tuple, list, long,
integer floating point and string.
In order to install Python on system, you have to download the following:
1 Python IDE
2. Python Interpreter.
The download of these two tools will facilitate the process of becoming a
Python programmer. An IDE is a packaged application program used by
programmers because it contains necessary tools in order to process and
execute code. An IDE contains a code editor, a compiler, a debugger, and a
graphical user interface (GUI). There are different types of IDE but the most
popular among them is PyCharm for Python. For you to use the PyCharm
IDE from JetBrains, you must first install the Python Interpreter (IDLE
version 3.4) on your system so PyCharm is able to detect Python on the
computer. For you to download the python interpreter use the link bellow:
https://www.python.org/downloads/ once you have open the link you will
find download then, click download and a file will be downloaded
accordingly. Once you have this file, execute it and follow the instructions on
the wizard to install the Python Interpreter. After the installation of python
interpreter you can proceed to downloading the IDE PyCharm. In order to
install PyCharm, visit the link below:
https://www.jetbrains.com/pycharm/download/ and click the “Download
Community” button and continue to download PyCharm. During this process,
it will automatically detect the Python 3.4 IDLE but in rare cases you might
need to specify the directory that you installed Python in.
Once you have completed the installation of PyCharm and the Python 3.4
IDLE, go to File New Project. You will reach this screen:
You can rename the “untitled” portion of the Location field to a specific
project name. Then click the “Create” button and you will end up being in an
empty project. The next thing we must do is create a new Python file which
you can do by going to: File New Python File Set the name of your python
file accordingly and it will show under your project name in the Project
Explorer. Now double click on the file and you will be met with a page where
you can start coding Python.
Text editor
You won't have the option to program Python without having the text editor
on your Computer. On the off chance that you are utilizing Windows, the
Notepad capacity will work. Ensure that you are not utilizing Word because it
isn't viewed as an editorial manager furthermore, your code won't save on the
system appropriately. In the event that you are considering getting a variant
of Notepad, you will see that Notepad ++ is the best one to use on a Windows
and Text Wrangler is the best to use for Mac. To set them up, fellow the steps
bellow:
Windows
Getting IDLE
While you are setting up Python, ensure that you download the integrated
Development and Learning Environment. This ought to download alongside
Python on the off chance that you are setting it up, however ensure to look
into this while you are experiencing the procedure. This is the environment
that you are going to work with when you are on Python and it can make
things simple. On the off chance that you try not to need to play with finding
another environment or you need to make the process as simple as workable
for you as a novice, this is the alternative for you.
The primary features of using integrated development learning environment
with your Python programming include:
And
Pass
Or not
Nonlocal
None
Lambda
Is
In import
If
Global
From
For
Finally
False
Except
Else
Elif
Del
Def
Continue
Class
Break
Assert
As
Yield
With
While
Try
True
Return
Raise
Identifier Names
At the point when you are making another program in Python, you are going
to work on making many entities, a mix of functions, classes, and variables.
All of these will be given a name that is otherwise called an identifier. There
are a scarcely any standards that you have to follow while framing an
identifier in Python including:
Flow of Control
When dealing on the Python program, you will work out the statements in a
rundown design, much the same as you would when working out a shopping
list. The PC will begin with the principal instruction before working through
each of them in the order that you make them appear on the list. So you
should work out the controls that you need simply like you would for your
basic food item shopping list to ensure that the PC is perusing it
appropriately. The PC will just quit perusing this rundown once it has done
the last instruction to finish. This is known as the flow of control. This is a
significant method to begin. You need to ensure that your flow of control is
even and smooth for the computer to peruse. This will make it simpler to get
the program to do what you want without much difficulty and do ensure that
the computer program is free from any issue.
Semi-colons and Indentation
If you examine some other computer languages you will notice that there are
lots of brackets used to organize the various blocks of code most times used
to start and end statements. This encourages you to make sure to indent the
code blocks in these languages to make the code simpler to read, despite the
fact that the system can peruse the various codes without any indentation.
This sort of coding can make it extremely hard for one peruse. You will see a
great deal of superfluous information that is required for the PC to peruse the
code, yet can make it hard on the natural eye to understand this. Python
utilizes an alternate method of doing this, generally to help make it simpler
on the natural eye to peruse what you have. You are going to need to indent
the code for this to work. A case of this is:
# this function definition starts another block
def add_numbers (a, b):
c= a + b
# as is this one
return c
# this function definition starts a new block
if it is Saturday
print (It's Tuesday!"
# and this one is outside the block
print ("print this no matter what.")
Moreover, there are a ton of languages that will utilize a semicolon to tell
when an instruction end. With Python however, you will utilize line ends to
tell the system when an instruction will end. You will have the option to
utilize a semi-colon if you have a couple of instruction that are on a similar
line, yet this is regularly thought about inappropriate behavior within the
language.
Letter Case
Most system languages will treat up ercase and lowercase letters equally, yet,
Python is one of the main ones that will be case sensitive. This implies that
the lower case and upper case letters will be dealt with differently in the
system. Remember too that all the reserved words will utilize lower case with
the exception of None, False, and valid.
Comments
Types will comprise of two separate parts. The first part is a domain
that will contain a potential arrangement of values and the next part is a set
that contains the potential operations. Both of these can be performed on any
value. For instance if you have a domain that is a sort of integer, it can just
contain integers inside it with addition, division, multiplication, and
subtraction. One thing to note with this is Python is a progressively composed
program. This implies that there truly isn't a need to indicate the sorts for the
variables when you make it. Similar factors can be utilized to store the values
of various types. Regardless of this, Python despite everything needs you to
have all the variables with a definitive type. For instance, if the developer
attempted to add a number to a string, the Python program would dictate the
mistake and show error. It won't attempt to make sense of what you needed;
rather it will simply exit.
Integers
On the off chance that you need to utilize integers as a type, you have to keep
them as whole numbers. These can be positive or negative numbers, as long
as there are no decimals with these numbers. In the event that you have a
decimal point in the number, regardless of whether the number is 1.0, you
should utilize it as a floating point number. Python can show these whole
numbers in the "print" function, yet just in the event that it is the sole
argument.
Print (3)
# Let's sum two numbers together
Print (1+2)
On the off chance that you are utilizing whole numbers, you won't have the
option to put the two right close to one another. This is for the most part a
direct result of how Python is a typed language furthermore, won't remember
them in the event that you join them together. If you might want to put the
number and the string together, you have to ensure that the number has
transformed into a string.
Operator Precedence
One thing that you have to monitor when you are working in Python is
operator precedence. For instance, on the off chance that you have 1+2//3
Python could interpret it as (1+2)//3 or 1+ (2//3). Python has a technique that
will assist you with ordering the operation appropriately with the goal that
you get the correct data to appear. For instance, with regards to integer
activity, Python deals first with bracket after which other operations that have
**, then*, and then//, then %, +, lastly - .
Whenever you are composing an expression that has various
operations in it, you will need to remember those signs. This will disclose to
Python how to work the numbers so you can find the correct solutions at that
point. Remember that most arithmetic operators will be left associative so
work it out that way for Python to peruse. The main special case is the **
feature. For instance:
# ** is right-associative
2**3**4
# will be assessed option to left:
2**(3**4)
Strings
While a string may appear to be something complex, in Python they are
fundamentally a sequence of characters. They are going to work a similar
way as a list does, yet they will contain more functionality that is explicit to
the text. Organizing strings can be a test with regards to composing your
code. There are a few messages that won't be fixed string and some of the
time there are values that are stored inside variables within it. There is an
approach to get this to work directly for string formatting. A case of this is:
Name = "Janet"
Age = 24
Print("Hello! My name is %s." % name)
Print("Hello! My name is %s and I am %d years old." % (name, age))
The symbols that have a % first are called placeholders. The variables that go
into these positions will be set after the % in the order where they are set in
the string. In the event that you are doing only a single string, you won't need
a wrapper, however if you do have more than one of these, you have to put
them into a tuple, with a () enclosing it. The placeholder symbols will begin
with various letters, based on the variable type you are utilizing. For instance,
the age will be an integer by the name in a string and all these variables will
be converted into the string before you can be able to add them into the rest.
Escape sequences
Escape sequence is a way used to denote special characters that are usually
difficult to type on your keyboard. What's more, they can be utilized to
represent characters that can be saved for something different. For instance,
using and in the arrangement can confuse the program so you may utilize the
escape sequence to change that for instance:
Print("This is a line. \nThis is another line.")
Triple Quotes
Having dealt with both single and double quotes its important that you
understand that at certain time you may need to bring in the triple quote. This
is used when you have to characterize a literal that will traverse numerous
lines or one that has a great deal of quotes in it. To do this, simply utilize a
single and double together or three singles. A similar principle applies with
the triple quotes likewise with all the others. You should begin and end the
phrase with a similar one.
String Operations
One of the most needful string operations is a concatenation, which is useful
while joining a pair of strings together and it’s denoted with the + symbol.
There are a great deal of functions that Python can support you with and they
will work with the strings to make an assortment of operations. They will
have some helpful alternatives that can do significantly more in the Pythons
program.
In Python programming, strings are called immutable. This implies
that once you make the string, it won’t be changed. You may need to assign a
new valuable to a particular variable that exists in the event that you are
hoping to make a few changes. There is so much that you can find out about
with regards to getting started with Python. It might be a straightforward
language, however you need to have the option to figure out how it functions,
how to write things appropriately, and even how to leave a comment for
others to comprehend when they are glancing through the code. It may appear
to be somewhat scary first and foremost, however sooner rather than later,
and with some training, you will get it down and be composing your own
code within the blink of an eye.
Modifying values
In some programming languages, you will have the option to characterize a
unique variable that has a value that has been set. This implies the value can't
be changed. These are called constants in the programming language.
Generally, Python won't take into consideration these sorts of limitations, yet
there is a convention that is utilized to help guarantee that a few factors are
set apart to demonstrate that the qualities should be changed. To show this,
the names will be written in CAPITAL letters with underscores between each
word. An example of a variable that is a constants include:
NUMBER_OF_DAYS_IN_A_WEEK=7
NUMBER_OF_WEEKS_IN_A_YEAR=52
Obviously, there are no rules to state you need to put the correct number
toward the end. You could state there are 8 days in a week if you want it that
way on the grounds that the Python program won't follow along, however it
is ideal to simply keep it exact in the event that other coders might want to
utilize it. These can be extremely useful to you in your string. Some of the
time in the program, for instance, you will need to change the limit of a
number that is permitted in the program. This may work fine for a bit, yet
perhaps later on you have to increase or reduce this number. Without setting
up a constant, you need to experience and make many changes to get
everything coordinated. Yet, with a decent constants all together, you can
simply return to one spot and get everything repaired. Understanding how the
strings work in your program can have a big effect in the success that you see
with this program. You have to realize where they are stored, what the rules
are that administer every one of them, and how to make them work in a
particular part of the program. With a touch of training, and utilizing the
procedures above, you will get this down in no time and can be a veteran as
well!
Python programming
2
Multiple assignments
Notwithstanding working with the single variables that were listed above,
you will likewise be ready to work on multiple assignments. This implies you
will be ready to assign one value to a few distinct variables simultaneously.
To do this, you would simply require to put the equivalent (=) sign between
every one of them to keep things sorted out and to tell the system that the
value will be with the whole of the factors together. You can keep them
separated out if that is best for you, however utilizing this technique is going
to assist you to send everything to a similar memory location on the system
and will give the code a more clear look on your screen. An instance of how
to give more than one variable a similar value includes:
a=b=c=1
From the above you want to let the code know that all the variables are of the
same value and that you want all the variables to be at same location within
your memory.
Standard data types
In addition to the goodies of python another thing that you’re able to work is
the various data types which will be used in your code to define the
operations that you can do on each data type and explain to others the storage
method that will be best for this kind of data. Python has five standard data
types, they are:
Numbers: The Number data types are the ones that will store the numeric
values. They will be made as objects once you assign a value to them. There
are additionally four unique kinds of numbers that Python will support they
are :
Keywords
The majority of the kinds of programming languges that you will manage
will have a few keywords that are saved as a component of the language.
These are words that you truly shouldn't use in your code except if you totally
can't resist. There are 33 keywords found in the latest version of Python and
you should spell them appropriately on the off chance that you need them to
carry out the responsibility that you want them do. The 33 keywords that you
should keep an eye on include:
False
Class
Finally
Is
Return
None
Continue
For
Lambda
Try
True
Def
From
Nonlocal
While
And
Del
Global
Not
Yield
As
Elif
If
Or
Assert
Else
Import
Pass
Break
Except
In
Raise
Keep this list handy in the event that you are stressed over learning the
language. It will have the option to help you out whenever that you have
issues with the interpreter about the names that you are giving the variable.
You might be confounded regarding why it is giving you a few issues with
the words you picked, you can through this list and check whether you
utilized one of the keywords inappropriately within your code.
Statements
At the point when you are composing your code in the Python language, you
will be making expressions and statements to get the program working.
Expressions will be able to process the objects and you will discover them
installed within your statements. A statement is essentially a unit of code that
will be sent to the interpreter with the goal that it may be executed. There are
two sorts of statements that you can utilize; assignment so far and print. You
will have the option to compose the statement, or multiple statements,
utilizing the Python Shell to do so intuitively or with the Python script
utilizing the .py extension. At the point when you type these statements into
the interactive mode, the interpreter will work to execute it, as long as
everything is appropriately set up, and afterward you can see the outcomes
shown on the screen. When there are many lines that you have to write in
code, it is ideal to utilize a script that has an arrangement of statements. For
instance
#All of these are statements
X = 56
Name = "Mainu"
Z = float(X)
Print(X)
Print(Name)
Print(Z)
While you are utilizing the operators and operands, you have to recall that
there is
Note: one other good thing about python is that you can send out, which
permits you to explain what you are working on instead of stressing the other
programmer that will read the code to comprehend the code that way. You
will simply introduce the # sign to denote that a comment/statement about the
code was left. The program interpreter whenever it comes across the # sign
will ignore it but it won’t be removed because another programmer may need
to look at the code if need be.
Utilizing the "if" keyword is going to tell the compiler that what you are
composing is a Decision control instruction. The condition that is behind the
keyword if it is within the parenthesis, the conditions should be true in the
event that you need the code to come out, however on the off chance that it
isn't correct, this statement is simply going to be overlooked in this
circumstance and it is going to proceed onward to the next command that you
give. You can as well set up an "if… else" clause. This one would show the
unique message if the conditions were true. In any case, if the conditions are
false, it would end up putting out a second statement. This can assist with
guaranteeing that you are getting the correct message across regardless of
what another person is sending over and keep the interpreter from totally
overlooking this step.
So the following inquiry that you might be asking is the means by
which we can tell whether the statement is true or false? You should utilize a
portion of the relational operators to make this happen on the grounds that it
will have the option to compare the two values to check whether they are
equivalent, inconsistent, or another choice. A portion of the options that you
can use to check whether a statement is correct include:
Expression Condition for the expression to be
true
X == y X is equal to y
X != y X X is not equal to y
X<yX X is less than y
X>yX X is greater than y
X <= y X X is less than or equal to y
X >= y X X is greater than or equal to y
if (age <=18):
print("You are not eligible for voting, try next election!")
print("Program closes")
This code will print you out a difference example based of the age that is
placed in. Since it is an if statement in particular, you will find a solution
exactly when the number is 18 or under. Here we will take a look at the
output based on the age of 18 and that of 35.
Enter your age: 18
You are not qualified for voting, try next election!
Program ends
Enter your age: 35
Program closes
Presently we should investigate including various statements in your "if"
statement. It isn't extraordinary to discover at least two statement being put
inside an expression and working fine and dandy if everything is fulfilled. On
the off chance that these statements are executed, you will need to ensure that
you indent them appropriately. We should investigate how this could work.
Ensure to check out this on your interpreter to get some knowledge in
composing code and how the "if" statements are going to work.
bonus = 0.0
currentyear = int(input("Enter current year:"))
yearofjoining = int(input("Enter year of joining:"))
yearofservice = currentyear – yearofjoining
if(yearofservice >2):
reward = 1500
print("Bonus - %d" %bonus)
print("Congratulations! We can give you a reward o %d" %bonus).
Now if the "if" statement ends up being higher than two, you will find that
the congrats statement is going to be displayed. However, in the event that
the sum is lower than two, you are going to wind up without any statement
since the entirety of the statements were not met. You can put whatever
numbers that you need inside it so as to get it to work for each employee in
this option.
The "if-else" Statement
So far we have recently been discussing the "if" statements. These are ones
that should be true before any of your statement come out. On the off chance
that things come out to be false, there will be no statement by any means.
Now assuming you want to have different statements displayed then you will
need the "if else" statement, you can pick two or more, statements that are
going to come up dependent on the outcomes. On the off chance that your
outcomes end up being true, you will have the first statement appear,
however on the off chance that the outcomes wind up being false, you can
pick another statement that you might want to appear also. This guarantees
you are getting an answer regardless of the outcome with the goal that the
program shows something new. You simply need to ensure that subsequent to
working out your "if" statement, you include the "else" and afterward put in
the statement that you might want to have displayed. This can take a touch of
time to work, yet it opens up such a significant number of extraordinary
options with your code to ensure that everything levels out and looks pleasant
with your code.
The elif Statement
Another alternative that you can do with your statements is the elif statement.
This one is going to give you the choice of looking at a couple of expressions
as true, instead of just one expression as true, with the goal that you can
execute the entire block of code once just one of the conditions goes up to be
true. Obviously, doing this is discretionary, yet there is the advantage of
being able to have any number of elif statements after the if.
How about we investigate what the whole of this is going to look like when
you work it out in the syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
You will at that point have the option to put your data into the parts and find
the solution that is
Nesting loops
Using a for loop
Using a while loop
Functions
Functions are another significant part of learning the Python language. These
are fundamentally blocks of code that are independent and will have the
option to play out some sort of rational task in your code. At the point when
you set aside the effort to characterize a function, you will be able to specify
the name of the function just as the sequence of the statement. You will at
that point have the option to call up the function utilizing its name. There are
two kinds of functions that we are going to use here and we will talk about
them beneath.
User characterized capacities
With this one, you will have the option to characterize the function that you
are utilizing. They are going to have essentially similar guidelines that you
found with variable names. This implies using underscore characters,
numbers, and letters will work extraordinary, however you ought to never
utilize a number for the first character in the function. You can't utilize your
keywords as the name of your function and you ought to be cautious about
having a function and a variable that have a similar name. The empty
brackets that you will see after the name will show that the function isn't
going to take on any arguments. The first line will be known as the header
while the rest are known as the body. You have to ensure that the header
closes with a colon and that you indent in the body so the interpreter
recognizes what you are doing. A good instance of the syntax or a function is:
def functionname(arg1, arg2, arg3):
'"docstring of the function i.e., a short presentation about the function"
#code inside the function
Return[value]
#a function might not have any arguments or parameters like
def functionname():
#code inside the function
Pass by references
In Python, the entirety of the parameter that you put in will be passed by
reference. This implies that the location of the area in the memory will be
referenced to the memory area. So in the event that you are going to change
what your parameter is able to refer to in the function, this equivalent change
is then going to reflect back when you are doing the calling function.
Flow of execution
The execution of the statement is continually going to begin directly at the
first statement that is in the program. Your statement will be done just one at
a time to stay away from disarray and ensure that the program is running as
easily as it should. The execution is likewise going to happen going from top-
down so you have to ensure that you are placing them rightly. Ensure that
you are characterizing the function before you choose to ring them to get the
correct request.
Anonymous functions
Python permits the developer to make anonymous functions. These are
functions that won't be bound to a name at run time and you are going to need
to utilize a construct that is known as "lambda." This operator is an approach
to create these functions that try not to have a name. Fundamentally you will
need to make these when the functions are considered expendable, or they are
simply required right where they have been made. There are a couple of
functions that Lambda functions will work with including reduce(), map(),
and filter().
The syntax that you will need to use with the lambda function is:
lambda argument_list: expression.
The reduce, filter, and map function
We have discussed various functions so far in this book, yet it an opportunity
to take a look at a Few others that are going to help you with get more out of
the code that you are composing. Especially, we are going to study the map,
filter, and reduce functions, with list comprehension to assist you getting
started.
Map function
The map() function is the one that will apply to every part in an iterable, or
those within a list. Generally, you would utilize the anonymous inline
function to make this work, however this is one of them that you can use
within any of your functions. So if you are attempting to take a shot at a list,
this would be a decent one for you to utilize in your system code.
Filter function
Following up is the filter function. Much the same as you would figure from
the name, the filter can remove the components in the sequence for which the
functions returns a true. The rest would be overlooked. This implies you will
need to do a grouping that would be either true or false so as to get this one to
function. At the point when the sequence has a couple of alternatives that are
valid, the filter function will choose those ones. Though, if every one of
them, or possibly a portion of the sequence points, are false, you will find that
these are not separated out.
Machine learning
What is machine learning?
Machine learning is the act of programming systems to study and learn
from data. For instance a system with artificial intelligence will be able to
determine when an information is true/false, important or spam, etc.
Why machine learning?
Assuming you prefer to write a filter program without machine learning
procedures, you will have to study the problems then write rules and evaluate
them to ensure they are as expected after which you launch the program if
there where error you then have to analyze the problem and repeat the rest
processes and launch again, you observe that every step is done manually
unlike when using artificial intelligent. Also machine learning procedures are
used to solve more complex problems automatically, lastly machine learning
will assist us to learn why machine learning algorithms makes it easy for us
to see what we have learnt.
When would it be a good idea for you to utilize machine learning?
• When you have a problem that requires many not insignificant list of rules
to discover the solution. For this situation, AI procedures can disentangle
your code and improve execution.
• Very perplexing issues for which there is no solution with a customary
approach.
• Non-stable environments: Machine learning programming can adjust to new
information.
Sorts of Systems of Machine Learning
There are various types of machine learning systems. We can partition them
into classes, based upon whether
• They have been trained with humans or not
Supervised
Unsupervised
Semi-administered
Reinforcement Learning
• If they can adapt gradually
• If they work just by contrasting new information to discover data points, or
can identify new patterns in the information,and afterward will manufacture a
model.
All these details are your inputs. The output is the time it took you to drive
Unsupervised Learning
Unsupervised learning is a machine learning technique, where there no need
to supervise the model. Instead, you will allow the model to work on
independently to predict accurately (here there is absence of output variable).
Unsupervised leaning majorly deals on unlabelled data, unsupervised
learning algorithms permits you to perform more complex processing tasks
than supervised learning. Also unsupervised learning can be more
unpredictable compared with other natural learning deep learning and
reinforcement learning methods.
Why Unsupervised Learning?
Here, are basic reasons for using Unsupervised Learning:
Unsupervised learning finds all kind of unknown patterns in data.
It is simple to get unlabeled data from a computer than labeled
data, which needs manual intervention.
Unsupervised methods help you to find features that can be useful
for categorization.
It occurs in real time, so all the input data to be analyzed and
labeled in the presence of learners.
Insignificant Features
The system might have the option to learn if the training information contains
enough features and information that aren't excessively insignificant. The
main piece of any machine learning project is to grow acceptable features "of
feature engineering".
Feature Engineering
The cycle of feature engineering goes this way:
System Testing
In the event that you'd prefer to ensure that your model is functioning
admirably and that model can sum up with new cases, you can evaluate new
cases with it by putting the model in the environment and afterward
observing how it will perform. This is a great technique, yet on the off chance
that your model is lacking, the user will grumble. You should isolate your
data into two sets, one set for training and the second one for testing, so you
can train your model utilizing the first and test it utilizing the second. The
speculation error is the rate of blunder by evaluation of your model on the
test set. The value you get will let you know whether your model is
acceptable enough, and in the event that it will work appropriately. In the
event that the error rate is low, the model is acceptable and will perform
appropriately. Conversely, in the event that your rate is high, this implies
your model will perform poorly and not work appropriately. My
recommendation to you is to utilize 80% of the data for training and 20% for
testing purposes, so that it's extremely easy to test or assess a model.
Overfitting the Data
Assuming you visited a home and one of them steals from you, why leaving
the house you will have the thought that every member of that family is a
thief. This is an overgeneralization, and, in machine learning, is designated
"overfitting". This implies that machines do something very similar: they can
perform well when they're working with the training data, yet they can't sum
them up appropriately. For instance, in the accompanying figure you'll locate
a high level of life fulfillment model that overfits the data, yet it functions
admirably with the training data.
When does this happen?
Overfitting happens when the model is extremely complex for the amount of
training data given.
Solutions
To take care of the overfitting issue, you ought to do the accompanying:
- Gather more data for "training data"
- Reduce the commotion level
- Select one with fewer parameters
Underfitting the Data
From its name, underfitting is something contrary to overfitting, and you'll
experience this when the model is exceptionally easy to learn. For instance,
utilizing the case of personal satisfaction, real life is more complex than your
model, so the expectations won't yield the same, even in the training models.
Solution
To fix this issue:
- Select the most powerful model, which has numerous parameters.
- Feed the best highlights into your algorithm. Here, I'm alluding to feature
enginerring.
- Reduce the constraints on your model.
Chapter 2
System classification
For you to appreciate this chapter you must install python, matplotlib and
scikit-learn
Matplotlib python
Matplotlib is a plotting library for the programming language; it provides an
object-oriented API for embedding plots into applications using general-
purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+. Matplotlib can be
used in Python scripts, the Python and IPython shell, web application servers,
and various graphical user interface toolkits.
Line Plot
Images
Matplotlib can display images
Arbitrary path
Metplotlib has option for arbitrary paths
Scikit-learn is a machine learning library for Python. It features
different algorithms like support random forests, and k-neighbours,
vector machine, and it also supports Python numerical and
scientific libraries like numpy and scipy.
The Mnist
In this part, you'll go further into grouping systems, and work with the Mnist
data set. This is a group of 70,000 pictures of digits handwritten by students
and employees. You'll see that each picture has a label and a digit that
represents it. This task resembles the "hello, world" case of customary
programming. So every learner to AI should begin with this venture to learn
about the grouping calculation. Scikit-Learn has numerous capacities,
including the MNIST. How about we take a look at the code:
>>> from sklearn.data sets import fetch_mldata
>>> mn= fetch_mldata('MNIST original)
>>> mn
{'COL_NAMES': ['label', 'data'],
Description: 'mldata.org data set: mn-original,
data: array([[0, 0, 0,..., 0, 0, 0],
[0, 0, 0,..., 0, 0, 0],
[0, 0, 0,..., 0, 0, 0],
...,
[0, 0, 0,..., 0, 0, 0],
[0, 0, 0,..., 0, 0, 0],
[0, 0, 0,..., 0, 0, 0]], dataType=uint8),
'tar': array([ 0., 0., 0.,..., 9., 9., 9.])} de
. Description is a key that defines the data set.
. The data key here contains an array with only one row for example, and a
column for each feature.
. This target key contains an array with labels.
Let practice with few of the code:
>>> X, y = mn["data"], mn["tar"]
>>> X.shape
(70000, 784)
>>> y.shape
(70000,)
. 7000 here implies that there are 70,000 images, and each picture has more
than
700 features: "784". because, as should be obvious, each picture is 28 x 28
pixels, you can envision that each pixel is one feature.
We should take another instance from the data set. You'll just need to get an
instance’s feature, at that point make it 26 x 26 array, and afterward show
them utilizing the imshow function:
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
yourDigit = X[36000]
Your_image = your_image.reshape(26, 26)
plt.imshow(Your_image, cmap = matplotlib.cm.binary,
interpolation="nearest")
plt.axis("off")
plt.show()
As should be obvious in the picture below, it’s like the number five, and we
can give that a label that reveals to us it's five.
In the following
figure, you can see more mind boggling grouping task from the MNIST data
set.
Additionally, you ought to make a test set and make it before your data is
assessed.
As earlier mentioned the MNIST data set is in two sets, one for training and
the other for testing.
x_tr, x_tes, y_tr, y_te = x [:60000], x[60000:], y[:60000], y[60000:]
How about we play with your training set as follows to make the cross-
validation to be comparative (with no missing of any digit)
Import numpy as np
myData = np.radom.permutaion(50000)
x_tr, y_tr = x_tr[myData], y_tr[myData]
Confusion matrix
The confusion matrix is a better way to evaluate the performance of your
classifier, measuring performance with confusion matrix, is easy just by
calculating the number of times instances of class X are classified as class Y,
for example. To have the number of times of image classifiers of 6s with 2s,
you should look at the 6th row and 2nd column of the confusion matrix.
Let's calculate the confusion matrix using the cross_val_predict () function.
From sklearn.model_selection Imported from cross_val_predict
y_tr_pre = cross_val_predict (sgd_cl, x_tr, y_tr_6, cv = 3)
This function, such as the cross_val_score () function, performs the K fold
cross_validation, it also returns predictions at every fold. It also gives a clean
prediction for each instance in your training set.
We are now ready to obtain the metrix using the following code.
From sKlearn.metrix import confusion_metrics
Confusion_metrics (y_tr_6, y_tr_pred)
You will find an array of 4 values, "numbers".
Each row represents a class in the matrix, and each column represents a
column predicted class.
The first row is the negative: containing "non-6 images". You can learn a lot
from the matrix.
But there is also a good one, which is interesting to work with if you want to
get The accuracy of positive predictions, which is the precision of classifier
using this equation.
Precision = (TP) / (TP + FP)
TP: The number of true positives
FP: Number of false positives
Recall = (TP) / (TP + FN) "Sensitivity": It measures the ratio of positive
instances.
Recall
>>> from sKlearn.matrics import precision _score, recall_score
>>> precision_score (y_tr_6, y_pre)
>>> recall_score (y_tr_6, y_tr_pre)
It is very common to combine precision and recall only one metric, which is
the F1 score.
F1 means both precision and recall. We can count the F1 score with this
equation:
F1 = 2 / ((1 / precision)) ((1) / recall)) = 2 * (precision * recall) / (precision +
Recall) = (TP) / ((TP) + (FN + FP) / 2)
To calculate the F1 score, just use the following function:
>>> from sKlearn.metrics import f1_score
>>> f1_score (y_tr_6, y_pre)
Recall Tradeoff
To get to this point, you should take a look at the SGDC classifier and how it
should look(Makes decisions regarding classification). It calculates the score
based on that decision function, and then it compares the score with the
threshold. if it is more than this score, it will exemplify "positive or
negative".class
For instance, if the decision is in the threshold center, you will find 4 true +
on the right of the threshold, and only one wrong. So the accuracy ratio will
just be
80%.
In SciKit-Learn, you cannot set thresholds directly. You will need access The
decision scores, which uses predictions and by y calling the decision
function, ().
>>> y_sco = sgd_clf.decision_funciton ([any digit])
>>> y_sco
>>> Threshold = 0
>>> y_any_digit_pre = (y_sco> Threshold)
In this code, the SGDClassifier has a threshold, = 0, to return the same
outcome as the predict () function.
>>> Threshold = 20000
>>> y_any_digit_pre = (y_sco> Threshold)
>>> y_ any_digit_pre
This code will prove that, when the threshold increases, the recall decreases.
y_sco = cross_wall_predict (sgd, cl, x_tree, y_tr_6, cv = 3, method =
”decision
Function)
This is the time to calculate all possible precision and remember the threshold
by calling the precision_recall_Curve () function
Import from sKleran.metrics the precision_recall_curve
precisions, recall, threshold = precision_recall_curve (y_tr_6, y_sco)
Let's now plot precision and recall using Metplotib
Def Plot_pre_re (pre_re_thr):
plt.plot (thr, pre [: - 1], “b—“, label = “precision”)
plt.plot (thr, re [: 1], "g-", label = "recall")
plt.xlabel ("Threshold")
plt.legnd (loc = "left")
plt.ylim ([0,1])
Plot_pre_re (pre, re, thr)
plt.show
ROC
ROC is meant for the receiver operating characteristic and it is a tool that
works well with binary Classifieds.
This tool is similar to a recall curve, but does not plot for precision and recall:
It plots the positive rate and negative rates. You will also be able to work
with FPR, which is the ratio of negative samples. You can imagine if it is like
this (1 - negative rate. There is another concept TNR and that is the
specificity. Recall = 1 – specificity).
Let's play with the ROC curve. First, we have to calculate TPR and FPR, just
by calling the roc-curve () function,
from sKlearn.metrics roc_curve
fp, tp, thers = roc_curve (y_tr_6, y_sco)
After that, you can plot FPR and TPR with Metplotlib. According to the
concept of
The following instructions
Def_roc_plot (fp, tp, label = none):
plt.plot (fp, tp, linewidth = 2, label = label)
plt.plot ([0,1)], [0,1], "k--")
plt.axis ([0,1,0,1])
plt.xlabel (‘This is the false rate’)
plt.ylabel (‘this is the true rate’)
roc_plot (FP, TP)
plt.show
Multi-class classification
We use binary classifiers to differentiate between any two classes, but when
you have the task to distinguish between multiple classes you use something
like a random forest classifier or a Bayes classifiers, which can compare
between more than two. But, on the other hand, SVM (support vector
machine) and linear classifiers act like binary classifiers.
If you want to develop a system that categorizes images of digit into 12
classes(0 to 11) You need to train 12 binary classifiers, and create one for
eachclassifier (such as 4-detector, 5-detector, 6-detector and more), and then
you will need to get DS, "decision score" of each classifier for the image.
Then you will choose the highest score classifier. We call this the OvA
strategy: one-versus-all.’’ The other method is to train the binary classifier for
each pair of digits; For instance, one for 5s and 6s and another for 5s and 7s. -
We call this method OvO, "one-versus-one" – to count the number of
classifiers needed depends on the number of classes that use the following
equation: ‘’N= number of classes’’ N * (N-1) / 2. If you want to use this
technique with MNIST 10 * (10-1) / 2,The output will be 45 classifiers,
"binary classifiers".
In Scikit-Learn, you run OvA automatically when you use binary.
classification algorithm.
>>> sgd_cl.fit (x_tr, y_tr)
>>> sgd_cl. predict([any issue])
Additionally, you can call the decision_function () to return scores "10
scores".For a class ”
>>> any_digit_scores = sgd_cl.diction_function ([any_digit])
>>> any_digit_scores
Arrays (["num", "num", "num", "num", "num", "num", "num" "
, ”“ Num ”]])
Training to random forest classifiers
>>> forest.clf.fit (x_tr, y_tr)
>>> Forest.clf.predict ([any digit]]
Array ([num])
As you can see, training with Random Forest Classifier is just two lines of
code and its very simple. Scikit-Learn does not run any OvA or OvO
functions because this type of algorithm - "Random Forest Classifier" - can
perform multiple tasks automatically classes. If you want to take a look at the
list of classifier possibilities, you can call the predict_oroba () function.
>>> forest_cl.predict_proba ([any_digit])
Array ([[0.1, 0, 0, 0.1, 0, 0.8, 0, 0, 0]]))
The classifier is very accurate with its prediction, as you can see in the
output; there is 0.8 at the index number 5.
Let's evaluate the classifier using the cross_val_score() function.
>>> cross_val_score(sgd_cl, x_tr, y_tr, cv = 3, scoring = "accuracy")
Array ([0.84463177, 0.859668, 0.8662669])
You will get 84% more times. When using a random classifier, you will find
in this case, 10% for the accuracy score. Keep in mind that the higher this
value is, the Better.
Error analysis
First of all, when developing a machine learning project:
1. Determine the problem;
2. Collect your data;
3. Work on and explore your data;
4. Clear data
5. Work with many models and choose the best;
6. Connect your models to the solution;
7. Show your solution;
8. Run and test your system.
First, you should work with the confusion metrics and make predictions by
cross-val function. Next, you will call the confusion matrix function:
>>> Y_tr_lover = cross_val_prediciton(sgd_cl, x _tr_scaled, y_tr, cv = 3)
>>> cn_mx = confusion_metrics(y_tr, y_tr_pre)
>>> cn_mx
Array ([5625, 2, 25, 8, 11, 44, 52, 12, 34, 6],
[2, 2415, 41, 22, 8, 45, 10, 10, 9],
[52, 43, 7443, 104, 89, 26, 87, 60, 166, 13]
[47, 46, 141, 5342, 1, 231, 40, 50, 141, 92]
[19, 29, 41, 10, 5366, 9, 56, 37, 86, 189]
[73, 45, 36, 193, 64, 4582, 111, 30, 193, 94],
[29, 34, 44, 2, 42, 85, 5627, 10, 45, 0],
[25, 24, 74, 32, 54, 12, 6, 5787, 15, 236]
[52, 161, 73, 156, 10, 163, 61, 25, 5027, 123]
[50, 24, 32, 81, 170, 38, 5, 433, 80, 4250]]
Multi-label classifications
In the above examples, there is only one example in each class, let’s say you
want to assign the examples to multiple classes (like facial recognition), for
example
Suppose you want to find more than one face in a single photo. There will be
a label for each face. Let's practice with a simple example.
y_tr_big = (y_tr> = 7)
y_tr_odd = (y_tr% 2 == 1)
Y_multi = np.c [y_tr_big, y_tr_odd]
kng_cl = KNeighborsClassifier()
Kng_cl.fit (x_tr, y_m, ulti)
In these instructions, we have created a y_multi array that has two labels for
each image.And the first contains information on whether the digit is"large"
(8,9,) another checks to see if it's not.
Next, we will make predictions using the following instructions.
>>> kng_cl.predict ([any digit])
Array ([false, true], dataType = bool)
True here means it’s false, meaning it’s not big.
Multi-output classification
At this point, we can cover the final type of classification function, which is
multi-output classification.
It's just a common case of multi-label taxonomy, but each label will have one
multiclass. In other words, it will have more than one value.
Let’s be clarified by this example, using MNIST and adding images some
noise to the image with NumPy functions.
No = rnd.randint (0, 101, (lane (x_tr), 785)))
No = rnd.randint (0, 101, (lane (x_tes), 785))
x_tr_mo = x_tr + no
x_tes_mo = x_tes + no
y_tr_mo = x_tr
y_tes_mo = x_tes
Kng_cl.fit (x_tr_mo, y_tr_mo)
cl_digit = kng_cl.predict (x_tes_mo [any index]])
Plot_digit (cl_digit)
How to train a model
Having gone this far in learning machine learning models and as well
training algorithms which at the first sight was quite challenging, out of this
fear we managed to penetrate regression system, and also cleared the
atmosphere on image classifiers. Although in the previous chapters we
achieved more than that but we didn’t comprehend the core principles of a
model so now we need to progress deeper into the wonder land so that we can
understand how models work and how to use them for purposes.
Getting a deeper understanding of the above details will help you find
the right model and by choosing the best training algorithm. Also, it will help
you with debugging and error analysis. In this chapter, we will deal with
polynomial regression, which is a complex model that works for nonlinear
data sets. In addition, we will work with some regularization techniques that
cuts down training that promote overfitting.
Linear regression
For example, we would take l_S = θ0 + 1 × GDP_per_cap. This is a simple
model
For the linear function of the input feature, select "GPD_per_cap". (θ0 and
θ1) are the dimensions of the model,
In general, you will use a linear model to calculate and predict
the weighted amount of input features and the constant “bias” as written
below
. Y is the value of the predictor.
. N represents the features
. X1 is the value of the feature.
. Θj is the model dimension of J Theta.
Also, we can write an equation in vector form like the following example.
Computational complexity
With the general formula, we can calculate the inverse of M^T.M - i.e., a
n * n matrix (n = number of features). The complexity of this inversion is
something like O (n ^ 2.5) to O (n ^ 3.2), depending on the implementation.
Indeed, if you create features like twice, you will create the time the
calculation comes between 2 ^ 2.5 and 2 ^ 3.2.
The good news here is that this equation is a linear equation. Which means it
easily handle a large training set and fit the memory.
After training your model, predictions will not be slow, and the complexity
will be simple, thanks to the linear model. It's time to dig dip and move on
into the procedures of training a linear regression model, which is always
used when large number of features and instances in the memory.
Gradient descent
This algorithm is a common algorithm used for optimization and providing
the best solution for various problems. The idea of this algorithm is to work
with the parameters in an iterative way, to make the cost function very
simple.
The gradient descent algorithm calculates the gradation of error using the
parameter theta, and it works with procedure of descending gradient. If the
gradient is equal to zero, you will reach the minimum.
Also, you should bear in mind that the size of the steps is vital for this
algorithm, because if small ( meaning the rate of learning) is slow, i.e it will
take longer time to cover everything that it needs to.
If the rate of learning is high, it will take less time to cover what’s needed,
and it gives optimal solution.
At times not all cost functions are easy there are some irregular functions that
make getting an optimal solution very hard. This problems are detected when
the local minimum and global minimum looks like the do in the following
figure
If you assign any of the two points on your curve, you will observe that
segment of the line will not join them at the same turn. This cost will look
like a task Bowl, which will happen if the features have many scales like the
image below.
Batch gradient descent
If you want to implement this algorithm, you must first calculate the gradient
of your cost function using theta parameters. If the value of the parameter
Theta has changed; you will need to know the changing rate of your cost
function. We can call this change by a partial derivative
We can calculate the partial derivation using the equations below:
But we will also use the following equations to calculate the partial
derivatives and the gradient vector together.
Tree classifiers
The next image illustrates the definition of a common target of collecting
functions that are simply for merging different classifiers into one-class
including a more generalization performance than each individual classifier
alone.
For example, suppose you have collected predictions from many experts.
Ensemble methods will allow us to merge these predictions by lots of experts
to get a prediction that is stronger than the predictions of each individual
expert. As you can see later in this chapter, there are a lot of different
methods for creating a combination of classifiers. In this part, we will
introduce one basic understanding of how ensemble works and why they are
common to achieve a good generalization performance.
In this chapter, we will work with the most popular ensemble method that
uses the majority voting principle. A lot of voting simply means we choose
the label that has been predicted by most classifiers (more than 50% votes
was achieved). For example, the word vote here is just binary class settings
only. However, generating a majority voting principle to multi-class setting is
not difficult
The principle is multi-class settings, called majority voting. After that, we
The class will select the label that received the most votes. The following
figure
Explains the concept of majority and majority voting for the 10 alliance
Classified where each unique symbol (triangle, square and circle) a
Unique class label:
Using the training set, we start by training m different classifiers (CC1,,…
8M).
Depending on the method, the ensemble can be made from several
classifications algorithms; For example, decision trees, support vector
machines, logistics regression classifier, and so much more. In fact, you can
use the same base classification algorithm fitting different subsets of the
training set. An instance of this method will be a random forest algorithm,
which combines many decisions ensemble ways to use majority voting.
To predict a class label by simple majority or plurality voting, we combine
these predicted the class labels of each individual classifier C j and select the
class label yˆ that got the most votes:
y m ˆ = ode {CC 1 2 () x x ,, ()), Cm () x}
For example, in a binary classification function where class 1 1 = - and class
2 1 = +, we can write a majority vote prediction.
Furthermore to explain why ensemble methods will work better than
individual classifications alone, let's apply the simple concepts of
combinatory. For the following example, we assume that all n base classifiers
for binary classification task have the same error rate, ε . Furthermore, we
assume that the classifiers are independent and does not relate to the error
rate. As you can see, we can only explain the error statistics of an ensembe of
the base classifiers as probability.