from traitlets.config.manager import BaseJSONConfigManager
cm = BaseJSONConfigManager()
cm.update('livereveal', {
'theme': 'sky',
'transition': 'zoom',
'start_slideshow_at': 'selected',
'scroll': True
})
{'theme': 'sky', 'transition': 'zoom', 'start_slideshow_at': 'selected', 'scroll': True}
Week 1: floating point, vector norms, matrix multiplication
Real numbers represent quantities: probabilities, velocities, masses, ...
It is important to know, how they are represented in the computer, which only knows about bits.
The most straightforward format for the representation of real numbers is fixed point representation, also known as Qm.n format.
A Qm.n number is in the range [−(2m),2m−2−n], with resolution 2−n.
Total storage is m+n+1 bits.
The range of numbers represented is fixed.
The numbers in computer memory are typically represented as floating point numbers
A floating point number is represented as
number=significand×baseexponent,where significand is integer, base is positive integer and exponent is integer (can be negative), i.e.
1.2=12⋅10−1.Q: What are the advantages/disadvantages of the fixed and floating points?
A: In most cases, they work just fine.
However, fixed point represents numbers within specified range and controls absolute accuracy.
Floating point represent numbers with relative accuracy, and is suitable for the case when numbers in the computations have varying scale (i.e., 10−1 and 105).
In practice, if speed is of no concern, use float32 or float64.
In modern computers, the floating point representation is controlled by IEEE 754 standard which was published in 1985 and before that point different computers behaved differently with floating point numbers.
IEEE 754 has:
Possible values are defined with
and have the following restrictions
The two most common formats, called binary32 and binary64 (called also single and double formats).
Name | Common Name | Base | Digits | Emin | Emax |
---|---|---|---|---|---|
binary32 | single precision | 2 | 11 | -14 | + 15 |
binary64 | double precision | 2 | 24 | -126 | + 127 |
The relative accuracy of single precision is 10−7−10−8,
while for double precision is 10−14−10−16.
Crucial note 1: A float32 takes 4 bytes, float64, or double precision, takes 8 bytes.
Crucial note 2: These are the only two floating point-types supported in hardware.
Crucial note 3: You should use double precision in CSE and float on GPU/Data Science.
import numpy as np
import random
#c = random.random()
#print(c)
c = np.float32(0.925924589693)
print(c)
a = np.float32(8.9)
b = np.float32(c / a)
print('{0:10.16f}'.format(b))
print(a * b - c)
0.9259246 0.1040364727377892 -5.9604645e-08
#a = np.array(1.585858585887575775757575e-5, dtype=np.float)
a = np.float32(5.0)
b = np.sqrt(a)
print('{0:10.16f}'.format(b ** 2 - a))
0.0000001468220603
a = np.array(2.28827272710, dtype=np.float32)
b = np.exp(a)
print(np.log(b) - a)
0.0
However, the rounding errors can depend on the algorithm.
Consider the simplest problem: given n floating point numbers x1,…,xn
Compute their sum
The simplest algorithm is to add one-by-one
What is the actual error for such algorithm?
Naïve algorithm adds numbers one-by-one:
y1=x1,y2=y1+x2,y3=y2+x3,….The worst-case error is then proportional to O(n), while mean-squared error is O(√n).
The Kahan algorithm gives the worst-case error bound O(1) (i.e., independent of n).
Can you find the O(logn) algorithm?
The following algorithm gives 2ε+O(nε2) error, where ε is the machine precision.
s = 0
c = 0
for i in range(len(x)):
y = x[i] - c
t = s + y
c = (t - s) - y
s = t
import math
from numba import jit
n = 10 ** 8
sm = 1e-10
x = np.ones(n, dtype=np.float32) * sm
x[0] = 1.0
true_sum = 1.0 + (n - 1)*sm
approx_sum = np.sum(x)
math_fsum = math.fsum(x)
@jit(nopython=True)
def dumb_sum(x):
s = np.float32(0.0)
for i in range(len(x)):
s = s + x[i]
return s
@jit(nopython=True)
def kahan_sum(x):
s = np.float32(0.0)
c = np.float32(0.0)
for i in range(len(x)):
y = x[i] - c
t = s + y
c = (t - s) - y
s = t
return s
k_sum = kahan_sum(x)
d_sum = dumb_sum(x)
print('Error in np sum: {0:3.1e}'.format(approx_sum - true_sum))
print('Error in Kahan sum: {0:3.1e}'.format(k_sum - true_sum))
print('Error in dumb sum: {0:3.1e}'.format(d_sum - true_sum))
print('Error in math fsum: {0:3.1e}'.format(math_fsum - true_sum))
Error in np sum: 1.9e-04 Error in Kahan sum: -1.3e-07 Error in dumb sum: -1.0e-02 Error in math fsum: 1.3e-10
import numpy as np
test_list = [1, 1e20, 1, -1e20]
print(math.fsum(test_list))
print(np.sum(test_list))
print(1 + 1e20 + 1 - 1e20)
2.0 0.0 0.0
You should be really careful with floating point, since it may give you incorrect answers due to rounding-off errors.
For many standard algorithms, the stability is well-understood and problems can be easily detected.
Example: Polynomials with degree ≤n form a linear space. Polynomial x3−2x2+1 can be considered as a vector [1−201] in the basis {x3,x2,x,1}
Vectors typically provide an (approximate) description of a physical (or some other) object
One of the main question is how accurate the approximation is (1%, 10%)
What is an acceptable representation, of course, depends on the particular applications. For example:
The norm should satisfy certain properties:
The distance between two vectors is then defined as
d(x,y)=‖x−y‖.The most well-known and widely used norm is euclidean norm:
‖x‖2=√n∑i=1|xi|2,which corresponds to the distance in our real life. If the vectors have complex elements, we use their modulus.
Euclidean norm, or 2-norm, is a subclass of an important class of p-norms:
‖x‖p=(n∑i=1|xi|p)1/p.There are two very important special cases:
We will give examples where L1 norm is very important: it all relates to the compressed sensing methods that emerged in the mid-00s as one of the most popular research topics.
All norms are equivalent in the sense that
C1‖x‖∗≤‖x‖∗∗≤C2‖x‖∗for some positive constants C1(n),C2(n), x∈Rn for any pairs of norms ‖⋅‖∗ and ‖⋅‖∗∗. The equivalence of the norms basically means that if the vector is small in one norm, it is small in another norm. However, the constants can be large.
The NumPy package has all you need for computing norms: np.linalg.norm
function.
import numpy as np
n = 100
a = np.ones(n)
b = a + 1e-3 * np.random.randn(n)
print('Relative error in L1 norm:', np.linalg.norm(a - b, 1) / np.linalg.norm(b, 1))
print('Relative error in L2 norm:', np.linalg.norm(a - b) / np.linalg.norm(b))
print('Relative error in Chebyshev norm:', np.linalg.norm(a - b, np.inf) / np.linalg.norm(b, np.inf))
Relative error in L1 norm: 0.0007329368243860864 Relative error in L2 norm: 0.0009161454481284762 Relative error in Chebyshev norm: 0.0025611753793460725
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
p = 1 # Which norm do we use
M = 40000 # Number of sampling points
a = np.random.randn(M, 2)
b = []
for i in range(M):
if np.linalg.norm(a[i, :], p) <= 1:
b.append(a[i, :])
b = np.array(b)
plt.plot(b[:, 0], b[:, 1], '.')
plt.axis('equal')
plt.title('Unit disk in the p-th norm, $p={0:}$'.format(p))
Text(0.5, 1.0, 'Unit disk in the p-th norm, $p=1$')
L1 norm, as it was discovered quite recently, plays an important role in compressed sensing.
The simplest formulation of the considered problem is as follows:
The question: can we find the solution?
The solution is obviously non-unique, so a natural approach is to find the solution that is minimal in the certain sense:
‖x‖→minxsubject to Ax=fTypical choice of ‖x‖=‖x‖2 leads to the linear least squares problem (and has been used for ages).
The choice ‖x‖=‖x‖1 leads to the compressed sensing
It typically yields the sparsest solution
And we finalize the lecture by the concept of stability.
You also have a numerical algorithm alg(x)
that actually computes approximation to f(x).
The algorithm is called forward stable, if ‖alg(x)−f(x)‖≤ε
The algorithm is called backward stable, if for any x there is a close vector x+δx such that
alg(x)=f(x+δx)and ‖δx‖ is small.
A classical example is the solution of linear systems of equations using Gaussian elimination which is similar to LU factorization (more details later)
We consider the Hilbert matrix with the elements
A={aij},aij=1i+j+1,i,j=0,…,n−1.And consider a linear system
Ax=f.We will look into matrices in more details in the next lecture, and for linear systems in the upcoming weeks
import numpy as np
n = 500
a = [[1.0/(i + j + 1) for i in range(n)] for j in range(n)] # Hilbert matrix
A = np.array(a)
rhs = np.random.random(n)
sol = np.linalg.solve(A, rhs)
print(np.linalg.norm(A.dot(sol) - rhs)/np.linalg.norm(rhs))
#plt.plot(sol)
34.458965526869264
rhs = np.ones(n)
sol = np.linalg.solve(A, rhs)
print(np.linalg.norm(A.dot(sol) - rhs)/np.linalg.norm(rhs))
#plt.plot(sol)
1.8802880144962684e-07
How to compute the following functions in numerically stable manner?
u = 300
eps = 1e-6
print("Original function:", np.log(1 - np.tanh(u)**2))
eps_add = np.log(1 - np.tanh(u)**2 + eps)
print("Attempt imporove stability with add small constant:", eps_add)
print("Use more numerically stable form:", np.log(4) - 2 * np.log(np.exp(-u) + np.exp(u)))
Original function: -inf Attempt imporove stability with add small constant: -13.815510557964274 Use more numerically stable form: -598.6137056388801
/Users/alex/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:3: RuntimeWarning: divide by zero encountered in log This is separate from the ipykernel package so we can avoid doing imports until
n = 5
x = np.random.randn(n)
x[0] = 1000
print(np.exp(x) / np.sum(np.exp(x)))
print(np.exp(x - np.max(x)) / np.sum(np.exp(x - np.max(x))))
[nan 0. 0. 0. 0.] [1. 0. 0. 0. 0.]
/Users/alex/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:4: RuntimeWarning: invalid value encountered in true_divide after removing the cwd from sys.path.