From 24b31e93532ce440297ef1d39178c6d03d3e906d Mon Sep 17 00:00:00 2001 From: Mab Date: Fri, 13 Jul 2018 09:11:47 -0700 Subject: [PATCH] notebooks for lecture 2 : Linear Algebra --- Lab41.Lab2-Solutions.ipynb | 488 +++++++++++++++++++++++++++++++++++++ Lab41.Lab2.ipynb | 466 +++++++++++++++++++++++++++++++++++ 2 files changed, 954 insertions(+) create mode 100644 Lab41.Lab2-Solutions.ipynb create mode 100644 Lab41.Lab2.ipynb diff --git a/Lab41.Lab2-Solutions.ipynb b/Lab41.Lab2-Solutions.ipynb new file mode 100644 index 0000000..e976dd0 --- /dev/null +++ b/Lab41.Lab2-Solutions.ipynb @@ -0,0 +1,488 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lab 2 - Linear Algebra" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from mpl_toolkits.mplot3d import Axes3D\n", + "\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# fix random seed for reproducibility\n", + "np.random.seed(7131)\n", + "\n", + "# matplotlib magic for inline plot\n", + "%matplotlib inline" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Linear algebra basics" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# a scalar is a single number\n", + "scalar = 10.0\n", + "np.isscalar(scalar)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0 1 2 3 4]\n" + ] + } + ], + "source": [ + "# a vector is 1D\n", + "v = np.arange(5)\n", + "print(v)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 1 2]\n", + " [3 4 5]]\n" + ] + } + ], + "source": [ + "# while a matrix is 2D\n", + "matrix = np.arange(6).reshape(2,3)\n", + "print(matrix)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[[ 0 1 2]\n", + " [ 3 4 5]\n", + " [ 6 7 8]]\n", + "\n", + " [[ 9 10 11]\n", + " [12 13 14]\n", + " [15 16 17]]\n", + "\n", + " [[18 19 20]\n", + " [21 22 23]\n", + " [24 25 26]]]\n" + ] + } + ], + "source": [ + "# tensors have higher number of dimensions\n", + "tensor = np.arange(27).reshape(3,3,3)\n", + "print(tensor)" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 0.1948294 0.18694484 0.29809353]\n", + " [ 0.53915291 0.00382536 0.8710852 ]\n", + " [ 0.22093992 0.53149704 0.29688214]\n", + " [ 0.4832809 0.80484005 0.97636989]]\n", + "\n", + "[[ 0.58178275 0.65085588]\n", + " [ 0.89260795 0.6131198 ]\n", + " [ 0.27797347 0.18398957]]\n" + ] + } + ], + "source": [ + "# generate two random matices\n", + "A = np.random.random_sample((4, 3))\n", + "B = np.random.random_sample((3,2))\n", + "print(A)\n", + "print('')\n", + "print(B)" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0.1948294 , 0.53915291, 0.22093992, 0.4832809 ],\n", + " [ 0.18694484, 0.00382536, 0.53149704, 0.80484005],\n", + " [ 0.29809353, 0.8710852 , 0.29688214, 0.97636989]])" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# find tranpose of matrix A\n", + "np.transpose(A)" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0.36307893, 0.29627154],\n", + " [ 0.55922298, 0.51352684],\n", + " [ 0.68548288, 0.52429462],\n", + " [ 1.27097604, 0.98765145]])" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# dot product\n", + "np.dot(A,B)" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0.36307893, 0.29627154],\n", + " [ 0.55922298, 0.51352684],\n", + " [ 0.68548288, 0.52429462],\n", + " [ 1.27097604, 0.98765145]])" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# you can also calculate it this way\n", + "A.dot(B)" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "matrix([[19, 8, 5],\n", + " [63, 24, 9]])" + ] + }, + "execution_count": 60, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# note that np.matrix has special operators like '*' (matrix mult.)\n", + "matrix1 = np.matrix([[1,5],[5,9]])\n", + "matrix2 = np.matrix([[9,3,0],[2,1,1]])\n", + "\n", + "matrix1*matrix2" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": {}, + "outputs": [], + "source": [ + "# This will probably be inefficient, but manually create a function to \n", + "# multipy two matrices\n", + "\n", + "def matrix_mult(a, b):\n", + " # check matrices are of correct dimensions\n", + " if a.shape[1] != b.shape[0]:\n", + " return 'invalid dimensions: must be (m x n) (n x p)'\n", + " # create results matrix to store values\n", + " results = np.zeros((a.shape[0], b.shape[1]))\n", + " # calcualte matrix multiplication\n", + " # rows in a\n", + " for i in np.arange(a.shape[0]):\n", + " # cols in b\n", + " for j in np.arange(b.shape[1]):\n", + " # rows in b\n", + " for k in np.arange(b.shape[0]):\n", + " results[i][j] += a[i][k]*b[k][j]\n", + " return results " + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0.36307893, 0.29627154],\n", + " [ 0.55922298, 0.51352684],\n", + " [ 0.68548288, 0.52429462],\n", + " [ 1.27097604, 0.98765145]])" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "matrix_mult(A,B)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Check you get the same result" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.allclose( np.dot(A,B), matrix_mult(A,B))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### System of equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Solve for X in AX = B, where\n", + "\n", + "\\begin{equation*}\n", + "A = \\begin{vmatrix}\n", + "14 & 1\\\\\n", + "5 & 8\n", + "\\end{vmatrix}\n", + "\\end{equation*}\n", + "\n", + "\\begin{equation*}\n", + "X = \\begin{vmatrix}\n", + "a \\\\\n", + "b\n", + "\\end{vmatrix}\n", + "\\end{equation*}\n", + "\n", + "\\begin{equation*}\n", + "B = \\begin{vmatrix}\n", + "20\\\\\n", + "100\n", + "\\end{vmatrix}\n", + "\\end{equation*}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "-------------------" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's try this by finding the inverse of A. And for fun, let's define a function to find the inverse. The inverse of 2x2 matrix \n", + "\\begin{equation*}\n", + "A = \\begin{vmatrix}\n", + "a & b\\\\\n", + "c & d\n", + "\\end{vmatrix}\n", + "\\end{equation*} \n", + "\n", + "that has a non-zero determinant, can be obtained via\n", + "\n", + "\\begin{equation*}\n", + "A^{-1} = \\frac{1}{det(A)} \\begin{vmatrix}\n", + "d & -b\\\\\n", + "-c & a\n", + "\\end{vmatrix}\n", + "\\end{equation*}" + ] + }, + { + "cell_type": "code", + "execution_count": 94, + "metadata": {}, + "outputs": [], + "source": [ + "# matrix inverse for 2x2 matrix\n", + "def matrix_inverse(a):\n", + " # check matrix is invertible, check input is a 2x2 matrix\n", + " # return error message otherwise\n", + " if np.linalg.det(a) == 0:\n", + " return 'determinant of matrix is 0; matrix is non-invertible'\n", + " if (a.shape[0] != 2) & (a.shape[1] != 2):\n", + " return 'This is not a 2x2 matrix'\n", + " #create results matrix to store values\n", + " results = np.zeros((2,2))\n", + " # interchange diagonal elements, take (-)ve of off-diagonal values\n", + " for i in np.arange(2):\n", + " results[i][i] = a[(i+1)%2][(i+1)%2]\n", + " results[i][(i+1)%2] = -a[i][(i+1)%2]\n", + " # multiply 1/determinate\n", + " results = (1/np.linalg.det(a))*results \n", + " return results " + ] + }, + { + "cell_type": "code", + "execution_count": 99, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 0.56074766]\n", + " [ 12.14953271]]\n" + ] + } + ], + "source": [ + "# define A and B matrices\n", + "A = np.array([[14, 1],[5,8]])\n", + "B = np.array([[20],[100]])\n", + "\n", + "# find inverse of A using above function \n", + "A_inverse = matrix_inverse(A)\n", + "\n", + "# solve for X\n", + "X = A_inverse.dot(B)\n", + "\n", + "print(X)" + ] + }, + { + "cell_type": "code", + "execution_count": 100, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 0.56074766]\n", + " [ 12.14953271]]\n" + ] + } + ], + "source": [ + "# we can also do this in one line using solve\n", + "print(np.linalg.solve(A,B))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "CosmiQ_py3.6", + "language": "python", + "name": "py36_cosmiq" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Lab41.Lab2.ipynb b/Lab41.Lab2.ipynb new file mode 100644 index 0000000..e48b72c --- /dev/null +++ b/Lab41.Lab2.ipynb @@ -0,0 +1,466 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lab 2 - Linear Algebra" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from mpl_toolkits.mplot3d import Axes3D\n", + "\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# fix random seed for reproducibility\n", + "np.random.seed(7131)\n", + "\n", + "# matplotlib magic for inline plot\n", + "%matplotlib inline" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Linear algebra basics" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# a scalar is a single number\n", + "scalar = 10.0\n", + "np.isscalar(scalar)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0 1 2 3 4]\n" + ] + } + ], + "source": [ + "# a vector is 1D\n", + "v = np.arange(5)\n", + "print(v)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 1 2]\n", + " [3 4 5]]\n" + ] + } + ], + "source": [ + "# while a matrix is 2D\n", + "matrix = np.arange(6).reshape(2,3)\n", + "print(matrix)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[[ 0 1 2]\n", + " [ 3 4 5]\n", + " [ 6 7 8]]\n", + "\n", + " [[ 9 10 11]\n", + " [12 13 14]\n", + " [15 16 17]]\n", + "\n", + " [[18 19 20]\n", + " [21 22 23]\n", + " [24 25 26]]]\n" + ] + } + ], + "source": [ + "# tensors have higher number of dimensions\n", + "tensor = np.arange(27).reshape(3,3,3)\n", + "print(tensor)" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 0.1948294 0.18694484 0.29809353]\n", + " [ 0.53915291 0.00382536 0.8710852 ]\n", + " [ 0.22093992 0.53149704 0.29688214]\n", + " [ 0.4832809 0.80484005 0.97636989]]\n", + "\n", + "[[ 0.58178275 0.65085588]\n", + " [ 0.89260795 0.6131198 ]\n", + " [ 0.27797347 0.18398957]]\n" + ] + } + ], + "source": [ + "# generate two random matices\n", + "A = np.random.random_sample((4, 3))\n", + "B = np.random.random_sample((3,2))\n", + "print(A)\n", + "print('')\n", + "print(B)" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0.1948294 , 0.53915291, 0.22093992, 0.4832809 ],\n", + " [ 0.18694484, 0.00382536, 0.53149704, 0.80484005],\n", + " [ 0.29809353, 0.8710852 , 0.29688214, 0.97636989]])" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# find tranpose of matrix A\n", + "np.transpose(A)" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0.36307893, 0.29627154],\n", + " [ 0.55922298, 0.51352684],\n", + " [ 0.68548288, 0.52429462],\n", + " [ 1.27097604, 0.98765145]])" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# dot product\n", + "np.dot(A,B)" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0.36307893, 0.29627154],\n", + " [ 0.55922298, 0.51352684],\n", + " [ 0.68548288, 0.52429462],\n", + " [ 1.27097604, 0.98765145]])" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# you can also calculate it this way\n", + "A.dot(B)" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "matrix([[19, 8, 5],\n", + " [63, 24, 9]])" + ] + }, + "execution_count": 60, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# note that np.matrix has special operators like '*' (matrix mult.)\n", + "matrix1 = np.matrix([[1,5],[5,9]])\n", + "matrix2 = np.matrix([[9,3,0],[2,1,1]])\n", + "\n", + "matrix1*matrix2" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# This will probably be inefficient, but manually create a function to \n", + "# multipy two matrices\n", + "\n", + "def matrix_mult(a, b):\n", + " # check matrices are of correct dimensions\n", + " if :\n", + " return 'invalid dimensions: must be (m x n) (n x p)'\n", + " # create results matrix to store values\n", + " results = np.zeros((, ))\n", + " # calcualte matrix multiplication\n", + " \n", + " return results " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "matrix_mult(A,B)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Check you get the same result" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.allclose( np.dot(A,B), matrix_mult(A,B))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### System of equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Solve for X in AX = B, where\n", + "\n", + "\\begin{equation*}\n", + "A = \\begin{vmatrix}\n", + "14 & 1\\\\\n", + "5 & 8\n", + "\\end{vmatrix}\n", + "\\end{equation*}\n", + "\n", + "\\begin{equation*}\n", + "X = \\begin{vmatrix}\n", + "a \\\\\n", + "b\n", + "\\end{vmatrix}\n", + "\\end{equation*}\n", + "\n", + "\\begin{equation*}\n", + "B = \\begin{vmatrix}\n", + "20\\\\\n", + "100\n", + "\\end{vmatrix}\n", + "\\end{equation*}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "-------------------" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's try this by finding the inverse of A. And for fun, let's define a function to find the inverse. The inverse of 2x2 matrix \n", + "\\begin{equation*}\n", + "A = \\begin{vmatrix}\n", + "a & b\\\\\n", + "c & d\n", + "\\end{vmatrix}\n", + "\\end{equation*} \n", + "\n", + "that has a non-zero determinant, can be obtained via\n", + "\n", + "\\begin{equation*}\n", + "A^{-1} = \\frac{1}{det(A)} \\begin{vmatrix}\n", + "d & -b\\\\\n", + "-c & a\n", + "\\end{vmatrix}\n", + "\\end{equation*}" + ] + }, + { + "cell_type": "code", + "execution_count": 94, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# matrix inverse for 2x2 matrix\n", + "def matrix_inverse(a):\n", + " # check matrix is invertible, check input is a 2x2 matrix\n", + " # return error message otherwise\n", + " \n", + " #create results matrix to store values\n", + " results = np.zeros((2,2))\n", + " # interchange diagonal elements, take (-)ve of off-diagonal values\n", + " \n", + " # multiply 1/determinate\n", + " \n", + " return results " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# define A and B matrices\n", + "A = \n", + "B = \n", + "\n", + "# find inverse of A using above function \n", + "A_inverse = \n", + "\n", + "# solve for X\n", + "X = \n", + "\n", + "print(X)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# we can also do this in one line using solve\n", + "print(np.linalg.solve(A,B))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# check you get the same result" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "CosmiQ_py3.6", + "language": "python", + "name": "py36_cosmiq" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}