Essential Math for Data Science Thomas Nield pdf download
Essential Math for Data Science Thomas Nield pdf download
install download
https://ebookmeta.com/product/essential-math-for-data-science-
thomas-nield/
https://ebookmeta.com/product/essential-math-for-data-science-
third-early-release-1-2021-11-05-third-release-edition-thomas-
nield/
https://ebookmeta.com/product/essential-math-for-data-science-
take-control-of-your-data-with-fundamental-calculus-linear-
algebra-probability-and-statistics-1st-edition-hadrien-jean/
https://ebookmeta.com/product/essential-math-for-ai-hala-nelson/
https://ebookmeta.com/product/snow-s-huntsman-a-fairytale-
retelling-1st-edition-mila-crawford-aria-cole/
Think Python How to Think Like a Computer Scientist 2nd
Edition Allen B Downey
https://ebookmeta.com/product/think-python-how-to-think-like-a-
computer-scientist-2nd-edition-allen-b-downey-3/
https://ebookmeta.com/product/industrial-revolution-in-mexico-
sanford-a-mosk/
https://ebookmeta.com/product/berlitz-pocket-guide-italian-lakes-
travel-guide-ebook-5th-edition-berlitz/
https://ebookmeta.com/product/the-sami-world-1st-edition-sanna-
valkonen-editor/
https://ebookmeta.com/product/a-frequency-dictionary-of-
contemporary-arabic-fiction-core-vocabulary-for-learners-and-
material-developers-1st-edition-laila-familiar/
Machine learning and artificial intelligence with
industrial applications : from big data to small data
1st Edition Diego Carou
https://ebookmeta.com/product/machine-learning-and-artificial-
intelligence-with-industrial-applications-from-big-data-to-small-
data-1st-edition-diego-carou/
Essential Math for Data Science
Take Control of Your Data with Fundamental Linear
Algebra, Probability, and Statistics
With Early Release ebooks, you get books in their earliest form—the
author’s raw and unedited content as they write—so you can take
advantage of these technologies long before the official release of these
titles.
Thomas Nield
Essential Math for Data Science
by Thomas Nield
Copyright © 2022 Thomas Nield. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles
(http://oreilly.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
[email protected].
Copyeditor:
Proofreader:
Indexer:
Illustrator:
In the past 10 years or so, there has been a growing interest in applying
math and statistics to our everyday work and lives. Why is that? Does it
have to do with the accelerated interest in “data science” which Harvard
Business Review called “the Sexiest Job of the 21st Century”. Or is it the
promise of machine learning and “artificial intelligence” changing our
lives? Is it because news headlines are inundated with studies, polls, and
research findings, but unsure how to scrutinize such claims? Or is it the
promise of “self-driving” cars and robots automating jobs in the near future
?
I will make the argument that the disciplines of math and statistics have
captured mainstream interest because of the growing availability of data,
and we need math, statistics, and machine learning to make sense of it. Yes,
we do have scientific tools, machine learning, and other automations that
call to us like sirens. We are to blindly trust these “black boxes,” devices
and softwares we do not understand but we use them anyway.
While it is easy to believe computers are smarter than us (and this idea is
frequently marketed), the reality cannot be more the opposite. This
disconnect can be precarious on so many levels. Do you really want an
“algorithm” or “AI” performing criminal sentencing or driving a vehicle,
but nobody including the developer can explain why it came to a specific
decision? Explainability is the next frontier of statistical computing and AI.
This can only begin when we open up the “black box” and uncover the
math.
You may also ask how can a developer not know how their own algorithm
works? We will talk about that in the second half of the book when we
discuss machine learning techniques, and emphasize why we need to
understand the math behind the black boxes we build.
To another point, the reason data is being collected on a massive scale is
largely due to connected devices and their presence in our everyday lives.
We no longer solely use the internet on a desktop or laptop computer. We
now take it with us in our smart phones, cars, and household devices. This
has subtly enabled a transition over the past two decades. Data has now
evolved from an operational tool to something that is collected and
analyzed for less defined objectives. A smartwatch is constantly collecting
data on our heart rate, breathing, walking distance, and other markers. Then
it uploads that data to a cloud to be analyzed alongside other users. Our
driving habits are being collected by computerized cars, and being used by
manufacturers to collect data and enable “self-driving” vehicles. Even
“smart toothbrushes” are finding their way into drug stores, which track
brushing habits and store that data in a cloud. Whether smart toothbrush
data is useful and essential is another discussion!
All of this data collection is permeating every corner of our lives. It can be
overwhelming, and a whole book can be written on privacy concerns and
ethics. But this availability of data also creates opportunities to leverage
math and statistics in new ways, and create more exposure outside
academic environments. We can learn more about the human experience,
improve product design and application, and optimize commercial
strategies. If you understand the ideas presented in this book, you will be
able to unlock the value held in our data-hording infrastructure. This does
not imply that data and statistical tools are a silver bullet to solve all the
world’s problems, but it has given us new tools that we can use. Sometimes
it is just as valuable to recognize certain data projects as rabbit holes, and
realize efforts are better spent elsewhere.
This growing availability of data has made way for “data science” and
“machine learning” to become demanded professions. We define essential
math as an exposure to probability, linear algebra, statistics, and machine
learning. If you are seeking a career in data science, machine learning, or
engineering, these topics are necessary. I will throw in just enough college
math, calculus, and statistics necessary to better understand what goes in the
“black box” libraries you will encounter.
With this book, I aim to give readers an exposure to different mathematical,
statistical, and machine learning areas that will be applicable to real-world
problems. The first four chapters cover foundational math concepts
including practical calculus, probability, linear algebra, and statistics. The
last three chapters will segue into machine learning. The ultimate purpose
of teaching machine learning is to integrate everything we learn, and
demonstrate practical insights in using machine learning and statistical
libraries beyond a “black box” understanding.
The only tool that is needed to follow examples is a Windows/Mac/Linux
computer and a Python 3 environment of your choice. The primary Python
libraries we will need are numpy, scipy, sympy, and sklearn. If you
are unfamiliar with Python, it is a friendly and easy-to-use programming
language with massive learning resources behind it. Here are some I
recommend:
This book will not make you an expert or give you PhD knowledge. I do
my best to avoid mathematical expressions full of Greek symbols, and
instead strive to use plain English in its place. But, what this book will do is
make you more comfortable talking about math and statistics, giving you
essential knowledge to navigate these areas successfully. I believe the
widest path to success is not having deep, specialized knowledge in one
topic, but instead having exposure and practical knowledge across several
topics. That is the goal of this book, and you will learn just enough to be
dangerous and ask those once elusive critical questions.
So let’s get started!
Chapter 1. Basic Math and
Calculus Review
We will kick off the first chapter covering what numbers are and how
variables and functions work on a Cartesian system. We will then cover
exponents and logarithms. After that we will learn the two basic operations
of calculus: derivatives and integrals.
Before we dive into the applied areas of essential math such as probability,
linear algebra, statistics, and machine learning, we should probably review
a few basic math and calculus concepts. Before you drop this book and run
screaming, do not worry! I will present how to calculate slopes and areas
for a function in a way you were probably not taught in college. We got
Python on our side, not a pencil and paper.
I will make these topics as tight and practical as possible, focusing only on
what will help us in later chapters and fall under the “essential math”
umbrella.
THIS IS NOT A FULL MATH CRASH COURSE!
This is by no means a comprehensive review of high school and college math. If you
want that, a great book to check out is No Bullshit Guide to Math and Physics by Ivan
Savov. The first few chapters contain the best crash course on high school and college
math I have ever seen. The book Mathematics 1001 by Dr. Richard Elwes has some
great content as well, and in bite-sized explanations.
Number Theory
What are numbers? I promise to not be too philosophical in this book, but
are numbers not a construct we have defined? Why do we have the digits 0
through 9, and not have more digits than that? Why do we have fractions
and decimals and not just whole numbers? This area of math where we
muse about numbers and why we designed them a certain way is known as
number theory.
Number theory goes all the way back to ancient times, where
mathematicians study different number systems and why we have accepted
them the way we do today. Here are different number systems that you may
recognize:
Natural Numbers
These are the numbers 1, 2, 3, 4, 5… and so on. Only positive numbers
are included here, and are the earliest known system. Natural numbers
are so ancient cavemen scratched tally marks on bones and cave walls
to keep records.
Whole Numbers
Adding to natural numbers, the concept of “0” was later accepted and
we call these “whole numbers.” The Babylonians also developed the
useful idea for place-holding notation for empty “columns” on numbers
greater than 9, such as “10”, “1000”, or “1090.” Those zeros indicate no
value occupying that column.
Integers
Integers include positive and negative whole numbers as well as 0. We
may take them for granted, but ancient mathematicians were deeply
distrusting of the idea of negative numbers. But when you subtract 5
from 3, you get -2. This is useful especially when it comes to finances
where we measure profits and losses. In 628 AD, an Indian
mathematician named Brahmagupta showed why negative numbers
were necessary for arithmetic to progress, and therefore integers became
accepted.
Rational Numbers
Any number that you can express as a fraction, such as , is a rational
2
number. This includes all finite decimals and integers since they can be
expressed as fractions too, such as687
100
= 6. 87 and
2
1
= 2 respectively.
They are called rational because they are ratios. Rational numbers were
quickly deemed necessary bececause because time, resources, and other
quantities could not always be measured in discrete units. Milk does not
always come in gallons. We may have to measure it as parts of a gallon.
If I run for 12 minutes, I cannot be forced to measure in whole miles
when in actuality I ran 9
10
of a mile.
Irrational Numbers
Irrational numbers cannot be expressed as a fraction. This includes the
famous Pi π, square roots of certain numbers like √2, and Euler’s
number e which we will learn about later. These numbers have an
infinite number of decimal digits, such as
π = 3. 141592653589793238462. . .
Real Numbers
Real numbers include rational as well as irrational numbers. In
practicality, when you are doing any data science work you can treat
any decimals you work with as real numbers.
In data science, you will find most (if not all) your work will be using
natural numbers, integers, and real numbers. Imaginary numbers may be
encountered in more advanced use cases such as matrix decomposition,
which we will touch on in Chapter 4.
Order of Operations
Hopefully you are familiar with order of operations which is the order you
solve each part of a mathematical expression. As a brief refresher, recall
you evaluate components in parantheses, followed by exponents, then
multiplication, division, addition, and subtraction. You can remember the
order of operations by the mnemonic device PEMDAS (Please Excuse My
Dear Aunt Sally) which corresponds to the ordering paranthesis, exponents,
multiplication, division, addition, and subtraction.
Take for example this expression:
2
(3 + 2)
2* − 4
5
Next we solve the exponent, which we can see is squaring that 5 we just
summed. That is 25.
25
2* − 4
5
5
50
50
− 4
5
Next we will perform the division, dividing 50 by 5 which will yield 10.
10 − 4
While both examples are technically correct, the latter one is more clear to
us easily confused humans. If you or someone else makes changes to your
code, the paranthesis provide an easy reference of operation order as you
make changes. This provides a line of defense against code changes to
prevent bugs as well.
Variables
If you have done some scripting with Python or another programming
language, you have an idea what a variable is. In mathematics, a variable is
a named placeholder for an unspecified or unknown number.
You may have a variable x representing any real number, and you can
multiply that variable without declaring what it is. In Example 1-3 we take
a variable input x from a user, and multiply it by 3.
Example 1-3. A variable in Python that is then multiplied
x = int(input("Please input a number\n"))
product = 3 * x
print(product)
There are some standard variable names for certain variable types. If these
variable names and concepts are unfamiliar, no worries! But the rest of you
readers might recognize we use theta θ to denote angles and beta β for a
parameter in a linear regression. Greek symbols make awkward variable
names in Python, so we would likely name these variables theta and
beta in Python as shown in Example 1-4.
Example 1-4. Greek variable names in Python
beta = 1.75
theta = 30.0
Note also that variable names can be subscripted so that several instances of
a variable name can be used. For practical purposes, just treat these as
separate variables. If you encounter variables x1, x2, and x3, just treat them
as three separate variables as shown in Example 1-5.
Example 1-5. Expressing subscripted variables in Python
x1 = 3 # or x_1 = 3
x2 = 10 # or x_2 = 10
x3 = 44 # or x_3 = 44
Functions
Functions are expressions that define relationships between two or more
variables. More specifically, a function takes input variables (also called
domain variables or independent variables), plugs them into an
expression, and then results in an output variable (also called dependent
variable).
Take this simple linear function y = 2x + 1. For any given x value, we
solve the expression with that x to find y. When x = 1, then y = 3. When x =
2, y = 5. When x = 3, y = 7 and so on as shown in Table 1-1.
y = 2x + 1
T
a
b
l
e
1
-
1
.
D
if
f
e
r
e
n
t
v
a
l
u
e
s
f
o
r
y
=
2
x
+
1
x 2x + 1 y
0 2(0) + 1 1
1 2(1) + 1 3
2 2(2) + 1 5
3 2(3) + 1 7
Functions are useful because they help predict the relationship between
variables, such as how many fires y can we expect at x temperature. We will
use linear functions to perform linear regressions in Chapter 5.
Another convention you may see for the dependent variable y is to
explicitly label it a function of x, such as f (x). So rather than express a
function as y = 2x + 1 we can also express it as:
f (x) = 2x + 1
Example 1-6 shows how we can declare a mathematical function and iterate
it in Python.
Example 1-6. Declaring a linear function in Python
def f(x):
return 2 * x + 1
x_values = [0, 1, 2, 3]
for x in x_values:
y = f(x)
print(y)
When dealing with real numbers, a subtle but important feature of functions
is they often have an infinite number of x values and resulting y values. Ask
yourself this: how many x values can we put through the function
y = 2x + 1 ? Rather than just 0, 1, 2, 3… why not 0, .5, 1, 1.5, 2, 2.5, 3 as
shown in Table 1-2 below?
T
a
b
l
e
1
-
2
.
D
if
f
e
r
e
n
t
v
a
l
u
e
s
f
o
r
y
=
2
x
+
1
x 2x + 1 y
0.0 2(0) + 1 1
0.5 2(.5) + 1 2
1.0 2(1) + 1 3
1.5 2(1.5) + 1 4
2.0 2(2) + 1 5
2.5 2(2.5) + 1 6
3.0 2(3) + 1 7
10
of a step? We can make these steps
infinitely small effectively showing y = 2x + 1 is a continuous function,
where for every possible value of x there is a value for y. This segues us
nicely to visualize our function as a line as shown in Figure 1-1.
Figure 1-1. Graph for function y = 2x + 1
When we plot on a two-dimensional plane with two number lines (one for
each variable) it is known as a Cartesian plane, x-y plane, or coordinate
plane. We trace a given x value and then look up the corresponding y value,
and plot the intersections as a line. Notice that due to the nature of real
numbers (or decimals, if you prefer), there are an infinite number of x
values. This is why when we plot the function f(x) we get a continuous
line with no breaks in it. There are an infinite number of points on that line,
or any part of that line.
If you want to plot this using Python, there are a number of charting
libraries from Plotly to matplotlib. However, SymPy gives us a quick, clean
way to plot a function. It uses matplotlib so make sure you have that
package installed, otherwise it will print an ugly text-based graph to your
console. After that, just declare the x variable to SymPy using
symbols(), declare your function, and then plot it as shown in
Example 1-7 and Figure 1-2.
Example 1-7. Charting a linear function in Python using SymPy
from sympy import *
x = symbols('x')
f = 2*x + 1
plot(f)
Figure 1-2. Using SymPy to graph a linear function
Example 1-8 and Figure 1-3 are another example showing the function
y = x + 1.
2
x = symbols('x')
f = x**2 + 1
plot(f)
Figure 1-3. Using SymPy to graph an exponential function
Notice in Figure 1-3 we do not get a straight line but rather a smooth,
symmetrical curve known as a parabola. It is continuous but not linear, as it
does not produce values in a straight line. Curvy functions like this are
mathematically harder to work with, but we will learn some tricks to make
it not so bad.
CURVILINEAR FUNCTIONS
When a function is continuous but curvy, rather than linear and straight, we call it a
curvilinear function.
Note that functions can utilize multiple input variables and not just one. For
example, we can have a function with independent variables x and y. Note
that y is not dependent like in previous examples.
f (x, y) = 2x + 3y
x, y = symbols('x y')
f = 2*x + 3*y
plot3d(f)
Summations
I promised not to use equations full of Greek symbols in this book.
However, there is one that is so common and useful that it would be remiss
to not cover it. A summation is expressed as a sigma Σ and adds elements
together.
For example, if I wanted to iterate the numbers 1 through 5, multiply each
by 2, and sum them here is how I would express that using a summation.
Example 1-10 shows how to execute this in Python.
5
∑ 2i
i=1
∑ 10x i
i=1
# specify n as 5,
# iterating the numbers 1 through 5
up_to_5 = summation.subs(n, 5)
print(up_to_5.doit()) # 30
Exponents
Exponents multiplies a number by itself a specified number of times. When
you raise 2 to the 3rd power (expressed as 2 using 3 as a superscript), that
3
The base is the variable or value we are exponentiating, and the exponent
is the number of times we multiply the base value. For the expression 2 , 2
3
together. Observe what happens below when I expand the exponents with
simple multiplication, and then consolidate into a single exponent:
2 3 2+3 5
x x = (x*x)*(x*x*x) = x = x
When we multiply exponents together with the same base, we simply add
the exponents which is known as the product rule. Note that the base of all
multiplied exponents must be the same for the product rule to apply.
Let’s explore division next. What happens when we divide x by x ? 2 5
2
x
5
x
x*x
x*x*x*x*x
x*x*x
1
−3
= x
3
x
As you can see above, when we divide x by x we can cancel out two x’s
2 5
algebra rules too much, here is what happens. When a factor exists in both
the numerator and denominator, we can cancel out that factor.
This is a good point to introduce negative exponents, which is another way
of expressing an exponent operation in the denominator of a fraction. To
demonstrate, 1
x
is the same as x .
3
−3
1 −3
= x
3
x
Tying back the product rule, we can see it applies to negative exponents too.
To get intuition behind this, let’s approach this problem a different way. We
can express this division of two exponents by making the “5” exponent of
x negative, and then multiplying it with x . When you add a negative
5 2
x = symbols('x')
expr = x**2 / x**5
print(expr) # x**(-3)
Now what about fractional exponents? They are just an alternative way to
represent roots, such as the square root. As a brief refresher, a square root of
4 asks “what number multiplied by itself will give me 4?”, which of course
is 2. Note here that 4 is the same as √4.
1/2
1/2
4 = √4 = 2
Cubed roots are similar to square roots, but they seek a number multiplied
by itself 3 times to give a result. A cubed root of 8 is expressed as √8, and 3
asks “what number multiplied by itself 3 times gives me 8”? This number
would be 2 because 2*2*2 = 8. In exponents, a cubed root is expressed as a
fractional exponent, and √8 can be re-expressed as 8 .
3 1/3
1/3 3
8 = √8 = 2
To bring it back full circle, what happens when you multiply the cubed root
of 8 three times? This will undo the cubed root and yield us 8.
Alternatively, if we express the cubed root as fractional exponenents 8 , it 1/3
would simplify to 8 .6
2
3 3*2 6
(8 ) = 8 = 8
If you are skeptical why this is, try expanding it and you will see the sum
rule makes it clear:
2
3 3 3 3+3 6
(8 ) = 8 8 = 8 = 8
687.2913. This may feel unintuitive, and understandably so! In the interest
of time we will not dive deep into this as it requires some Calculus. But
essentially, we can calculate irrational exponents by approximating with a
rational number. This is effectively what computers do since they can only
compute to so many decimal places anyway.
For example Pi π has an infinite number of decimal places. But if we take
the first 11 digits, 3.1415926535, we can approximate Pi as a rational
number 31415926535 / 10000000000. Sure enough, this gives us
approximately 687.2913 which should approximately match any calculator.
31415926535
π
8 ≈ 8 10000000000
≈ 687. 2913
Logarithms
A logarithm is a math function that finds a power for a specific number
and base. It may not sound interesting at first, but it actually has many
applications. From measuring earthquakes to managing volume on your
stereo, the logarithm is found everywhere. It also finds its way into machine
learning and data science a lot. As a matter of fact, logarithms will be a key
part of logistic regressions in Chapter 6.
Start your thinking by asking “2 raised to what power gives me 8?” One
way to express this mathematically is to use an x for the exponent:
x
2 = 8
log 2 8 = x
As you can see in the logarithm expression above, we have a base 2 and are
finding a power to give us 8. More generally, we can re-express a variable
exponent as a logarithm:
x
a = b
log a b = x
Multiplication x
m
*x
n
= x
m+n
log(a*b) = log(a) + log(b)
Division
m
x m−n a
n = x log ( ) = log (a) − log (b)
x b
Exponentiation (x
m
)
n
= x
mn
log (a
n
) = n*log (a)
Zero Exponent x
0
= 1 log(1) = 0
Inverse x
−1
=
1
x
log (x
−1
) = log(
1
x
= −log (x)
Here is how I like to discover Euler’s number. Let’s say you loan $100 to
somebody with 20% interest annually. Typically interest will be
compounded monthly, so the interest each month would be
. 20/12 =. 01666. How much will the loan balance be after two years? To
keep it simple, let’s assume the loan does not require payments (and no
payments are made) until the end of those two years.
Putting together the exponent concepts we learned so far (or perhaps pulling
it out a finance textbook), we can come up with a formula to calculate
interest. It consists of a balance A for a starting investment P, interest rate r,
time span t (number of years), and periods n (number of months in each
year). Here it is as follows:
nt
r
A = P × (1 + )
n
12*2
. 20
100*(1 + ) = 148. 6914618
12
If you want to do this in Python, try it out with the code in Example 1-15.
Example 1-15. Calculating compound interest in Python
from math import exp
p = 100
r = .20
t = 2.0
n = 12
a = p * (1 + (r/n))**(n * t)
365*2
. 20
100*(1 + ) = 149. 1661279
365
8760*2
. 20
100*(1 + ) = 149. 1817886
8760
Okay we are only gaining smaller and smaller fractions of a cent the more
frequently we compound. So if I keep making these periods infinitely
smaller to the point of compounding continuously, where does this lead to?
Let me introduce you to Euler’s number e, which is approximately 2.71828.
Here is the formula to compound “continuously,” meaning we are
compounding nonstop:
rt
A = P *e
Returning to our example, let’s calculate the balance of our loan after 2
years if we compounded continuously:
rt
A = P *e
.20*2
A = 100*e = 149. 1824698
Okay this is not too surpising considering compounding every minute got
us a balance of 149.1824584. That got us really close to our value of
149.1824698 when compounding continuously.
Typically you use e as an exponent base in Python, Excel, and other
platforms using the exp() function. You will find that e is so commonly
used, it is the default base for both exponent and logarithm functions.
Example 1-16 calculates continuous interest in Python using the exp()
function.
Example 1-16. Calculating continuous interest in Python
from math import exp
a = p * exp(r*t)
print(a) # prints 149.18246976412703
rt
A = P *e
n
) as n forever gets bigger and bigger, thus approaching infinity.
Try experimenting with increasingly large values for n. By making it larger
and larger you will notice something:
n
1
(1 + )
n
100
1
(1 + ) = 2. 70481382942
100
1000
1
(1 + ) = 2. 71692393224
1000
10000
1
(1 + ) = 2. 71814592682
10000
10000000
1
(1 + ) = 2. 71828169413
10000000
Natural Logarithms
When we use e as our base for a logarithm, we call it a natural logarithm.
Depending on the platform, we may use ln() instead of log() to specify
a natural logarithm. So rather than express a natural logarithm expressed as
log 10 to find the power raised on e to get 10, we would shorthand it as
e
ln(10).
log e 10 = ln (10)
Limits
As we have seen with Euler’s number, some interesting ideas emerge when
we forever increase or decrease an input variable and the output variable
keeps approaching a value but never reaching it. Let’s formally explore this
idea.
Take this function which is plotted in Figure 1-5:
1
f (x) =
x
Figure 1-5. A function that forever approaches 0 in either direction but never reaches 0
x
as x
approaches infinity ∞.
Example 1-18. Using SymPy to calculate limits
from sympy import *
x = symbols('x')
f = 1 / x
result = limit(f, x, oo)
print(result) # 0
As you have seen, we discovered Euler’s number e this way too. It is the
result of forever extending n into infinity for this function.
n
1
lim (1 + ) = e = 2. 71828169413. . .
n→∞ n
n = symbols('n')
f = (1 + (1/n))**n
result = limit(f, n, oo)
print(result) # E
print(result.evalf()) # 2.71828182845905
THE POWER OF SYMPY
SymPy is a powerful and fantastic computer algebra system (CAS) for
Python that uses exact symbolic computation rather than approximate
computation using decimals. It’s helpful for those situations you would
use “pencil and paper” to solve math and Calculus problems, with the
benefit of using familiar Python syntax. Rather than represent the
square root of 2 by approximating 1.4142135623730951, it will
preserve it as exactly sqrt(2).
So why not use SymPy for everything math-related? While we will use
it throughout this book, it is important to still be comfortable doing
Python math with plain decimals, as SciKit-Learn and other data
science libraries take this approach. It is much faster for computers to
use decimals rather than symbols. But keep SymPy in your back pocket
as your advantage, and do not tell your high school and college-age kids
about it. They can literally use it to do their math homework.
https://docs.sympy.org/latest/tutorial/intro.html
Derivatives
Let’s go back to talking about functions and look at them from a Calculus
perspective, starting with derivatives. A derivative tells the slope of a
function, and it is useful to measure the rate of change at any point in a
function.
Why do we care about derivatives? They are often used in machine learning
and other mathematical algorithms, especially with gradient descent. When
the slope is 0, that means we are at the minimum or maximum of an output
variable. This concept will be useful later when we do linear regression,
logistic regression, and neural networks.
But let’s start with a simple example. A derivative provides the slope at that
given x value. Let’s take a look at the function f (x) = x in Figure 1-6.
2
How “steep” is the curve at x = 2?
Figure 1-6. Observing steepness at a given part of the function
Other documents randomly have
different content
cheering beams once more upon the rippling waters; and, as the
willows on the banks of the noble Trent waved in the gentle breeze,
and the rich meadows on the border of the river sent forth their
reviving fragrance, Zed lifted up his head, while his hand plied the
oar, and in the fulness of a happy heart thus opened the
conversation for the day:—
"Well, I wouldn't change places with the king on his throne, Phil;
I don't believe there's a happier pair than you and I, Phil, in the wide
world. And yet, now, as wild a scheme as that was of mine last
night, I cannot help wishing, this morning, that we had some o' that
gold at this moment. I could like to try my hand, Phil, as old and
inexperienced as it is in such work, at making some part of the world
happier."
"And so could I, Zed," said Phil; "and now don't you think that
my godmother's grandfather's plan of dividing the land would be a
good one, and tend to make the world happier, if it were carried into
effect?"
"The deuce is in you, Phil, for always bringing up that plan of
your godmother's grandfather!" said old Zed; "why, the plan may be
good enough, Phil; but how can it be brought about?"
"How can you get the gold?" retorted Phil.
"Good!" said Zed, with a hearty laugh; "i'faith, Phil, one scheme
is as likely to be brought about as the other: but, take hold of that
end o' the net, Phil, for I see a famous pike or two, darting about;
and, you know, we must try to get something to-day."
The net was thrown out, but failed; and, what was most
unusual, the labour of Zed and Phil was continued for several hours
without the capture even of a solitary eel. Phil often thought Zed
threw out the net very wildly, and imagined the liquor he took at the
wedding had not yet spent its effects on him; but the blind man
could not be sure, for Zed seemed resolutely taciturn.
'Twas about ten in the forenoon that Phil felt the little boat was
"brought up,"—he thought in an inlet, or small creek, on the Lindsey
side of the Trent, after they had laboured with nets and lines ever
since a little after sunrise, and all without a single instance of
success.——
"Phil, d'ye know why I've pulled in here this morning?" said Zed,
as he was mooring the skiff.
"No, by'r leddy!" answered the old-fashioned fiddler, "I can't tell,
for the life of me! but it seems to me that you've pulled in at Burton
Folly,—have you not, Zed? and what's the meaning of it?"
"Look sharp, Phil!" said Zed, briskly helping Phil out of the boat,
"we've had hard luck in the water this morning, but we'll try our luck
on land for once: we'll have one or two of 'Squire Hutton's pheasants
before we leave the holt."
"'Don't say so till you're sure!'" said Phil, for that was a common
saying with him, as I hinted before; "I wish I could look sharp, as
you bid me, Zed,—for I'll be hanged if you are not tearing my poor
legs among the whins, like old pork, as the saying goes."
"The deuce I am!" exclaimed Zed, slackening his pace; "I
wouldn't hurt you, for all the world, Phil: but you know it's worth
while trying to catch a pheasant or two,—they're such fine game."
"I don't know, Zed," rejoined Phil, "whether it be worth while or
not: we may get into a scrape by it, as old as we are, and——"
"Pshaw!" cried Zed, with an air of resolute contempt; "come
along, Phil!—come along!"
"O come along, ay!" said Phil; "I shall go with you, if you go to
the very devil!—but then I don't see what's the use of going there,
yet,—as old 'Squire Pimpleface used to say, when he gave up playing
cards at Saturday midnight, and refused, ever after to play on
Sunday mornings——"
"Hush!" said Zed, stopping short,—"my eyes! why, that must be
the gamekeeper! No, it isn't:—but we had better lie down, Phil."
"Down be it then!" said Phil, prostrating himself among the long
grass, while the old fisherman followed his example.
"Now, tell me," continued the fiddler, in a whisper, as they lay
along among the grass, and the fisherman was anxiously keeping
the look-out,—"tell me how you intend to catch the pheasants, Zed:
you know you've no gun; and you can't catch 'em with a net in open
day,—besides you haven't brought the net out of the boat, have
you?"
"Pooh!" replied Zed, "why, I've heard my father say that 'Squire
Hutton's pheasants used to be as tame as bantam cocks, even in his
time. We may catch 'em, bless your soul! ay, easily! And, if not, I'm
sure I could hit one and knock it down with my hat."
The blind fiddler burst into an uncontrollable fit of laughter on
hearing this artless declaration from his ancient companion.
"Zowks, Zed!" he exclaimed at last, "thou hast got some wild
maggots, for sure, into thy head this morning! prythee look out
again, and see if the coast be clear; for the sooner we shove off in
the boat again the better, I'm very sartain."
"Confound that fellow! he's coming this way," said Zed, in a
voice of alarm. And, indeed, there now seemed to be cause for fear,
seeing that a tall man, with a gun on his shoulder, was hastening
down the hill, apparently in a direction towards the foolish hiding-
place of the fiddler and the fisherman.
"What shall we do, Phil?" asked Zed, in the next breath.
"Cut and run!" cried Phil, and sprung up as nimbly as a hare
when you stumble upon her seat.
"Come along, then!" said Zed; and, seizing his blind companion
by the hand, away they galloped, as fast as their old limbs would
wag down the declivity, to the boat.
Zed pushed Phil, head over heels, into the skiff, and, jumping in
himself, scudded away out of the creek as fast as he could possibly
"scull," or turn the oar, at the boat's stern, after the manner of a
screw, in the water. The gamekeeper came up the water-side, and
approached within a few yards of the boat, before the adventurers
could make their way back into the broad Trent.
"You are two very old men," said he, lifting up his hand in a
warning manner, "or I would certainly detain you, and have you
indicted for trespass. Take care you are never found here again!"
Neither of the old men made a word of reply; and the
gamekeeper walked away.
"Detained us!—would he?" said Zed, in a low, but contemptuous
tone, as soon as they had gained the breadth of the river, and the
gamekeeper was sufficiently out of hearing,—"how could he have
done that, if he had tried, think you, Phil?"
"Never mind talking about that, Zed,—let us be content with
having got out of a scrape," answered blind Phil: "but now tell me,
Zed," he continued, putting an oar on one side of the boat, and
taking his share of labour with as easy naturalness as if he had
possessed the most perfect eyesight,—"what it could be that put
such a wild notion into your head as to lead you to think of catching
a pheasant with your hand, or of knocking it down with your hat:—
why didn't you take a bit o' salt to throw on its tail, Zed?" concluded
the fiddler, and burst into another fit of helpless laughter.
"He—he—he!" said the fisherman, forcing a faint laugh, to
conceal his shame and vexation;—"never mind,—never mind that,
Phil!" he said,—"my old head gets weak, or I might ha' been sure it
would be a fool's errand. Was not it a mighty piece of impudence in
that thief of a gamekeeper, think you, to tell us he had a mind to
indict us for 'trespass,' as the Jack-in-office called it?—what harm
could we do, Phil, by just trampling among the grass for a few
minutes?"
"Poor folks are not allowed to tread upon rich folks' land, you
know, Zed, without their leave," said the fiddler.
"No; but isn't it hard that there should be such a law, Phil?" said
the fisherman.
"Why, as for that, Zed," replied Phil, "my godmother's
grandfather,—who, my godmother used to tell me, was a famous
scholar in his day,—used to say that all the land belonged to every
body, and that nobody ought ever to have called an acre his own, in
particular. If that had been the case, you see, Zed, the gamekeeper
could not have threatened to indict you and me for trespass this
morning."
"No more he could, Phil," rejoined Zed; "but, then, if the land
belonged to every body,—in such a way that nobody could say an
acre belonged to him, only,—why, how would the land be ploughed
and the grain sown,—for you know the old saying, Phil, 'What's
every body's business is nobody's business?'"
"My godmother's grandfather used to say that people ought to
join in companies to do it," replied Phil: "it's a subject I am not
master of to the extent he was, by all account; but I feel sure of one
thing, Zed,—that the world could not have been much worse divided
than it is at present, since the rich have so much land among them,
and the poor have none."
"You are right there, Phil, beyond a grain o'doubt," rejoined Zed.
"And my godmother's grandfather used to say besides,"
continued the fiddler, "that God Almighty gave the world to every
body, and that the rich had stolen the poor's share of the land—for
God Almighty never left them destitute."
"Then, in that case, Phil," said the fisherman, "there is a share,
each, belonging to you and to me: and then it seems doubly hard to
be told, when your own share has been stolen from you, that you
shall be indicted for trespassing upon the land of one that has more
than his share—doesn't it, Phil?"
"Right, Zed, right!" returned Phil; "I'm pleased to find you relish
a bit of sensible talk, now and then; and can you deny, now, that
that plan of my godmother's grandfather would be a real good one,
and tend to make every body happy. Place all the folks in the world
on a level, Zed,—and let every man take his fair share in ploughing
and tilling, you know, Zed,—and then let every man share in cutting
the corn,—and all would have a fair title to eat it. You must see this
to be fair—quite fair, Zed?"
"Fair enough, no doubt," replied the fisherman; "but then, Phil,—
as I always ask you, but you never answer me,—how can you
contrive to bring all this about?"
"Nay, now, you don't argue fair!" answered Phil; and it was the
only answer he had, like many more learned proposers of good
theories.
"A plague on all such gibberish!" exclaimed Zed, "we shall want
but a small share of any thing long, and if we don't get our fair six
feet of land when we have done sailing, why, we can rest very well
in Davy Jones's locker. Where's the use of bothering our old brains
with such crabbed matters?"
"Ods bobs and bodikins!" replied Phil, "but I think you are about
right, Zed: I must own it's only a simple sort of a thing for you and I
to be troubling our heads about great folks and their lands."
"I' faith, you talk sense, Phil!" said Zed; "confound the great
folks! let 'em take their land! We've managed to push along through
threescore summers and more, and we can manage to get through,
I think, now. But, swape in, Phil! for we're just alongside
Littleborough again, and I'm so hungry that I feel inclined to step on
shore, and ask for a bite of the wedding-cake this morning: I'll
warrant 'em they'll be keeping up the merriment yet."
"Promise me one thing, though, Zed," said Phil,—"that you'll take
no more rum, if they offer it you, and that you won't stay longer
than a couple of hours or so."
"Don't think I shall play the fool twice over!" retorted Zed; "I'll
warrant it I'll come away as sober as a judge this time, and take no
more fool's tricks into my head to-day."
"'Don't say so till you're sure!'" observed Phil, in his usual sly
way; but Zed did not answer, for they were now at shore, and the
fisherman had leaped out, and was once more mooring the little
boat.
It is hardly necessary to relate that Zed found it impossible to
keep his hasty promise of a very short stay, seeing that the
"Weddingers" were "keeping it up" in true old-fashioned style, and
Phil's fiddle became, right soon, the very soul of their merriment.
Phil, however, had made his mind up, and succeeded, though with
great effort, in getting his old companion once more fairly afloat and
on the way home about an hour before sunset. Although Zed had,
indeed, the virtue to refuse the parting cup of rum, when it was
offered, yet his old noddle was far from being its own perfect
master, by reason of his frequent revisitations of the ale-pottle; and
the first mile on the water was all music of the most gleeful nature
with the old voyagers. "Indeed," as Phil himself used to say, when
talking about it, "we had each of us whetted our whistles till will-ye,
nil-ye, we must pipe, and couldn't help it!" They were trolling forth,
for the last time, their old burthen of
when the report of a gun, and the sudden flight of a drooping heron
across the Trent, arrested their music.
"By Jingo! she's a dead bird, in three minutes!" exclaimed Zed;
"mark how her right wing droops, Phil!"
"I wish I could mark it," said Phil; "but you always forget that my
poor old eyes are blanks, when you've——"
"There she goes, plop among the osiers!" cried Zed, in an
ecstasy; "pull away to the larboard, Phil. I'll have her in a twink."
"'Don't say so till you're sure!'" observed Phil, but pulled away
like a dragon in the direction recommended by his companion,
nevertheless.
Zed leaped out of the boat in a confounded hurry, when he
thought it was near enough for him to gain the shore; but he leaped
out too soon, for he fell flat on his face among the "warp," as the
mud of the Trent is called in Lincolnshire, and floundered like a flat
fish when it has been left by the water in a situation where it cannot
get away.
"Holloa! what, in the name o' bad luck, are you about?" cried
Phil, hearing poor Zed make a mighty scuffle among the mud.
Zed made no answer, but kept struggling on; for the fact was,
that he was so eager to secure the bird, that he had succeeded in
laying hold of one of its legs, and, keeping hold, prevented himself
from rising. The heron and Zed made a desperate flapping and
floundering, insomuch that Phil roared out, more than once,—
"What, in the name of heaven and earth, are you about, I say,
Zed?"
"Keep the boat in shore," cried Zed, with his mouth half filled
with mud; "I shall have her in another minute."
"'Don't say so till you're sure!'" retorted Phil again; and just then
the sportsman who had shot the heron jumped out of his boat on a
firmer part of the strand, and, running along the bank, arrived at the
spot where Zed was struggling with the bird. He struck off Zed's hold
of the fowl with a slight blow from his fowling-piece, and bore away
the bird in triumph. Zed slipped into the Trent, and went souse over
head, but rose instantly, and clambered into the boat. He vented his
disappointment and vexation against the sportsman in no very
gentle terms, while the sportsman mocked him from the bank; and,
when the captor of the heron stepped into his boat, Zed urged Phil
to pull away, that they might capsize the fellow, and give him a
ducking, as he said in his foolish haste. But Phil was always Zed's
better angel, though he was but a blind old fiddler. "No, no, Zed," he
cried, "you shall not go that way. Let us make for home, that you
may get to the fire-side. I say you shall not go—and I mean it, too."
Nobody in the world could control Zed Marrowby but Phil Garret,
when old Zed was in his fuddled freaks; and even Phil could not
always succeed; but Zed's wet shirt helped to cool his choler in this
instance.
"To old Nick with the fellow, and his heron-sue!" cried Zed,
pulling in the same direction with Phil; "I'll e'en let him take his live
lumber: what good will it do him?"
"Just as the fox said of the grapes, when he couldn't reach 'em
—'Hang 'em! they're as sour as crabs!'" rejoined Phil; "but that was
what I said to myself, when you were struggling so hard to get the
useless fowl; and what good would it have done you, Zed?"
"Hang me, if I know, exactly!" replied Zed, looking foolish, and
wishing himself in a corner.
"You wouldn't like to eat a heron-sue, for they're as rank as
stinking fish, I've heard say," continued Phil; "and what else you
would have done with it I'm quite at a loss to guess: but never mind,
Zed, you've got a cooler, now,—and I think you won't be so hot
again for some time to come."
"Well, well, it's all in our lifetime," said Zed, resolving to be
cheerful; "only pull away, and let us get to our own fire-side, that I
may dry my old skin, there's a jolly fellow!"
"So I will, Zed," replied Phil, and doubled the force of his strokes
at the oar; "but I hope you'll promise me not to resume your gold-
digging when we land under the old castle-walls."
"I will, I will, Phil,—and so don't banter me any more; I shall be
a cooler man for some time to come, after this, depend on't,"
answered Zed, with his teeth chattering.
And Zed spoke as truly as ever a prophet spoke, and much more
truly than many; for, although he got well warmed ere he went to
bed, yet his participation of so much extra liquor at the wedding, his
foolish freak at money-digging the preceding night, and his cold bath
to conclude, operating together upon his aged frame, produced
rheumatic effects which never left him.
Zed Marrowby and Phil Garrett left their voyaging at the close of
that summer. True, they made all fit and industrious preparation for
the next spring; and Zed's heart was gleefully bent on resuming their
old cruises on their beloved Trent, and in their beloved old boat; but
Phil listened with a foreboding heart to the deep cough which shook
Zed's old body through the winter, and often interrupted his fervid
utterances of what pleasure he expected when summer should come
again. And when Zed Marrowby would exclaim, "We shall have
another merry summer's cruise yet, Phil!" Phil Garret would answer
with more solemnity, much more, than was his wont to put on,
"Don't say so till you're are sure. I think, Zed, we shall cruise no
more in this world; and I hope our next port will be in a better land."
Zed poohed and pshawed, for some time, at this "solemn way o'
talking," as he called it; but at length he began to feel that Phil was
right—he grew feebler as the spring drew nearer, and when it came,
feeling the expectation to be vain of ever stepping again into the
beloved old boat, he took Phil's advice—for he said he always
thought it worth more than the parson's—and strove to fix his mind
on reaching the happy port in the better land.
Zed Marrowby's end was calm and peaceful; and so was that of
Phil Garret, his faithful companion, who was also laid under the
green sod in old Torksey churchyard within six months after. The
memory of their names and lives is well-nigh lost in the rural locality
where they lived; but there is not a saying more common in old
Lincolnshire to this day than that quaint caution so often uttered by
the blind fiddler to his less grave comrade, "Don't say so till you are
sure!"
MASTER ZERUBBABEL,
THE ANTIQUARY;
AND
HOW HE FOUND OUT THE "NOOSE LARNING."