<jupyter_start><jupyter_text>You can read an overview of this Numerical Linear Algebra course in [this blog post](http://www.fast.ai/2017/07/17/num-lin-alg/).  The course was originally taught in the [University of San Francisco MS in Analytics](https://www.usfca.edu/arts-sciences/graduate-programs/analytics) graduate program.  Course lecture videos are [available on YouTube](https://www.youtube.com/playlist?list=PLtmWHNX-gukIc92m1K0P6bIOnZb-mg0hY) (note that the notebook numbers and video numbers do not line up, since some notebooks took longer than 1 video to cover).You can ask questions about the course on [our fast.ai forums](http://forums.fast.ai/c/lin-alg).  6. How to Implement Linear Regression In the previous lesson, we calculated the least squares linear regression for a diabetes dataset, using scikit learn's implementation.  Today, we will look at how we could write our own implementation.<jupyter_code>from sklearn import datasets, linear_model, metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures
import math, scipy, numpy as np
from scipy import linalg
np.set_printoptions(precision=6)
data = datasets.load_diabetes()
feature_names=['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']
trn,test,y_trn,y_test = train_test_split(data.data, data.target, test_size=0.2)
trn.shape, test.shape
def regr_metrics(act, pred):
    return (math.sqrt(metrics.mean_squared_error(act, pred)), 
     metrics.mean_absolute_error(act, pred))<jupyter_output><empty_output><jupyter_text>How did sklearn do it? How is sklearn doing this?  By checking [the source code](https://github.com/scikit-learn/scikit-learn/blob/14031f6/sklearn/linear_model/base.pyL417), you can see that in the dense case, it calls [scipy.linalg.lstqr](https://github.com/scipy/scipy/blob/v0.19.0/scipy/linalg/basic.pyL892-L1058), which is calling a LAPACK method:        Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default        (``'gelsd'``) is a good choice.  However, ``'gelsy'`` can be slightly        faster on many problems.  ``'gelss'`` was used historically.  It is        generally slow but uses less memory.- [gelsd](https://software.intel.com/sites/products/documentation/doclib/mkl_sa/11/mkl_lapack_examples/_gelsd.htm): uses SVD and a divide-and-conquer method- [gelsy](https://software.intel.com/en-us/node/521113): uses QR factorization- [gelss](https://software.intel.com/en-us/node/521114): uses SVD  Scipy Sparse Least Squares We will not get into too much detail about the sparse version of least squares.  Here is a bit of info if you are interested:  [Scipy sparse lsqr](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.linalg.lsqr.htmlid1) uses an iterative method called [Golub and Kahan bidiagonalization](https://web.stanford.edu/class/cme324/paige-saunders2.pdf). from [scipy sparse lsqr source code](https://github.com/scipy/scipy/blob/v0.14.0/scipy/sparse/linalg/isolve/lsqr.pyL96):  Preconditioning is another way to reduce the number of iterations. If it is possible to solve a related system ``M*x = b`` efficiently, where M approximates A in some helpful way (e.g. M - A has low rank or its elements are small relative to those of A), LSQR may converge more rapidly on the system ``A*M(inverse)*z = b``, after which x can be recovered by solving M\*x = z.  If A is symmetric, LSQR should not be used! Alternatives are the symmetric conjugate-gradient method (cg) and/or SYMMLQ.  SYMMLQ is an implementation of symmetric cg that applies to any symmetric A and will converge more rapidly than LSQR.  If A is positive definite, there are other implementations of symmetric cg that require slightly less work per iteration than SYMMLQ (but will take the same number of iterations).  linalg.lstqr The sklearn implementation handled adding a constant term (since the y-intercept is presumably not 0 for the line we are learning) for us.  We will need to do that by hand now:<jupyter_code>trn_int = np.c_[trn, np.ones(trn.shape[0])]
test_int = np.c_[test, np.ones(test.shape[0])]<jupyter_output><empty_output><jupyter_text>Since `linalg.lstsq` lets us specify which LAPACK routine we want to use, lets try them all and do some timing comparisons:<jupyter_code>%timeit coef, _,_,_ = linalg.lstsq(trn_int, y_trn, lapack_driver="gelsd")
%timeit coef, _,_,_ = linalg.lstsq(trn_int, y_trn, lapack_driver="gelsy")
%timeit coef, _,_,_ = linalg.lstsq(trn_int, y_trn, lapack_driver="gelss")<jupyter_output>199 µs ± 228 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)<jupyter_text>Naive Solution Recall that we want to find $\hat{x}$ that minimizes: $$ \big\vert\big\vert Ax - b \big\vert\big\vert_2$$Another way to think about this is that we are interested in where vector $b$ is closest to the subspace spanned by $A$ (called the *range of* $A$).  This is the projection of $b$ onto $A$.  Since $b - A\hat{x}$ must be perpendicular to the subspace spanned by $A$, we see that$$A^T (b - A\hat{x}) = 0 $$(we are using $A^T$ because we want to multiply each column of $A$ by $b - A\hat{x}$ This leads us to the *normal equations*:$$ x = (A^TA)^{-1}A^T b $$<jupyter_code>def ls_naive(A, b):
     return np.linalg.inv(A.T @ A) @ A.T @ b
%timeit coeffs_naive = ls_naive(trn_int, y_trn)
coeffs_naive = ls_naive(trn_int, y_trn)
regr_metrics(y_test, test_int @ coeffs_naive)<jupyter_output><empty_output><jupyter_text>Normal Equations (Cholesky) Normal equations:$$ A^TA x = A^T b $$If $A$ has full rank, the pseudo-inverse $(A^TA)^{-1}A^T$ is a **square, hermitian positive definite** matrix.  The standard way of solving such a system is *Cholesky Factorization*, which finds upper-triangular R s.t. $A^TA = R^TR$. The following steps are based on Algorithm 11.1 from Trefethen:<jupyter_code>A = trn_int
b = y_trn
AtA = A.T @ A
Atb = A.T @ b<jupyter_output><empty_output><jupyter_text>**Warning:** Numpy and Scipy default to different upper/lower for Cholesky<jupyter_code>R = scipy.linalg.cholesky(AtA)
np.set_printoptions(suppress=True, precision=4)
R<jupyter_output><empty_output><jupyter_text>check our factorization:<jupyter_code>np.linalg.norm(AtA - R.T @ R)<jupyter_output><empty_output><jupyter_text>$$ A^T A x = A^T b $$$$ R^T R x = A^T b $$$$ R^T w = A^T b $$$$ R x = w $$<jupyter_code>w = scipy.linalg.solve_triangular(R, Atb, lower=False, trans='T')<jupyter_output><empty_output><jupyter_text>It's always good to check that our result is what we expect it to be: (in case we entered the wrong params, the function didn't return what we thought, or sometimes the docs are even outdated)<jupyter_code>np.linalg.norm(R.T @ w - Atb)
coeffs_chol = scipy.linalg.solve_triangular(R, w, lower=False)
np.linalg.norm(R @ coeffs_chol - w)
def ls_chol(A, b):
    R = scipy.linalg.cholesky(A.T @ A)
    w = scipy.linalg.solve_triangular(R, A.T @ b, trans='T')
    return scipy.linalg.solve_triangular(R, w)
%timeit coeffs_chol = ls_chol(trn_int, y_trn)
coeffs_chol = ls_chol(trn_int, y_trn)
regr_metrics(y_test, test_int @ coeffs_chol)<jupyter_output><empty_output><jupyter_text>QR Factorization $$ A x = b $$$$ A = Q R $$$$ Q R x = b $$$$ R x = Q^T b $$<jupyter_code>def ls_qr(A,b):
    Q, R = scipy.linalg.qr(A, mode='economic')
    return scipy.linalg.solve_triangular(R, Q.T @ b)
%timeit coeffs_qr = ls_qr(trn_int, y_trn)
coeffs_qr = ls_qr(trn_int, y_trn)
regr_metrics(y_test, test_int @ coeffs_qr)<jupyter_output><empty_output><jupyter_text>SVD $$ A x = b $$$$ A = U \Sigma V $$$$ \Sigma V x = U^T b $$$$ \Sigma w = U^T b $$$$ x = V^T w $$ SVD gives the pseudo-inverse<jupyter_code>def ls_svd(A,b):
    m, n = A.shape
    U, sigma, Vh = scipy.linalg.svd(A, full_matrices=False, lapack_driver='gesdd')
    w = (U.T @ b)/ sigma
    return Vh.T @ w
%timeit coeffs_svd = ls_svd(trn_int, y_trn)
%timeit coeffs_svd = ls_svd(trn_int, y_trn)
coeffs_svd = ls_svd(trn_int, y_trn)
regr_metrics(y_test, test_int @ coeffs_svd)<jupyter_output><empty_output><jupyter_text>Random Sketching Technique for Least Squares Regression [Linear Sketching](http://researcher.watson.ibm.com/researcher/files/us-dpwoodru/journal.pdf) (Woodruff)1. Sample a r x n random matrix S, r << n2. Compute S A and S b3. Find exact solution x to regression SA x = Sb  Timing Comparison<jupyter_code>import timeit
import pandas as pd
def scipylstq(A, b):
    return scipy.linalg.lstsq(A,b)[0]
row_names = ['Normal Eqns- Naive',
             'Normal Eqns- Cholesky', 
             'QR Factorization', 
             'SVD', 
             'Scipy lstsq']

name2func = {'Normal Eqns- Naive': 'ls_naive', 
             'Normal Eqns- Cholesky': 'ls_chol', 
             'QR Factorization': 'ls_qr',
             'SVD': 'ls_svd',
             'Scipy lstsq': 'scipylstq'}
m_array = np.array([100, 1000, 10000])
n_array = np.array([20, 100, 1000])
index = pd.MultiIndex.from_product([m_array, n_array], names=['# rows', '# cols'])
pd.options.display.float_format = '{:,.6f}'.format
df = pd.DataFrame(index=row_names, columns=index)
df_error = pd.DataFrame(index=row_names, columns=index)
# %%prun
for m in m_array:
    for n in n_array:
        if m >= n:        
            x = np.random.uniform(-10,10,n)
            A = np.random.uniform(-40,40,[m,n])   # removed np.asfortranarray
            b = np.matmul(A, x) + np.random.normal(0,2,m)
            for name in row_names:
                fcn = name2func[name]
                t = timeit.timeit(fcn + '(A,b)', number=5, globals=globals())
                df.set_value(name, (m,n), t)
                coeffs = locals()[fcn](A, b)
                reg_met = regr_metrics(b, A @ coeffs)
                df_error.set_value(name, (m,n), reg_met[0])
df
df_error
store = pd.HDFStore('least_squares_results.h5')
store['df'] = df<jupyter_output>C:\Users\rache\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:2881: PerformanceWarning: 
your performance may suffer as PyTables will pickle object types that it cannot
map directly to c-types [inferred_type->floating,key->block0_values] [items->[(100, 20), (100, 100), (100, 1000), (1000, 20), (1000, 100), (1000, 1000), (5000, 20), (5000, 100), (5000, 1000)]]

  exec(code_obj, self.user_global_ns, self.user_ns)<jupyter_text>Notes I used the magick %prun to profile my code. Alternative: least absolute deviation (L1 regression)- Less sensitive to outliers than least squares.- No closed form solution, but can solve with linear programming  Conditioning & stability  Condition Number *Condition number* is a measure of how small changes to the input cause the output to change.**Question**: Why do we care about behavior with small changes to the input in numerical linear algebra? The *relative condition number* is defined by$$ \kappa = \sup_{\delta x} \frac{\|\delta f\|}{\| f(x) \|}\bigg/ \frac{\| \delta x \|}{\| x \|} $$  where $\delta x$ is infinitesimalAccording to Trefethen (pg. 91), a problem is *well-conditioned* if $\kappa$ is small (e.g. $1$, $10$, $10^2$) and *ill-conditioned* if $\kappa$ is large (e.g. $10^6$, $10^{16}$) **Conditioning**: perturbation behavior of a mathematical problem (e.g. least squares)**Stability**: perturbation behavior of an algorithm used to solve that problem on a computer (e.g. least squares algorithms, householder, back substitution, gaussian elimination)  Conditioning example The problem of computing eigenvalues of a non-symmetric matrix is often ill-conditioned<jupyter_code>A = [[1, 1000], [0, 1]]
B = [[1, 1000], [0.001, 1]]
wA, vrA = scipy.linalg.eig(A)
wB, vrB = scipy.linalg.eig(B)
wA, wB<jupyter_output><empty_output><jupyter_text>Condition Number of a Matrix The product $\| A\| \|A^{-1} \|$ comes up so often it has its own name: the *condition number* of $A$.  Note that normally we talk about the conditioning of problems, not matrices.The *condition number* of $A$ relates to:- computing $b$ given $A$ and $x$ in $Ax = b$- computing $x$ given $A$ and $b$ in $Ax = b$  Loose ends from last time  Full vs Reduced Factorizations **SVD** Diagrams from Trefethen: **QR Factorization exists for ALL matrices** Just like with SVD, there are full and reduced versions of the QR factorization.  Matrix Inversion is Unstable<jupyter_code>from scipy.linalg import hilbert
n = 14
A = hilbert(n)
x = np.random.uniform(-10,10,n)
b = A @ x
A_inv = np.linalg.inv(A)
np.linalg.norm(np.eye(n) - A @ A_inv)
np.linalg.cond(A)
A @ A_inv
row_names = ['Normal Eqns- Naive',
             'QR Factorization', 
             'SVD', 
             'Scipy lstsq']

name2func = {'Normal Eqns- Naive': 'ls_naive', 
             'QR Factorization': 'ls_qr',
             'SVD': 'ls_svd',
             'Scipy lstsq': 'scipylstq'}
pd.options.display.float_format = '{:,.9f}'.format
df = pd.DataFrame(index=row_names, columns=['Time', 'Error'])
for name in row_names:
    fcn = name2func[name]
    t = timeit.timeit(fcn + '(A,b)', number=5, globals=globals())
    coeffs = locals()[fcn](A, b)
    df.set_value(name, 'Time', t)
    df.set_value(name, 'Error', regr_metrics(b, A @ coeffs)[0])<jupyter_output><empty_output><jupyter_text>SVD is best here! DO NOT RERUN<jupyter_code>df
df<jupyter_output><empty_output><jupyter_text>**Another reason not to take inverse** Even if $A$ is incredibly sparse, $A^{-1}$ is generally dense.  For large matrices, $A^{-1}$ could be so dense as to not fit in memory.  Runtime Matrix Inversion: $2n^3$Matrix Multiplication: $n^3$Cholesky: $\frac{1}{3}n^3$QR, Gram Schmidt: $2mn^2$, $m\geq n$ (chapter 8 of Trefethen)QR, Householder: $2mn^2 - \frac{2}{3}n^3$ (chapter 10 of Trefethen)Solving a triangular system: $n^2$ **Why Cholesky Factorization is Fast:**(source: [Stanford Convex Optimization: Numerical Linear Algebra Background Slides](http://stanford.edu/class/ee364a/lectures/num-lin-alg.pdf))  A Case Where QR is the Best<jupyter_code>m=100
n=15
t=np.linspace(0, 1, m)
# Vandermonde matrix
A=np.stack([t**i for i in range(n)], 1)
b=np.exp(np.sin(4*t))

# This will turn out to normalize the solution to be 1
b /= 2006.787453080206
from matplotlib import pyplot as plt
%matplotlib inline
plt.plot(t, b)<jupyter_output><empty_output><jupyter_text>Check that we get 1:<jupyter_code>1 - ls_qr(A, b)[14]<jupyter_output><empty_output><jupyter_text>Bad condition number:<jupyter_code>kappa = np.linalg.cond(A); kappa
row_names = ['Normal Eqns- Naive',
             'QR Factorization', 
             'SVD', 
             'Scipy lstsq']

name2func = {'Normal Eqns- Naive': 'ls_naive', 
             'QR Factorization': 'ls_qr',
             'SVD': 'ls_svd',
             'Scipy lstsq': 'scipylstq'}
pd.options.display.float_format = '{:,.9f}'.format
df = pd.DataFrame(index=row_names, columns=['Time', 'Error'])
for name in row_names:
    fcn = name2func[name]
    t = timeit.timeit(fcn + '(A,b)', number=5, globals=globals())
    coeffs = locals()[fcn](A, b)
    df.set_value(name, 'Time', t)
    df.set_value(name, 'Error', np.abs(1 - coeffs[-1]))
df<jupyter_output><empty_output><jupyter_text>The solution for least squares via the normal equations is unstable in general, although stable for problems with small condition numbers.  Low-rank<jupyter_code>m = 100
n = 10
x = np.random.uniform(-10,10,n)
A2 = np.random.uniform(-40,40, [m, int(n/2)])   # removed np.asfortranarray
A = np.hstack([A2, A2])
A.shape, A2.shape
b = A @ x + np.random.normal(0,1,m)
row_names = ['Normal Eqns- Naive',
             'QR Factorization', 
             'SVD', 
             'Scipy lstsq']

name2func = {'Normal Eqns- Naive': 'ls_naive', 
             'QR Factorization': 'ls_qr',
             'SVD': 'ls_svd',
             'Scipy lstsq': 'scipylstq'}
pd.options.display.float_format = '{:,.9f}'.format
df = pd.DataFrame(index=row_names, columns=['Time', 'Error'])
for name in row_names:
    fcn = name2func[name]
    t = timeit.timeit(fcn + '(A,b)', number=5, globals=globals())
    coeffs = locals()[fcn](A, b)
    df.set_value(name, 'Time', t)
    df.set_value(name, 'Error', regr_metrics(b, A @ coeffs)[0])
df<jupyter_output><empty_output><jupyter_text>Comparison Our results from above:<jupyter_code>df<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13565022421524664, 'fraction_numerical': 0.02061534628799203, 'mean_word_length': 4.290609555189456, 'pattern_counts': {'":': 0, '<': 81, '<?xml version=': 0, '>': 83, 'https://': 10, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '194128', 'license': 'Apache-2.0', 'n_tokens_mistral': 6171, 'n_tokens_neox': 5793, 'n_words': 1679, 'path': 'numerical-linear-algebra/nbs/6. How to Implement Linear Regression.ipynb', 'repo_name': 'nimacgit/courses', 'size': '16056'}