File size: 333,517 Bytes
5697766 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | {"text": "# HW07: Solving Linear Least Squares Problems\n**Yuanxing Cheng, 810925466**\n\nThis homework studies the polynomial fitting problem. Given a set of $m$ different points, $(x_i , y_i )$, $i = 1, 2, \\dots, m$, in the $xy\\text{-coordinate}$ plane, determine a polynomial of degree $n − 1$.\n\n$$p(x) = a_1 x^{n-1} + a_2 x^{n-2} + \\cdots + a_{n-1} x + a_n$$\n\nwhere $n\\leq m$, such that $\\displaystyle \\sum_{i=1}^{m} \\left|p(x_i) - y_i\\right|^2$ is minimized.\n\nThis leads to a linear least squares problem, where the coefficient matrix is given by the $m \\times n$ Vandermonde matrix\n\n$$\\left[\\begin{array}{ccccc}\nx_{1}^{n-1} & x_{1}^{n-2} & \\cdots & x_{1} & 1 \\\\\nx_{2}^{n-1} & x_{2}^{n-2} & \\cdots & x_{2} & 1 \\\\\nx_{3}^{n-1} & x_{3}^{n-2} & \\cdots & x_{3} & 1 \\\\\n\\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\nx_{m}^{n-1} & x_{m}^{n-2} & \\cdots & x_{m} & 1 \\\\\n\\end{array}\\right]$$\n\nthe right hand side is the $m\\text{−dimensional}$ column vector \n$\\left[\\begin{array}{cccc}\ny_{1} & y_{2} & \\cdots & y_{m} \\\\\n\\end{array}\\right]'$, and the unknown is the $n\\text{−dimensional}$ column vector $\\left[\\begin{array}{cccc}\na_{1} & a_{2} & \\cdots & a_{n} \\\\\n\\end{array}\\right]'$ containing the coefficients of p(x). Note that several MATLAB functions, e.g., `vander`, `polyval`, may be useful in this homework.\n\n## Q1 \nTake the following $m$ equally spaced points on the interval $−1 \\leq x \\leq 1$,\n\n$$\\begin{align}\nx_i=-1+ {{2(i-1)}\\over{m-1}} && y_i = \\frac{1} {1 + 25x_i^2}\n\\end{align}$$\n\nHere $i = 1,2,\\cdots, m$. Use the following three different approaches to solve the above least squares problem, respectively, to obtain the polynomial $p(x)$ of degree $n − 1$. Here take $m = 50$ and $n = 20$.\n\n($\\text{a}$) The Matlab backslash function `\\`, which solves the least squares problem when the matrix is an $m \\times n$ matrix ($m > n$).\n\n($\\text{b}$) The reduced $QR$ factorization. Here the $QR$ factorization can be computed via the MATLAB built-in function `qr`.\n\n($\\text{c}$) Solution of the normal equation.\n\nCompare the coefficients of $p(x)$ obtained from the above three approaches. Which two approaches generate results more close to each other. You need to use format long to observe more digits in the coefficients for comparison.\n\n$Answer$\n\nThe distance between using Matlab backslash function and reduced QR factorization is the lowest.\n\n$Code$\n\n```MATLAB\nclear\nclc\n\nm = 50;\nn = 20;\n\nx = linspace(-1,1,m);\nx = x';\ny = 1./(1+25*x.^2);\nA = vander(x);\n\nA1 = A(:,m-n+1:m);\nx1 = A1\\y;\n\n[Q,R] = qr(A1,0);\ny2 = Q'*y;\nx2 = backwardSubeps(R,y2);\n\nA3 = A1'*A1;\nL = chol(A3,'lower');\ny3 = L^(-1)*A1'*y;\nx3 = backwardSubeps(L',y3);\n\nd12 = norm(x1-x2);\nd23 = norm(x2-x3);\nd31 = norm(x3-x1);\n\ns1 = 'Matlab backslash function';\ns2 = 'reduced QR factorization';\ns3 = 'normal equation';\n\nif d12 < d23\n if d12 < d31\n s = [s1,' and ',s2];\n else\n s = [s3,' and ',s1];\n end\nelse\n if d23 < d31\n s = [s2,' and ',s3];\n else\n s = [s3,' and ',s1];\n end\nend\n\ndisp(['The distance between using ',s,' is the lowest.'])\n\n```\n\n## Q2\nFor the case $m = 50$ and $n = 20$, draw the fitting polynomial $y = p(x)$ obtained from one approach in Part 1 and compare it in the same figure with the plot of the original function $y = 1/(1 + 25x^2 )$. Do they match well?\n\n$Answer$\n\nYes, all three methods fit very well.\n\n\n\n$Code$\n\n```MATLAB\nclear\nclc\n\nm = 50;\nn = 20;\n\nx = linspace(-1,1,m);\nx = x';\ny = 1./(1+25*x.^2);\nA = vander(x);\n\nA1 = A(:,m-n+1:m);\nx1 = A1\\y;\n\n[Q,R] = qr(A1,0);\ny2 = Q'*y;\nx2 = backwardSubeps(R,y2);\n\nA3 = A1'*A1;\nL = chol(A3,'lower');\ny3 = L^(-1)*A1'*y;\nx3 = backwardSubeps(L',y3);\n\ns1 = 'Matlab backslash function';\ns2 = 'reduced QR factorization';\ns3 = 'normal equation';\n\nt = linspace(-1,1,100);\n\nsubplot(3,1,1)\nY1 = polyval(x1,t);\nplot(x,y,'bo')\nhold on\nplot(t,Y1,'r')\ntitle(s1)\n```\n\n```MATLAB\nsubplot(3,1,2)\nY2 = polyval(x2,t);\nplot(x,y,'bo')\nhold on \nplot(t,Y2,'r')\ntitle(s2)\n\nsubplot(3,1,3)\nY3 = polyval(x3,t);\nplot(x,y,'bo')\nhold on\nplot(t,Y3,'r')\ntitle(s3)\n```\n\n## Q3\nRepeat Part 2, but taking $m = n = 50$, which is now a polynomial interpolation problem. Does the interpolation polynomial match the function $y = 1/(1 + 25x^2)$ well in this case?\n\n$Answer$\n\nFor the result from using Matlab backslash function and reduced QR factorization, they don't fit as well as before. And for the last method, it even doesn't work here because the matrix we now are using is no more full rank.\n\n\n\n$Code$\n\n```MATLAB\nclear\nclc\n\nm = 50;\nn = 50;\n\nx = linspace(-1,1,m);\nx = x';\ny = 1./(1+25*x.^2);\nA = vander(x);\n```\n\n```MATLAB\nA1 = A(:,m-n+1:m);\nx1 = A1\\y;\n\n[Q,R] = qr(A1,0);\ny2 = Q'*y;\nx2 = backwardSubeps(R,y2);\n\ns1 = 'Matlab backslash function';\ns2 = 'reduced QR factorization';\n\nt = linspace(-1,1,100);\n\nsubplot(2,1,1)\nY1 = polyval(x1,t);\nplot(x,y,'bo')\nhold on\nplot(t,Y1,'r')\ntitle(s1)\n\nsubplot(2,1,2)\nY2 = polyval(x2,t);\nplot(x,y,'bo')\nhold on \nplot(t,Y2,'r')\ntitle(s2)\n```\n", "meta": {"hexsha": "20c7b85c5fd106ee58937cc454af39a8fd9dcb41", "size": 8055, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Computational/Intro to Numerical Computing/HW_Chap07.ipynb", "max_stars_repo_name": "XavierOwen/Notes", "max_stars_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-27T10:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-20T03:11:58.000Z", "max_issues_repo_path": "Computational/Intro to Numerical Computing/HW_Chap07.ipynb", "max_issues_repo_name": "XavierOwen/Notes", "max_issues_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Computational/Intro to Numerical Computing/HW_Chap07.ipynb", "max_forks_repo_name": "XavierOwen/Notes", "max_forks_repo_head_hexsha": "d262a9103b29ee043aa198b475654aabd7a2818d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-14T19:57:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T19:57:23.000Z", "avg_line_length": 29.7232472325, "max_line_length": 236, "alphanum_fraction": 0.4875232775, "converted": true, "num_tokens": 1783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799472560581, "lm_q2_score": 0.9653811591688145, "lm_q1q2_score": 0.9304150026657123}}
{"text": "# Exponentials, Radicals, and Logs\nUp to this point, all of our equations have included standard arithmetic operations, such as division, multiplication, addition, and subtraction. Many real-world calculations involve exponential values in which numbers are raised by a specific power.\n\n## Exponentials\nA simple case of of using an exponential is squaring a number; in other words, multipying a number by itself. For example, 2 squared is 2 times 2, which is 4. This is written like this:\n\n\\begin{equation}2^{2} = 2 \\cdot 2 = 4\\end{equation}\n\nSimilarly, 2 cubed is 2 times 2 times 2 (which is of course 8):\n\n\\begin{equation}2^{3} = 2 \\cdot 2 \\cdot 2 = 8\\end{equation}\n\nIn Python, you use the ****** operator, like this example in which **x** is assigned the value of 5 raised to the power of 3 (in other words, 5 x 5 x 5, or 5-cubed):\n\n\n```python\nx = 5**3\nprint(x)\n```\n\n 125\n\n\nMultiplying a number by itself twice or three times to calculate the square or cube of a number is a common operation, but you can raise a number by any exponential power. For example, the following notation shows 4 to the power of 7 (or 4 x 4 x 4 x 4 x 4 x 4 x 4), which has the value:\n\n\\begin{equation}4^{7} = 16384 \\end{equation}\n\nIn mathematical terminology, **4** is the *base*, and **7** is the *power* or *exponent* in this expression.\n\n## Radicals (Roots)\nWhile it's common to need to calculate the solution for a given base and exponential, sometimes you'll need to calculate one or other of the elements themselves. For example, consider the following expression:\n\n\\begin{equation}?^{2} = 9 \\end{equation}\n\nThis expression is asking, given a number (9) and an exponent (2), what's the base? In other words, which number multipled by itself results in 9? This type of operation is referred to as calculating the *root*, and in this particular case it's the *square root* (the base for a specified number given the exponential **2**). In this case, the answer is 3, because 3 x 3 = 9. We show this with a **√** symbol, like this:\n\n\\begin{equation}\\sqrt{9} = 3 \\end{equation}\n\nOther common roots include the *cube root* (the base for a specified number given the exponential **3**). For example, the cube root of 64 is 4 (because 4 x 4 x 4 = 64). To show that this is the cube root, we include the exponent **3** in the **√** symbol, like this:\n\n\\begin{equation}\\sqrt[3]{64} = 4 \\end{equation}\n\nWe can calculate any root of any non-negative number, indicating the exponent in the **√** symbol.\n\nThe **math** package in Python includes a **sqrt** function that calculates the square root of a number. To calculate other roots, you need to reverse the exponential calculation by raising the given number to the power of 1 divided by the given exponent:\n\n\n```python\nimport math\n\n# Calculate square root of 25\nx = math.sqrt(25)\nprint (x)\n\n# Calculate cube root of 64\ncr = round(64 ** (1. / 3))\nprint(cr)\n```\n\n 5.0\n 4\n\n\nThe code used in Python to calculate roots other than the square root reveals something about the relationship between roots and exponentials. The exponential root of a number is the same as that number raised to the power of 1 divided by the exponential. For example, consider the following statement:\n\n\\begin{equation} 8^{\\frac{1}{3}} = \\sqrt[3]{8} = 2 \\end{equation}\n\nNote that a number to the power of 1/3 is the same as the cube root of that number.\n\nBased on the same arithmetic, a number to the power of 1/2 is the same as the square root of the number:\n\n\\begin{equation} 9^{\\frac{1}{2}} = \\sqrt{9} = 3 \\end{equation}\n\nYou can see this for yourself with the following Python code:\n\n\n```python\nimport math\n\nprint (9**0.5)\nprint (math.sqrt(9))\n```\n\n 3.0\n 3.0\n\n\n## Logarithms\nAnother consideration for exponential values is the requirement occassionally to determine the exponent for a given number and base. In other words, how many times do I need to multiply a base number by itself to get the given result. This kind of calculation is known as the *logarithm*.\n\nFor example, consider the following expression:\n\n\\begin{equation}4^{?} = 16 \\end{equation}\n\nIn other words, to what power must you raise 4 to produce the result 16?\n\nThe answer to this is 2, because 4 x 4 (or 4 to the power of 2) = 16. The notation looks like this:\n\n\\begin{equation}log_{4}(16) = 2 \\end{equation}\n\nIn Python, you can calculate the logarithm of a number using the **log** function in the **math** package, indicating the number and the base:\n\n\n```python\nimport math\n\nx = math.log(16, 4)\nprint(x)\n```\n\n 2.0\n\n\nThe final thing you need to know about exponentials and logarithms is that there are some special logarithms:\n\nThe *common* logarithm of a number is its exponential for the base **10**. You'll occassionally see this written using the usual *log* notation with the base omitted:\n\n\\begin{equation}log(1000) = 3 \\end{equation}\n\nAnother special logarithm is something called the *natural log*, which is a exponential of a number for base ***e***, where ***e*** is a constant with the approximate value 2.718. This number occurs naturally in a lot of scenarios, and you'll see it often as you work with data in many analytical contexts. For the time being, just be aware that the natural log is sometimes written as ***ln***:\n\n\\begin{equation}log_{e}(64) = ln(64) = 4.1589 \\end{equation}\n\nThe **math.log** function in Python returns the natural log (base ***e***) when no base is specified. Note that this can be confusing, as the mathematical notation *log* with no base usually refers to the common log (base **10**). To return the common log in Python, use the **math.log10** function:\n\n\n```python\nimport math\n\n# Natural log of 29\nprint (math.log(29))\n\n# Common log of 100\nprint(math.log10(100))\n```\n\n 3.367295829986474\n 2.0\n\n\n## Solving Equations with Exponentials\nOK, so now that you have a basic understanding of exponentials, roots, and logarithms; let's take a look at some equations that involve exponential calculations.\n\nLet's start with what might at first glance look like a complicated example, but don't worry - we'll solve it step-by-step and learn a few tricks along the way:\n\n\\begin{equation}2y = 2x^{4} ( \\frac{x^{2} + 2x^{2}}{x^{3}} ) \\end{equation}\n\nFirst, let's deal with the fraction on the right side. The numerator of this fraction is x<sup>2</sup> + 2x<sup>2</sup> - so we're adding two exponential terms. When the terms you're adding (or subtracting) have the same exponential, you can simply add (or subtract) the coefficients. In this case, x<sup>2</sup> is the same as 1x<sup>2</sup>, which when added to 2x<sup>2</sup> gives us the result 3x<sup>2</sup>, so our equation now looks like this: \n\n\\begin{equation}2y = 2x^{4} ( \\frac{3x^{2}}{x^{3}} ) \\end{equation}\n\nNow that we've condolidated the numerator, let's simplify the entire fraction by dividing the numerator by the denominator. When you divide exponential terms with the same variable, you simply divide the coefficients as you usually would and subtract the exponential of the denominator from the exponential of the numerator. In this case, we're dividing 3x<sup>2</sup> by 1x<sup>3</sup>: The coefficient 3 divided by 1 is 3, and the exponential 2 minus 3 is -1, so the result is 3x<sup>-1</sup>, making our equation:\n\n\\begin{equation}2y = 2x^{4} ( 3x^{-1} ) \\end{equation}\n\nSo now we've got rid of the fraction on the right side, let's deal with the remaining multiplication. We need to multiply 3x<sup>-1</sup> by 2x<sup>4</sup>. Multiplication, is the opposite of division, so this time we'll multipy the coefficients and add the exponentials: 3 multiplied by 2 is 6, and -1 + 4 is 3, so the result is 6x<sup>3</sup>:\n\n\\begin{equation}2y = 6x^{3} \\end{equation}\n\nWe're in the home stretch now, we just need to isolate y on the left side, and we can do that by dividing both sides by 2. Note that we're not dividing by an exponential, we simply need to divide the whole 6x<sup>3</sup> term by two; and half of 6 times x<sup>3</sup> is just 3 times x<sup>3</sup>:\n\n\\begin{equation}y = 3x^{3} \\end{equation}\n\nNow we have a solution that defines y in terms of x. We can use Python to plot the line created by this equation for a set of arbitrary *x* and *y* values:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = 3*df['x']**3\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"magenta\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nNote that the line is curved. This is symptomatic of an exponential equation: as values on one axis increase or decrease, the values on the other axis scale *exponentially* rather than *linearly*.\n\nLet's look at an example in which x is the exponential, not the base:\n\n\\begin{equation}y = 2^{x} \\end{equation}\n\nWe can still plot this as a line:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with an x column containing values from -10 to 10\ndf = pd.DataFrame ({'x': range(-10, 11)})\n\n# Add a y column by applying the slope-intercept equation to x\ndf['y'] = 2.0**df['x']\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.x, df.y, color=\"magenta\")\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid()\nplt.axhline()\nplt.axvline()\nplt.show()\n```\n\nNote that when the exponential is a negative number, Python reports the result as 0. Actually, it's a very small fractional number, but because the base is positive the exponential number will always positive. Also, note the rate at which y increases as x increases - exponential growth can be be pretty dramatic.\n\nSo what's the practical application of this?\n\nWell, let's suppose you deposit $100 in a bank account that earns 5% interest per year. What would the balance of the account be in twenty years, assuming you don't deposit or withdraw any additional funds?\n\nTo work this out, you could calculate the balance for each year:\n\nAfter the first year, the balance will be the initial deposit ($100) plus 5% of that amount:\n\n\\begin{equation}y1 = 100 + (100 \\cdot 0.05) \\end{equation}\n\nAnother way of saying this is:\n\n\\begin{equation}y1 = 100 \\cdot 1.05 \\end{equation}\n\nAt the end of year two, the balance will be the year one balance plus 5%:\n\n\\begin{equation}y2 = 100 \\cdot 1.05 \\cdot 1.05 \\end{equation}\n\nNote that the interest for year two, is the interest for year one multiplied by itself - in other words, squared. So another way of saying this is:\n\n\\begin{equation}y2 = 100 \\cdot 1.05^{2} \\end{equation}\n\nIt turns out, if we just use the year as the exponent, we can easily calculate the growth after twenty years like this:\n\n\\begin{equation}y20 = 100 \\cdot 1.05^{20} \\end{equation}\n\nLet's apply this logic in Python to see how the account balance would grow over twenty years:\n\n\n```python\nimport pandas as pd\n\n# Create a dataframe with 20 years\ndf = pd.DataFrame ({'Year': range(1, 21)})\n\n# Calculate the balance for each year based on the exponential growth from interest\ndf['Balance'] = 100 * (1.05**df['Year'])\n\n#Display the dataframe\nprint(df)\n\n# Plot the line\n%matplotlib inline\nfrom matplotlib import pyplot as plt\n\nplt.plot(df.Year, df.Balance, color=\"green\")\nplt.xlabel('Year')\nplt.ylabel('Balance')\nplt.show()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "07a2862422e06b9505a6e51f4e3e9b9e94883028", "size": 55729, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Basics Of Algebra by Hiren/01-04-Exponentials Radicals and Logarithms.ipynb", "max_stars_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Basics Of Algebra by Hiren/01-04-Exponentials Radicals and Logarithms.ipynb", "max_issues_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Basics Of Algebra by Hiren/01-04-Exponentials Radicals and Logarithms.ipynb", "max_forks_repo_name": "serkin/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "ac0ae9fad82a9f0429c93e3da744af6e6d63e5ab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 103.7783985102, "max_line_length": 14720, "alphanum_fraction": 0.8348256742, "converted": true, "num_tokens": 3193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799451753696, "lm_q2_score": 0.9597620580957161, "lm_q1q2_score": 0.9249994237328891}}
{"text": "# I. Linear least squares approximation\n\nConsider a function $y = f(x)$ which is defined by a set of values $y_0, y_1, \\cdots, y_n$ at points $x_0, x_1, \\cdots, x_n$.\n\n\n```python\nx = [-1, -0.7, -0.43, -0.14, -0.14, 0.43, 0.71, 1, 1.29, 1.57, 1.86, 2.14, 2.43, 2.71, 3]\ny = [-2.25, -0.77, 0.21, 0.44, 0.64, 0.03, -0.22, -0.84, -1.2, -1.03, -0.37, 0.61, 2.67, 5.04, 8.90]\n```\n\n### I.I. Find a best fit polynomial\n\n$$\nP_m(x) = a_0 + a_1 x + \\cdots + a_m x^m\n$$\n\nusing the linear least squares approach. To this end\n\n1. implement a function which constructs the design matrix using $1, x, \\cdots, x^m$ as the basis functions.\n\n2. construct explicitly the normal system of equations of the linear least squares problem at fixed $m$.\n\n3. Solve the normal equations to find the coefficients of $P_m(x)$ for $m = 0, 1, 2, \\dots$. For the linear algebra problem, you can either use library functions (`numpy.linalg.solve`) or your LU factorization code from week 1.\n\n(20% of the total grade)\n\n\n```python\n# ... ENTER YOUR CODE HERE\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef design_matrix(x, m):\n mat = np.empty(shape=[len(x), m])\n for i in range(m):\n mat[:, i] = np.power(x, i) \n return mat\n\ndef solve_normal_equation(x, y, m):\n A=design_matrix(x, m)\n AT_A=A.T@A\n b=A.T@y\n beta=np.linalg.solve(AT_A,b)\n return beta\n\ndef predict(xval, beta):\n term = sum(beta[j]*xval**j for j in range(len(beta)))\n return term\n```\n\n\n```python\nsolve_normal_equation(x, y, 4)\n```\n\n\n\n\n array([ 0.49483598, -0.26983377, -2.01973166, 1.01540301])\n\n\n\n### I.II \n\nTo find the optimal value of m, use the following criterion: take $m=0, 1, 2, \\dots$, for each value of $m$ compute \n\n$$\n\\sigma_m^2 = \\frac{1}{n - m} \\sum_{k=0}^n \\left( P_m(x_k) - y_k \\right)^2\n$$\n\nAnd take the value of $m$, at which $\\sigma_m$ stabilizes or starts increasing.\n\n(20% of the total grade)\n\n\n```python\n# ... ENTER YOUR CODE HERE ...\ndef compute_sigma(x, y, m):\n beta = solve_normal_equation(x, y, m)\n y_predict = np.array([predict(_, beta) for _ in x])\n n=len(x)\n sigma = np.sum(np.square(y_predict - np.array(y))) / (n - m)\n return sigma\n\nsigma = []\nm_range = range(10)\nsigmas = [compute_sigma(x, y, m) for m in m_range]\nplt.plot(m_range, sigmas)\nplt.show()\n```\n\nPlot your polynomials $P_m(x)$ on one plot, together with the datapoints. Visually compare best-fit polynomials of different degrees. Is the visual comparison consistent with the optimal value of $m$?\n\n\n```python\n# ... ENTER YOUR CODE HERE\nplt.scatter(x,y)\nfor m in range(5):\n beta = solve_normal_equation(x, y, m)\n y_predict = [predict(_, beta) for _ in x]\n #print(beta)\n plt.plot(x, y_predict, label=m)\n plt.legend()\nplt.show()\n```\n\n### I.III. Linear least-squares using the QR factorization.\n\nFor the optimal value of $m$ from the previous part, solve the LLS problem using the QR factorization, withou ever forming the normal equations explicitly. For linear algebra, you can use standard library functions (look up `numpy.linalg.solve`, `numpy.linalg.qr` etc) or your code from previous weeks.\n\nCompare the results with the results of solving the normal system of equations.\n\n(20% of the grade)\n\n\n```python\n# ... ENTER YOUR CODE HERE ...\ndef solve_normal_equation_qr(x, y, m):\n A=design_matrix(x, m)\n Q, R = np.linalg.qr(A) #factorize\n y_rotated = Q.T@y # rotate y by Q.T\n beta=np.linalg.solve(R[:m,:], y_rotated[:m]) #solve R1*beta = f\n return beta\n```\n\n\n```python\n# ... ENTER YOUR CODE HERE\nplt.scatter(x,y)\nfor m in range(1,5):\n beta = solve_normal_equation_qr(x, y, m)\n y_predict = [predict(_, beta) for _ in x]\n print(beta)\n plt.plot(x, y_predict, label=m)\n plt.legend()\nplt.show()\n```\n\n# II. Lagrange interpolation\n\n### II.1 \n\nConsider the function, $f(x) = x^2 \\cos{x}$. On the interval $x\\in [\\pi/2, \\pi]$, interpolate the function using the Lagrange interpolating polynomial of degree $m$ with $m=1, 2, 3, 4, 5$. Use the uniform mesh. Plot the resulting interpolants together with $f(x)$.\n\n(20% of the total grade)\n\n\n```python\n# ... ENTER YOUR CODE HERE ...\ndef f(x):\n return (x**2)*np.cos(x)\n\ndef lagrange_k(xval, xk, k):\n n = len(xk)\n term = 1.0\n for j in range(n):\n if j==k: \n continue\n num = xval - xk[j]\n den = xk[k] - xk[j]\n term *= num / den\n return term\n\ndef lagrange(xval, xk, yk):\n return sum(yk[j] * lagrange_k(xval, xk, j) for j in range(len(xk)))\n```\n\n\n```python\nimport numpy as np\nimport sympy\nimport matplotlib.pyplot as plt\n#plt.style.use('fivethirtyeight')\n\n#%matplotlib notebook\n\ndef plot_interp(func, nodes, add_legend=True):\n #tabulate\n yy = func(nodes)\n \n #interpolate and evaluate on a finer grid\n xn = np.linspace(np.pi/2, np.pi, 201) \n yn = [lagrange(_, nodes, yy) for _ in xn]\n \n #plot\n plt.plot(xn, yn, '-', alpha=0.7, label=r'interp, $n=%s$'%len(nodes))\n plt.plot(xn, func(xn), label=r'$f(x)$')\n plt.plot(nodes, yy, 'o', ms=7)\n if add_legend:\n plt.legend(loc='best')\n #s = r\"$f(x) = %s $\" % sympy.printing.latex(func(sympy.Symbol('x')))\n #plt.text(-1, 0.9, s, fontsize=22)\n```\n\n\n```python\nnum_points = 3\nnodes = np.linspace(np.pi/2, np.pi, num_points)\nplot_interp(f, nodes)\n```\n\n\n```python\n#alternate plot\nxv=np.linspace(np.pi/2, np.pi, 201)\nfv=[f(x) for x in xv]\nplt.plot(xv,fv, label=\"original\")\n\n###lagrange roots\nfor m in range(2, 5):\n xv_m = np.linspace(np.pi/2,np.pi, m)\n yv_m = [f(x) for x in xv_m]\n langv = [lagrange(_, xv_m, yv_m) for _ in xv]\n # remove this to see result\n plt.plot(xv, langv, label=m)\n \nplt.legend()\nplt.show()\n```\n\n### II.2. \n\nRepeat the previous task using the Chebyshev nodes. Compare the quality of interpolation on a uniform mesh and Chebyshev nodes for $m=3$.\n\n(20% of the total grade)\n\n\n```python\n# ... ENTER YOUR CODE HERE ...\ndef cheb_nodes(n):\n k = np.arange(n)\n return np.cos((2*k+1)*np.pi/(2*n))\n```\n\n\n```python\nnum_points = 3\nrightrange = np.pi\nleftrange = np.pi/2\nnonscaled_nodes = cheb_nodes(num_points)\nnodes = (rightrange-leftrange)/(1-(-1))*(nonscaled_nodes-(-1)) + leftrange\nplot_interp(f, nodes)\n```\n\n\n```python\n#alternate plot\nxv=np.linspace(np.pi/2, np.pi, 201)\nfv=[f(x) for x in xv]\nplt.plot(xv,fv, label=\"original\")\n\n###lagrange roots\nfor m in range(2, 5):\n xv_m = (rightrange-leftrange)/(1-(-1))*(cheb_nodes(m)-(-1)) + leftrange\n yv_m = [f(x) for x in xv_m]\n langv = [lagrange(_, xv_m, yv_m) for _ in xv]\n # remove this to see result\n plt.plot(xv, langv, label=m)\n \nplt.legend()\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "1c1b59269a45c36fe76dcd336c2b57eb888644b2", "size": 143413, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NumericalAnalysis/Week5/week_5_intep_approx.ipynb", "max_stars_repo_name": "pradeeptadas/coursera", "max_stars_repo_head_hexsha": "c3b7daddaca9ba67de2bf488283ede6fe7bd560b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NumericalAnalysis/Week5/week_5_intep_approx.ipynb", "max_issues_repo_name": "pradeeptadas/coursera", "max_issues_repo_head_hexsha": "c3b7daddaca9ba67de2bf488283ede6fe7bd560b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumericalAnalysis/Week5/week_5_intep_approx.ipynb", "max_forks_repo_name": "pradeeptadas/coursera", "max_forks_repo_head_hexsha": "c3b7daddaca9ba67de2bf488283ede6fe7bd560b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 285.6832669323, "max_line_length": 23496, "alphanum_fraction": 0.9242676745, "converted": true, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551576415562, "lm_q2_score": 0.9579122753885635, "lm_q1q2_score": 0.9242465994768142}}
{"text": "## Linear Regression using Gradient Descent\n\nIn this notebook, I've built a simple linear regression model using gradient descent to fit a line ($y = mx + c$) through input data consisting of ($x, y$) values. The purpose is to better understand gradient descent by calculating the gradients by hand and implementing it without using out-of-the-box libraries/ methods.\n\n### Problem Statement\n\n**Given a set of $x$ and $y$ values, the problem statement here is to find a line \"$y = mx + b$\" that best fits the data**. This involes finding the values of $m$ and $b$ that minimizes an _Error/ Loss_ function for the given dataset. We will use _Mean Squared Error (denoted as E)_ as the error function to be minimized, and it is given by - \n\n$E = \\dfrac{1}{N} \\sum_{i=1}^N (y_i - (mx_i + b))^2$\n\nTo find the optimial value of $m$ and $b$ that minimizes the error function using Gradient Descent, the values are randomly initialized first and then updated $number of steps$ times or until the error function value converges. Below equations are used to update the values of $m$ and $b$ at each step -\n\n$\nm = m - learning\\_rate \\times \\dfrac{\\partial E}{\\partial m}\n$\n\n$\nb = b - learning\\_rate \\times \\dfrac{\\partial E}{\\partial b}\n$\n\n### Calculating Gradients for Mean Squared Error \n\nThe Gradient Descent update formulae given above needs the partial derivatives of error function $E$ with respect to both $m$ and $b$ ($\\dfrac{\\partial E}{\\partial m}$ and $\\dfrac{\\partial E}{\\partial b}$ respectively). These partial derivatives are calculated as follows -\n\n$\n\\begin{align}\nE &= \\dfrac{1}{N} \\sum_{i=1}^N (y_i - (mx_i + b))^2 \\\\\n &= \\dfrac{1}{N} \\sum_{i=1}^N y_i^2 - 2y_i(mx_i + b) + (mx_i + b)^2 \\\\ \n &= \\dfrac{1}{N} \\sum_{i=1}^N y_i^2 - 2x_iy_im - 2y_ib + x_i^2m^2 + 2x_imb + b^2 \\\\\n\\end{align}\n$\n\n$\n\\begin{align}\n\\dfrac{\\partial E}{\\partial m} &= \\dfrac{1}{N} \\sum_{i=1}^N 0 - 2x_iy_i - 0 + 2x_i^2m + 2x_ib + 0 \\\\\n &= \\dfrac{-2}{N} \\sum_{i=1}^N x_i(y_i - (mx_i + b))\n\\end{align}\n$\n\n$\n\\begin{align}\n\\dfrac{\\partial E}{\\partial b} &= \\dfrac{1}{N} \\sum_{i=1}^N 0 - 0 - 2y_i + 0 + 2x_im + 2b \\\\\n &= \\dfrac{-2}{N} \\sum_{i=1}^N (y_i - (mx_i + b))\n\\end{align}\n$\n\n\n\n\n\n\n## Implementation\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n\ndef plot_fit(points, m, b, step, error):\n '''\n Plots a scatterplot of points, with a line defined by m and b.\n Also shows the current step number in Gradient Descent and \n current error value.\n '''\n \n x_values = [p[0] for p in points]\n y_values = [p[1] for p in points]\n \n plt.scatter(x_values, y_values, color='skyblue') \n fit_xvalues = list(range(int(min(x_values)), int(max(x_values))))\n fit_yvalues = [m * fit_x + b for fit_x in fit_xvalues]\n plt.plot(fit_xvalues, fit_yvalues, color='blue')\n plt.title('Step: ' + str(step) + ', Error:' + str(round(error, 2)))\n plt.show()\n\ndef mean_squared_error(points, m, b):\n '''\n Calculates Mean Squared Error for the line defined by m & b\n with the given points.\n '''\n n = len(points)\n error = 0\n \n for i in range(n):\n x_i = points[i, 0]\n y_i = points[i, 1]\n \n error += (y_i - (m * x_i + b)) **2\n \n error = float(error) / n\n \n return error\n\ndef gradient_step(points, current_m, current_b, learning_rate):\n '''\n Calculates gradients and new values for m and b based on\n current values of m and b and given learning rate.\n '''\n gradient_m = 0\n gradient_b = 0\n \n n = len(points)\n \n for i in range(n):\n x_i = float(points[i, 0])\n y_i = float(points[i, 1])\n \n gradient_m += (-2 / n) * (x_i * (y_i - (current_m * x_i + current_b)))\n gradient_b += (-2 / n) * (y_i - (current_m * x_i + current_b))\n \n new_m = current_m - learning_rate * gradient_m\n new_b = current_b - learning_rate * gradient_b\n new_error = mean_squared_error(points, new_m, new_b)\n \n return [new_m, new_b, new_error]\n \ndef gradient_descent(points, initial_m, initial_b, learning_rate, num_steps):\n '''\n Runs Gradient Descent for the given points, starting with the initial\n m and b values, and the given learning rate for the given number of steps.\n '''\n m = initial_m\n b = initial_b\n \n error_vec = list()\n \n # Update m and b for each gradient descent step\n for step in range(num_steps):\n \n [m, b, error] = gradient_step(points, m, b, learning_rate)\n\n # Plot the current fit once every 100 steps to track progress\n if not step % 100: \n plot_fit(points, m, b, step, error)\n \n error_vec.append(error)\n \n # Plot the error function value for each step\n plt.plot(error_vec, color='red')\n plt.xlabel('Number of Steps')\n plt.ylabel('Mean Squared Error')\n plt.show()\n \n return [m, b]\n\ndef run():\n points = np.genfromtxt('data.csv', delimiter=',')\n \n initial_m = 0\n initial_b = 0\n \n learning_rate = 0.0001\n num_steps = 1000\n \n m, b = gradient_descent(points, initial_m, initial_b, learning_rate, num_steps)\n \nif __name__ == '__main__':\n run()\n```\n", "meta": {"hexsha": "afcce2eb1243b440cade80763e0b905211712b81", "size": 172593, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "linear-regression-gradient-descent/gradient_descent.ipynb", "max_stars_repo_name": "cijogeorge/workspace-machine-learning", "max_stars_repo_head_hexsha": "a8d16d4b1fa6a9549eff28307e3e2f73bc661038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear-regression-gradient-descent/gradient_descent.ipynb", "max_issues_repo_name": "cijogeorge/workspace-machine-learning", "max_issues_repo_head_hexsha": "a8d16d4b1fa6a9549eff28307e3e2f73bc661038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear-regression-gradient-descent/gradient_descent.ipynb", "max_forks_repo_name": "cijogeorge/workspace-machine-learning", "max_forks_repo_head_hexsha": "a8d16d4b1fa6a9549eff28307e3e2f73bc661038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 553.1826923077, "max_line_length": 15610, "alphanum_fraction": 0.9247420231, "converted": true, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9719924818279465, "lm_q2_score": 0.9504109745579498, "lm_q1q2_score": 0.9237923219170989}}
{"text": "## Symbolic Mathematics with [Sympy](http://docs.sympy.org/latest/tutorial/intro.html)\n\n\n\n```python\nimport sympy as sym\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n#### declare symbolic variables \n\n\n```python\nx = sym.Symbol('x')\ny = sym.Symbol('y')\n```\n\nor\n\n\n```python\nx, y = sym.symbols('x y')\n```\n\n#### declare the matematical expression $xy\\exp[-(x^2+y^2)]$\n\n\n```python\nexpr = x*y*sym.exp(-(x**2+y**2))\n```\n\n#### print the `LaTeX` expression\n\n\n```python\nsym.latex(expr)\n```\n\n#### expand an expression\n\n\n```python\nexpr.expand()\n```\n\n\n```python\nsym.expand( (x-y)**3 )\n```\n\n\n```python\nsym.expand_trig(sym.cos(2*x))\n```\n\n#### simplify an expression\n\n\n```python\nsym.simplify( sym.sin(x) * ( sym.sin(x)**2 + sym.cos(x)**2 ) / sym.tan(x) )\n```\n\n#### Task: declare and simplify the expression $\\left(2 \\cos^{2}{\\left (u \\right )} - 1\\right) \\sin{\\left (v \\right )} + 2 \\sin{\\left (u \\right )} \\cos{\\left (u \\right )} \\cos{\\left (v \\right )}$\n\n\n```python\nx,y = sym.symbols('u v')\nexpr = (2*sym.cos(x)**2 - 1)*sym.sin(y) + 2*sym.sin(x)*sym.cos(x)*sym.cos(y)\nsimplified = sym.simplify(expr)\nprint( sym.latex(simplified) )\n```\n\n* Limit, Integral, and Derivative represent the unevaluated calculation\n* limit, integrate, and diff perform the calculation\n\n#### limits: calculate $\\lim_{x \\to \\frac{\\pi}{2}} \\tan{\\left (x \\right )}$\n\n\n```python\nx = sym.Symbol('x')\n```\n\n\n```python\nprint( sym.latex( sym.Limit( sym.tan(x), x, sym.pi/2, dir='+' ) ), '=' )\nsym.limit( sym.tan(x), x, sym.pi/2, dir='+' )\n```\n\n\n```python\nsym.limit( sym.tan(x), x, sym.pi/2, dir='-' )\n```\n\n#### Task: using `sym.Integral`, `sym.integrate`, and `sym.latex` calculate and print the integral $\\int x y e^{- x^{2} - y^{2}}\\, dx$ and its solution\n\n\n```python\nx,y = sym.symbols('x y')\nexpr = x*y*sym.exp(-(x**2+y**2))\nprint( sym.latex( sym.Integral(expr, x) ), '=', sym.latex( sym.integrate(expr, x) ))\n```\n\n#### Task: calculate and print the integral $\\int_{-2}^{2}\\int_{-2}^{2} x y e^{- x^{2} - y^{2}}\\, dx\\, dy$ and its solution\n\n\n```python\nprint( sym.latex( sym.Integral(expr, [x,-2,2], [y,-2,2] ) ), '=', sym.latex( sym.integrate(expr, [x,-2,2], [y,-2,2] ) ) )\n```\n", "meta": {"hexsha": "753f0b01db32d24f17c7a6d66538aca645bb8eee", "size": 7317, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "2017/lectures/03-sympy.ipynb", "max_stars_repo_name": "urania277/jupyter-course", "max_stars_repo_head_hexsha": "20060173e7355fc4726148f00b61404d2613b74b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2017/lectures/03-sympy.ipynb", "max_issues_repo_name": "urania277/jupyter-course", "max_issues_repo_head_hexsha": "20060173e7355fc4726148f00b61404d2613b74b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2017/lectures/03-sympy.ipynb", "max_forks_repo_name": "urania277/jupyter-course", "max_forks_repo_head_hexsha": "20060173e7355fc4726148f00b61404d2613b74b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-20T14:45:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-20T14:45:43.000Z", "avg_line_length": 19.3571428571, "max_line_length": 218, "alphanum_fraction": 0.4869482028, "converted": true, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9780517424466175, "lm_q2_score": 0.9433475792711057, "lm_q1q2_score": 0.9226427436389035}}
{"text": "# Daily Coding Problem 14: Find $\\pi$ using a Monte Carlo Method\n\nThe area of a circle is defined as $\\pi r^{2}$. Estimate $\\pi$ to 3 decimal places using a Monte Carlo method.\n\n\n## Visualising the Geometry\n\nThe equation of a circle whose centre is at the origin is:\n\n\\begin{equation}\nr^{2} = x^{2} + y^{2}\n\\end{equation}\nwhere $r$ is the radius of the circle. As a circle can be thought of as a polygon with an infinite number of sides, a line plot joining a significantly large number of points along the edge of the circle can approximate its shape. Both $x$- and $y$-values vary from $-r$ to $r$, assuming that the centre of the circle lies at the origin. Given the $x$-position, the equation of a circle can be rearranged to yield an equation for $y$:\n\n\\begin{equation}\ny = \\pm\\sqrt{\\left(r^{2} - x^{2}\\right)}\n\\end{equation}\n\nSimply plotting the positive $y$-values as a function of $x$ will result in a semi-circle. It is necessary to include the negative $y$-values and their corresponding $x$-positions to complete the circle.\n\nThis produces the circle below, inscribed in a square of side $2r$:\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\ndef CirclePoints(x, r):\n \"\"\"Given list of x-coordinates, returns two lists of y-coordinates to plot circle around origin.\"\"\"\n return np.sqrt(r**2 - x**2), -np.sqrt(r**2 - x**2)\n\ndef SquarePoints(r):\n \"\"\"Given radius of circle, return vertices of square in which circle is inscribed.\"\"\"\n x = [-r, -r, r, r, -r]\n y = [-r, r, r, -r, -r]\n return x, y\n\ncircle_radius = 1.0 # Define radius r of circle\n\nx = np.linspace(-circle_radius, circle_radius, int(circle_radius)*100) # x-coordinates\n\n# y-coordinates for semi-circles at positive and negative y-values\ny_pos, y_neg = CirclePoints(x, circle_radius)\ny = np.append(y_pos, list(reversed(y_neg))) # Merge y-coordinates\n\n# Append x-coordinates with x-values for negative y-positions\nx = np.append(x, list(reversed(x)))\n\n# Draw circle\nfig0 = plt.figure(figsize=(8,8), facecolor='w', edgecolor='k')\nplt.plot(x, y, color='k')\nplt.grid()\nplt.axis('equal')\nplt.xlabel(\"x (arbitrary units)\")\nplt.ylabel(\"y (arbitrary units)\")\n\n# Draw square in which circle is inscribed\nx_sq, y_sq = SquarePoints(circle_radius)\nplt.plot(x_sq, y_sq, color='b')\n\n# Draw line to represent radius of circle\nplt.plot([0.0, circle_radius], [0.0, 0.0], color='red')\nplt.annotate(r\"$r$\", xy=(circle_radius/2, circle_radius/16.0), color='r', size=20)\n\nplt.show()\n```\n\n## Determination of $\\pi$\n\nThe area of the circle $A_{c}$ is given by $\\pi r^{2}$. The circle is incribed by a square of area $A_{s} = 2r\\times 2r = 4r^{2}$. Therefore, the ratio of $A_{c}$ to $A_{s}$ is given by:\n\n\\begin{equation}\n\\frac{A_{c}}{A_{s}} = \\frac{\\pi r^{2}}{4r^{2}} = \\frac{\\pi}{4}\n\\end{equation}\n\nIt is apparent from the diagram above that $A_{c} < A_{s}$, therefore it can be inferred that $\\pi < 4$. The equation of the ratios can be rearranged to yield one for $\\pi$:\n\n\\begin{equation}\n\\pi = 4\\frac{A_{c}}{A_{s}}\n\\end{equation}\n\nIn order to lie within the square, a point must have coordinates such that $-r\\le x\\le r$ and $-r\\le y\\le r$. If this point also lies within the boundaries of the circle, from the equation of the circle above, it must have coordinates such that:\n\n\\begin{equation}\nr\\ge \\sqrt{x^{2} + y^{2}}\n\\end{equation}\n\nBy generating a large number of points with coordinates that lie within the square, and determining the proportion of these that lie within the circle, the ratio $\\frac{A_{c}}{A_{s}}$ can be approximated.\n\nThe following line can be commented out should the random seed not be predetermined:\n\n\n```python\n# Set random seed; comment out if random seed is not predetermined\nrandom.seed(1)\n```\n\n\n```python\ndef WithinCircleCheck(x, y, r):\n \"\"\"Determines whether point with coordinates (x,y) lies within circle of radius r and returns True if so.\"\"\"\n return r > np.sqrt(x**2 + y**2)\n\nn_points = 1000000 # Number of points to be generated\n\n# Generate lists of x- and y-coordinates for points that lie within the square\npoints_x = []\npoints_y = []\nfor point in range(n_points):\n points_x.append(random.uniform(-circle_radius, circle_radius))\n points_y.append(random.uniform(-circle_radius, circle_radius))\n\npoints_x = np.array(points_x)\npoints_y = np.array(points_y)\n\n# Boolean array to determine whether each generated point lies within circle\nwithin_circle = WithinCircleCheck(points_x, points_y, circle_radius)\n\n# Plot positions of first 100 generated points\nif n_points < 100:\n n_plot = n_points\nelse:\n n_plot = 100\n\nfig1 = plt.figure(figsize=(8,8), facecolor='w', edgecolor='k')\nplt.plot(x, y, color='k')\nplt.grid()\nplt.axis('equal')\nplt.xlabel(\"x (arbitrary units)\")\nplt.ylabel(\"y (arbitrary units)\")\nplt.plot(x_sq, y_sq, color='b')\n\nplt.scatter(points_x[:n_plot], points_y[:n_plot], color='r')\nplt.title(\"First {} Generated Points\".format(n_plot))\n\nplt.show()\n```\n\nAs shown by the positions of the first few generated points above, a proportion of them lie within the circle. Using the equation for $\\pi$ given above, its value can be determined by multiplying the proportion of these points by four:\n\n\n```python\ndef Determine_pi(prop_in_circle):\n \"\"\"Returns estimation of pi based on proportion of points that lie within circle.\"\"\"\n return 4 * list(prop_in_circle).count(True) / float(len(prop_in_circle))\n\n# Print value of pi to 3 decimal places\nprint(\"The value of pi = {:.3f}\".format(Determine_pi(within_circle)))\n```\n\n The value of pi = 3.141\n\n\n## The Point of Diminishing Returns\n\nIt would be interesting to see how quickly the value converges.\n\n\n```python\n# Lists for pi values and points at sampling positions\npi_values = []\npoint_gen = []\n\n# Take sample of 100 points and determine pi approximations\nfor point in range(0, n_points, n_points//n_plot):\n pi_values.append(Determine_pi(within_circle[:point+1]))\n point_gen.append(point+1)\n\n# Plot evolution of approximate pi value with number of generated points\nfig2 = plt.figure(figsize=(14,10), facecolor='w', edgecolor='k')\nplt.subplot(2, 1, 1)\nplt.plot(point_gen, pi_values, color='k')\nplt.plot([point_gen[0], point_gen[-1]], [np.pi, np.pi], color='r')\n# Show line for pi on plot\nplt.annotate(r\"$\\pi$\", xy=(point_gen[-1]/10, np.pi), xytext=(point_gen[-1]/5, np.pi+0.005),\n color='r', size=20, arrowprops=dict(facecolor='r', edgecolor='r', shrink=0.05))\nplt.grid()\nplt.ylim(3.13, 3.15)\nplt.title(r\"Improvement in Approximation of $\\pi$ with Number of Generated Points\")\nplt.xlabel(\"Number of Generated Points\")\nplt.ylabel(r\"Approximation of $\\pi$\")\n\n# Plot deviation of approximate pi value from true value\nplt.subplot(2, 1, 2)\npi_residual = np.array(pi_values) - np.pi\nplt.plot(point_gen, pi_residual, color='k')\nplt.grid()\nplt.ylim(-0.0025, 0.0025)\nplt.title(r\"Deviation of Approximation of $\\pi$ from True Value\")\nplt.xlabel(\"Number of Generated Points\")\nplt.ylabel(r\"$\\pi$ $-$ (Approximation of $\\pi$)\")\n\nplt.tight_layout()\nplt.show()\n```\n\nAfter about 100,000 generated points, the value of $\\pi$ can be approximated to 2 decimal places with reasonable confidence. As expected, as the number of generated points increases, the deviation from the expected value of $\\pi$ decreases. However, the magnitude of these improvements decreases with each successive generated point.\n\nIt is difficult to state with certainty where the point of diminishing returns lies. In the case of determining $\\pi$ to 2 decimal places, it could be said that this point lies after 100,000 generations as no improvement is seen beyond this point. However, the problem asks for a solution to 3 decimal places. After approximately 450,000 points have been generated, the approximate value of $\\pi$ lies within the boundaries $3.141\\le \\pi\\le 3.143$. It can be argued that beyond this point, little improvement in the approximation is seen and its value is close enough to the true value to provide a valid answer.\n\n\n```python\n\n```\n", "meta": {"hexsha": "35ea1c1c23344342f3f57b8523165a378a603a0e", "size": 191342, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "solutions/014_piMonteCarlo.ipynb", "max_stars_repo_name": "hchagani/dailyCodingProblems", "max_stars_repo_head_hexsha": "93e64fa0817ed94d629265351daae68ee10bdb6d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solutions/014_piMonteCarlo.ipynb", "max_issues_repo_name": "hchagani/dailyCodingProblems", "max_issues_repo_head_hexsha": "93e64fa0817ed94d629265351daae68ee10bdb6d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solutions/014_piMonteCarlo.ipynb", "max_forks_repo_name": "hchagani/dailyCodingProblems", "max_forks_repo_head_hexsha": "93e64fa0817ed94d629265351daae68ee10bdb6d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 596.0809968847, "max_line_length": 90594, "alphanum_fraction": 0.9345987812, "converted": true, "num_tokens": 2140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9632305349799242, "lm_q2_score": 0.9572778012346835, "lm_q1q2_score": 0.9220792086076898}}
{"text": "## Exercise 03.1\n\nCompare the computed values of \n\n$$ \nd_0 = a \\cdot b + a \\cdot c\n$$\n\nand \n\n$$ \nd_1 = a \\cdot (b + c)\n$$\n\nwhen $a = 100$, $b = 0.1$ and $c = 0.2$. Store $d_{0}$ in the variable `d0` and $d_{1}$ in the variable `d1`.\n\n\nTry checking for equality, e.g. `print(d0 == d1)`. \n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\nassert d0 == 30.0\nassert d1 != 30.0\nassert d0 != d1\n```\n\n## Exercise 03.2\n\nFor the polynomial \n\\begin{align}\nf(x, y) &= (x + y)^{6} \n\\\\\n&= x^6 + 6x^{5}y + 15x^{4}y^{2} + 20x^{3}y^{3} + 15x^{2}y^{4} + 6xy^{5} + y^{6}\n\\end{align}\ncompute $f$ using: (i) the compact form $(x + y)^{6}$; and (ii) the expanded form for:\n\n(a) $x = 10$ and $y = 10.1$\n\n(b) $x = 10$ and $y = -10.1$\n\nand compare the number of significant digits for which the answers are the same.\nStore the answer for the compact version using the variable `f0`, and using the variable `f1` for the expanded version.\n\nFor case (b), compare the computed and analytical solutions and consider the relative error.\nWhich approach would you recommend for computing this expression?\n\n#### (a) $x = 10$ and $y = 10.1$\n\n\n```python\nx = 10.0\ny = 10.1\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\nimport math\nassert math.isclose(f0, 65944160.60120103, rel_tol=1e-10)\nassert math.isclose(f1, 65944160.601201, rel_tol=1e-10)\n```\n\n#### (b) $x = 10$ and $y = -10.1$\n\n\n```python\nx = 10.0\ny = -10.1\n\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n\n```python\nimport math\nassert math.isclose(f0, 1.0e-6, rel_tol=1e-10)\nassert math.isclose(f1, 1.0e-6, rel_tol=1e-2)\n```\n\n## Exercise 03.3\n\nConsider the expression\n\n$$\nf = \\frac{1}{\\sqrt{x^2 - 1} - x}\n$$\n\nWhen $x$ is very large, the denominator approaches zero, which can cause problems.\n\nTry rephrasing the problem and eliminating the fraction by multiplying the numerator and denominator by $\\sqrt{x^2 - 1} + x$ and evaluate the two versions of the expression when:\n\n(a) $x = 1 \\times 10^{7}$\n\n(b) $x = 1 \\times 10^{9}$ (You may get a Python error for this case. Why?)\n\n#### (a) $x = 1 \\times 10^{7}$\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n\n#### (b) $x = 1 \\times 10^{9}$\n\n\n```python\n# YOUR CODE HERE\nraise NotImplementedError()\n```\n", "meta": {"hexsha": "5d6e8640e4c12cc895cca1590f8a4f4800307885", "size": 7544, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Assignment/03 Exercises.ipynb", "max_stars_repo_name": "reddyprasade/PYTHON-BASIC-FOR-ALL", "max_stars_repo_head_hexsha": "4fa4bf850f065e9ac1cea0365b93257e1f04e2cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2019-06-28T05:11:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:02:28.000Z", "max_issues_repo_path": "Assignment/03 Exercises.ipynb", "max_issues_repo_name": "chandhukogila/Python-Basic-For-All-3.x", "max_issues_repo_head_hexsha": "f4105833759a271fa0777f3d6fb96db32bbfaaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-12-28T14:15:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-28T14:16:02.000Z", "max_forks_repo_path": "Assignment/03 Exercises.ipynb", "max_forks_repo_name": "chandhukogila/Python-Basic-For-All-3.x", "max_forks_repo_head_hexsha": "f4105833759a271fa0777f3d6fb96db32bbfaaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-07-07T03:20:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T10:44:18.000Z", "avg_line_length": 22.7228915663, "max_line_length": 188, "alphanum_fraction": 0.519883351, "converted": true, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551515780318, "lm_q2_score": 0.9546474150908866, "lm_q1q2_score": 0.9210964763910936}}
{"text": "## Introduction to Sympy\n\nWhat if you would like to perform some calculus alongside your other computations? For that, you would need a computer algebra system (CAS). Luckily, the sympy package can provide you with the tools to perform symbolic computations and then can help you numerically evaluate those results.\n\nLet's get started...\n\n\n```python\n# Import sympy tools\nimport sympy as sp\nsp.init_printing(use_latex=True)\n\n# Other tools\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\nNote that I imported sympy, but then also initialized the sympy printing facilities to utilize $\\LaTeX$. The reason for this will be obvious soon, if you haven't already figured it out.\n\nRather than have x be a vector, I need it to be a symbol. In particular, I need it to be a symbol that one would like to manipulate similar to how one uses symbols in mathematical expressions. Unlike variables which point to specific data structures, a symbol is more like how a variable is used in mathematics, and can take on values at a later time.\n\n\n```python\n# Make x a symbol\nx = sp.symbols('x')\n```\n\n\n```python\n# Let's write an expression\ny = sp.cos(x)\n```\n\n\n```python\n# Just provide the expression by itself,\n# and it will be printed with LaTeX!\ny\n```\n\nSo, you can define mathematical expressions in sympy, and they will be rendered using $\\LaTeX$. Don't be confused by the naming conventions though. In this particular case, x is a standard python variable: it just so happens to reference the sympy _symbol_ 'x'. We are naming the python variable the same as the intended mathematical symbol just for parsimony. Similarly, y is a standard python variable, but it now references a sympy expression (which itself is composed of a sympy function defined in terms of the symbol x):\n\n\n```python\ntype(x)\n```\n\n\n\n\n sympy.core.symbol.Symbol\n\n\n\n\n```python\ntype(y)\n```\n\n\n\n\n cos\n\n\n\n\n```python\ntype(type(y))\n```\n\n\n\n\n sympy.core.function.FunctionClass\n\n\n\n\n```python\ny.free_symbols\n```\n\nAdditionally, we can perform symbolic math on that expression. For example, let's take the derivative with respect to x using the `diff()` function.\n\n\n```python\ndydx = y.diff(x)\n```\n\n\n```python\ndydx\n```\n\nNow we have the derivative of the function with respect to x, and have solved it __analytically__ (rather than numerically) using sympy! The `diff()` function is a member function of the function class, but you can also use the general `diff()` function if desired:\n\n\n```python\nsp.diff(y,x)\n```\n\nSympy has it's own builtin function which utilize matplotlib underneath for plotting expressions as well...\n\n\n```python\nsp.plot(dydx)\n```\n\nHowever, we may want more control over the x values sampled and plot itself. This can sometimes be better done by evaluating the function _numerically_ at the intended points. Let's do that now...\n\n\n```python\nx_vals = np.linspace(-2*np.pi,2*np.pi,101)\ny_vals = np.array([dydx.evalf(subs=dict(x=x_val)) for x_val in x_vals])\nprint('The length of x is %d'%(len(x_vals)))\nprint('The length of y is %d'%(len(y_vals)))\n```\n\n The length of x is 101\n The length of y is 101\n\n\nHere we have used a python list comprehension to evaluate our derivative (dydx) at each of the 101 points in the $-2\\pi$ to $2\\pi$ range created by `linspace()`. The `evalf()` function allows us plug in specific numberic values for our symbols. In particular, we pass the subs= argument a python dictionary object which contains a mapping from a symbol to a particular value we would like to associate with that symbol. Multiple symbols can be passed into the function using the dictionary object, so that functions with more than one symbol can be evaluated numerically as well. We can now plot those specific values and maintain full control over the appearance of the plot itself since we are using matplotlib/pyplot directly:\n\n\n```python\nplt.plot(x_vals,y_vals)\nplt.title(r'$y=%s$'%(sp.latex(dydx)))\nplt.xlabel('x')\nplt.ylabel('y')\nplt.show()\n```\n\nYou can also now see in the code above how the `sympy.latex()` function can be used to convert the expression we were storing in dydx into a string form recognized by $\\LaTeX$ math mode, and therefore also the `pyplot.title()` function from matplotlib. It's usually much easier to control how you want your plots to look using numerical evaluation instead of using sympy's built-in plotting tools, so keep that in mind in the future.\n", "meta": {"hexsha": "68daca47137c489dfa40ac58e5fe1135e0347f18", "size": 65852, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Introductions/Sympy Intro.ipynb", "max_stars_repo_name": "CSCI4850/notebook-examples", "max_stars_repo_head_hexsha": "8846792d8acc6b619c22f5d8bc7a4b3a446a8296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-03-28T18:06:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T19:50:49.000Z", "max_issues_repo_path": "Introductions/Sympy Intro.ipynb", "max_issues_repo_name": "CSCI4850/notebook-examples", "max_issues_repo_head_hexsha": "8846792d8acc6b619c22f5d8bc7a4b3a446a8296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introductions/Sympy Intro.ipynb", "max_forks_repo_name": "CSCI4850/notebook-examples", "max_forks_repo_head_hexsha": "8846792d8acc6b619c22f5d8bc7a4b3a446a8296", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-06T02:15:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-23T15:01:19.000Z", "avg_line_length": 175.1382978723, "max_line_length": 30564, "alphanum_fraction": 0.9104203365, "converted": true, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9693242009478238, "lm_q2_score": 0.9481545298708258, "lm_q1q2_score": 0.9190691320420977}}
{"text": "# Task for lecture 19\n\n## 1. Find the extrema in the function $f(x)=x^3-7.5x^2+18x-10$ analytically and determine if they are minimum or maximum. \n\n\n```python\n# import Python libraries\nimport numpy as np\n%matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport sympy as sym\nfrom sympy.plotting import plot\nfrom sympy.interactive import printing\nprinting.init_printing()\nimport pandas as pd\nfrom IPython.display import display\nfrom IPython.core.display import Math\n```\n\n\n```python\na, b = sym.symbols('a b')\nV = b*(a - 2*b)*(a - 2*b)\nVdiff = sym.expand(sym.diff(V, b))\nroots = sym.solve(Vdiff, b)\ndisplay(Math(sym.latex('Roots:') + sym.latex(roots)))\n```\n\nFor a function of one variable, if the maximum or minimum of a function is not at the limits of the domain and if at least the first and second derivatives of the function exist, a maximum and minimum can be found as the point where the first derivative of the function is zero.\n\n\n```python\n# Question 1\nx = sym.symbols('x')\ny = x**3 -7.5*x**2 + 18*x -10\ndy = sym.diff(y, x)\ndy\n```\n\n\n```python\nroots = sym.solve(dy, x)\ndisplay(Math(sym.latex('Roots:') + sym.latex(roots)))\n```\n\n\n$$Roots:\\left [ 2.0, \\quad 3.0\\right ]$$\n\n\nIf the second derivative on that point is positive, then it's a minimum, if it is negative, it's a maximum.\nSo, let's perform the second derivative.\n\n\n```python\ndy2 = sym.diff(dy, x)\ndy2\n```\n\n\n```python\nroots2 = sym.solve(dy2, x)\ndisplay(Math(sym.latex('Roots:') + sym.latex(roots2)))\n```\n\n\n$$Roots:\\left [ 2.5\\right ]$$\n\n\n## 2. Find the minimum in the $f(x)=x^3-7.5x^2+18x-10$ using the gradient descent algorithm. \n\n\n```python\n# From https://en.wikipedia.org/wiki/Gradient_descent\n\ncur_x = 6 # The algorithm starts at x=6\ngamma = 0.01 # step size multiplier\nprecision = 0.00001\nstep_size = 1 # initial step size\nmax_iters = 10000 # maximum number of iterations\niters = 0 # iteration counter\n\nf = lambda x: x**3 - 7.5*x**2 + 18*x - 10 # lambda function for f(x)\ndf = lambda x: 3*x**2 - 15*x + 18 # lambda function for the gradient of f(x)\n\nwhile (step_size > precision) & (iters < max_iters):\n prev_x = cur_x\n cur_x -= gamma*df(prev_x)\n step_size = abs(cur_x - prev_x)\n iters+=1\n\nprint('True local minimum at {} with function value {}.'.format(3, f(3)))\nprint('Local minimum by gradient descent at {} with function value {}.'.format(cur_x, f(cur_x)))\n```\n\n True local minimum at 3 with function value 3.5.\n Local minimum by gradient descent at 3.000323195755751 with function value 3.5000001567170003.\n\n", "meta": {"hexsha": "dc003b40bd14f9b992a5654f6559b04288794a69", "size": 9513, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "courses/modsim2018/reginaldo/Task for lecture 19.ipynb", "max_stars_repo_name": "regifukuchi/bmc-1", "max_stars_repo_head_hexsha": "f4418212664758511bb3f4d4ca2318ac48a55e88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "courses/modsim2018/reginaldo/Task for lecture 19.ipynb", "max_issues_repo_name": "regifukuchi/bmc-1", "max_issues_repo_head_hexsha": "f4418212664758511bb3f4d4ca2318ac48a55e88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "courses/modsim2018/reginaldo/Task for lecture 19.ipynb", "max_forks_repo_name": "regifukuchi/bmc-1", "max_forks_repo_head_hexsha": "f4418212664758511bb3f4d4ca2318ac48a55e88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9742647059, "max_line_length": 1828, "alphanum_fraction": 0.6590980763, "converted": true, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9724147201714923, "lm_q2_score": 0.9441768576872941, "lm_q1q2_score": 0.918131474860389}}
{"text": "<a href=\"https://colab.research.google.com/github/Codingtheedge/testtest/blob/main/Numerical_Optimization_Assignment1.ipynb\" target=\"_parent\"></a>\n\n\n```python\nimport numpy as np\nfrom numpy import linalg as la\n```\n\n**1. Function Plot**\n\nwith function *meshgrid*, *contour* and *contourf*\n\n$\nf(x) = 10 (x_2 - x_1^2)^2 + (1-x_1)^2\n$\n\n\n```python\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n#f(x) = 10 (x2 - x1**2)**2 + (1-x1)**2\ndef rosen(x):\n f = 10 * (x[1] - x[0]**2)**2 + (1-x[0])**2\n return f\n\nnx, ny = (240, 200)\nxv = np.linspace(-1.2, 1.2, nx)\nxh = np.linspace(-0.5,1.5, ny)\nx0, x1 = np.meshgrid(xv, xh, sparse= True)\n\nF = np.zeros((x1.shape[0],x0.shape[1])) # shape (200,240)\n\nfor i in range(F.shape[0]):\n for j in range(F.shape[1]):\n x = [x0[0,j], x1[i,0]]\n F[i, j] = rosen(x)\n\nplt.figure('Contours')\nplt.contour(x0[0,:], x1[:,0], F, 50)\nplt.axis('scaled')\nplt.colorbar()\nplt.show()\n\nplt.figure('Contours')\nplt.contourf(x0[0,:], x1[:,0], F, 50)\nplt.axis('scaled')\nplt.colorbar()\nplt.show()\n```\n\n**2. Gradient Computation**\n\nwith fucntion *symbols* and *diff*\n\n$\n∇f=\\begin{bmatrix}\n -40x_1(x_2-x_1^2)+2x_1-2 \\\\ \n 20*(x_2-x_1^2) \n \\end{bmatrix} \n$\n\n\n```python\nfrom sympy import symbols, diff\nx_1, x_2 = symbols('x_1 x_2', real= True)\ng0 = diff((10 * (x_2 - x_1**2)**2 + (1-x_1)**2),x_1)\ng1 = diff((10 * (x_2 - x_1**2)**2 + (1-x_1)**2),x_2)\n\ndef rosen_grad(x):\n g = np.zeros(2) \n g[0] = g0.subs({x_1:x[0], x_2:x[1]})\n g[1] = g1.subs({x_1:x[0], x_2:x[1]})\n return g\n```\n\n**3. Backtracking Line Search**\n\n\n```python\ndef backtrack_linesearch(f, gk, pk, xk, alpha = 0.1, beta = 0.8): # Algorithm parameters alpha and beta\n t = 1\n while(f(xk + t*pk) > f(xk) + alpha * t * gk @ pk):\n t *= beta # reduce t incrementally\n return t\n\ndef steepest_descent_bt(f, grad, x0):\n tol = 1e-5 # converge to a gradient norm of 1e-5 \n x = x0\n history = np.array( [x0] )\n while ( la.norm(grad(x)) > tol ):\n p = -grad(x)\n t = backtrack_linesearch(f, grad(x), p, x)\n x += t * p\n history = np.vstack( (history, x) )# The returned array formed by stacking the given arrays, will be at least 2-D.\n return x, history\n\n# plot convergence behaviour\nx_startpoint = np.array([-1.2, 1.0]) # start point\n\nxstar, hist = steepest_descent_bt(rosen, rosen_grad, x_startpoint)\nnsteps = hist.shape[0]\n\nprint('Optimal solution:',xstar)\nprint('The minima is ',rosen(xstar))\nprint('Iteration count:', nsteps)\n```\n\n Optimal solution: [1.00000578 1.00001197]\n The minima is 3.514046547976252e-11\n Iteration count: 1311\n\n\n**4. Convergence Behavior**\n\n\n```python\nfhist = np.zeros(nsteps)\nfor i in range(nsteps):\n fhist[i] = rosen(hist[i,:])\n\nplt.figure('Convergence behaviour')\nplt.semilogy(np.arange(0, nsteps), np.absolute(fhist))\nplt.grid(True, which =\"both\") \nplt.title('Convergence of Steepest Descent') \n#plt.text(0,10e-10,'Y axis in Semilogy') #text annotation\nplt.xlabel('Iteration count')\nplt.ylabel(r'$|f^k - f^*|$') \nplt.show()\n\nplt.figure('Contours Behavior')\nplt.title('Contours Behavior')\nplt.contour(x0[0,:], x1[:,0], F, 150)\nplt.axis('scaled')\nplt.plot(hist[:,0],hist[:,1],'r-')\nplt.colorbar()\nplt.show()\n```\n\nOn a semilog plot, $|f^k-f^*|$ vs *k* looks like a straight piecewise line segment.From the figure *Contours Behaviour*, the rate of convergence is very fast, but the search path is different with the samples given by slides.\n", "meta": {"hexsha": "52bb1f10c8e629b0e50cea6253263a9f9ee861f9", "size": 394680, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Numerical_Optimization_Assignment1.ipynb", "max_stars_repo_name": "Codingtheedge/testtest", "max_stars_repo_head_hexsha": "e735a29d1e29170dde475194cdc025edebda70f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Numerical_Optimization_Assignment1.ipynb", "max_issues_repo_name": "Codingtheedge/testtest", "max_issues_repo_head_hexsha": "e735a29d1e29170dde475194cdc025edebda70f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Numerical_Optimization_Assignment1.ipynb", "max_forks_repo_name": "Codingtheedge/testtest", "max_forks_repo_head_hexsha": "e735a29d1e29170dde475194cdc025edebda70f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 1294.0327868852, "max_line_length": 198094, "alphanum_fraction": 0.9553080977, "converted": true, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9643214491222695, "lm_q2_score": 0.9518632316144274, "lm_q1q2_score": 0.9179021308766311}}
{"text": "Suggestions for lab exercises.\n\n# Variables and assignment\n\n## Exercise 1\n\nRemember that $n! = n \\times (n - 1) \\times \\dots \\times 2 \\times 1$. Compute $15!$, assigning the result to a sensible variable name.\n\n## Exercise 2\n\nUsing the `math` module, check your result for $15$ factorial. You should explore the help for the `math` library and its functions, using eg tab-completion, the spyder inspector, or online sources.\n\n## Exercise 3\n\n[Stirling's approximation](http://mathworld.wolfram.com/StirlingsApproximation.html) gives that, for large enough $n$, \n\n\\begin{equation}\n n! \\simeq \\sqrt{2 \\pi} n^{n + 1/2} e^{-n}.\n\\end{equation}\n\nUsing functions and constants from the `math` library, compare the results of $n!$ and Stirling's approximation for $n = 5, 10, 15, 20$. In what sense does the approximation improve?\n\n# Basic functions\n\n## Exercise 1\n\nWrite a function to calculate the volume of a cuboid with edge lengths $a, b, c$. Test your code on sample values such as\n\n1. $a=1, b=1, c=1$ (result should be $1$);\n2. $a=1, b=2, c=3.5$ (result should be $7.0$);\n3. $a=0, b=1, c=1$ (result should be $0$);\n4. $a=2, b=-1, c=1$ (what do you think the result should be?).\n\n## Exercise 2\n\nWrite a function to compute the time (in seconds) taken for an object to fall from a height $H$ (in metres) to the ground, using the formula\n\\begin{equation}\n h(t) = \\frac{1}{2} g t^2.\n\\end{equation}\nUse the value of the acceleration due to gravity $g$ from `scipy.constants.g`. Test your code on sample values such as\n\n1. $H = 1$m (result should be $\\approx 0.452$s);\n2. $H = 10$m (result should be $\\approx 1.428$s);\n3. $H = 0$m (result should be $0$s);\n4. $H = -1$m (what do you think the result should be?).\n\n## Exercise 3\n\nWrite a function that computes the area of a triangle with edge lengths $a, b, c$. You may use the formula\n\\begin{equation}\n A = \\sqrt{s (s - a) (s - b) (s - c)}, \\qquad s = \\frac{a + b + c}{2}.\n\\end{equation}\n\nConstruct your own test cases to cover a range of possibilities.\n\n# Floating point numbers\n\n## Exercise 1\n\nComputers cannot, in principle, represent real numbers perfectly. This can lead to problems of accuracy. For example, if\n\\begin{equation}\n x = 1, \\qquad y = 1 + 10^{-14} \\sqrt{3}\n\\end{equation}\nthen it *should* be true that\n\\begin{equation}\n 10^{14} (y - x) = \\sqrt{3}.\n\\end{equation}\nCheck how accurately this equation holds in Python and see what this implies about the accuracy of subtracting two numbers that are close together.\n\n## Exercise 2\n\nThe standard quadratic formula gives the solutions to\n\n\\begin{equation}\n a x^2 + b x + c = 0\n\\end{equation}\n\nas\n\n\\begin{equation}\n x = \\frac{-b \\pm \\sqrt{b^2 - 4 a c}}{2 a}.\n\\end{equation}\n\nShow that, if $a = 10^{-n} = c$ and $b = 10^n$ then\n\n\\begin{equation}\n x = \\frac{10^{2 n}}{2} \\left( -1 \\pm \\sqrt{1 - 10^{-4n}} \\right).\n\\end{equation}\n\nUsing the expansion (from Taylor's theorem)\n\n\\begin{equation}\n \\sqrt{1 - 10^{-4 n}} \\simeq 1 - \\frac{10^{-4 n}}{2} + \\dots, \\qquad n \\gg 1,\n\\end{equation}\n\nshow that\n\n\\begin{equation}\n x \\simeq -10^{2 n} + \\frac{10^{-2 n}}{4} \\quad \\text{and} \\quad -\\frac{10^{-2n}}{4}, \\qquad n \\gg 1.\n\\end{equation}\n\n## Exercise 3\n\nBy multiplying and dividing by $-b \\mp \\sqrt{b^2 - 4 a c}$, check that we can also write the solutions to the quadratic equation as\n\n\\begin{equation}\n x = \\frac{2 c}{-b \\mp \\sqrt{b^2 - 4 a c}}.\n\\end{equation}\n\n## Exercise 4\n\nUsing Python, calculate both solutions to the quadratic equation\n\n\\begin{equation}\n 10^{-n} x^2 + 10^n x + 10^{-n} = 0\n\\end{equation}\n\nfor $n = 3$ and $n = 4$ using both formulas. What do you see? How has floating point accuracy caused problems here?\n\n## Exercise 5\n\nThe standard definition of the derivative of a function is\n\n\\begin{equation}\n \\left. \\frac{\\text{d} f}{\\text{d} x} \\right|_{x=X} = \\lim_{\\delta \\to 0} \\frac{f(X + \\delta) - f(X)}{\\delta}.\n\\end{equation}\n\nWe can *approximate* this by computing the result for a *finite* value of $\\delta$:\n\n\\begin{equation}\n g(x, \\delta) = \\frac{f(x + \\delta) - f(x)}{\\delta}.\n\\end{equation}\n\nWrite a function that takes as inputs a function of one variable, $f(x)$, a location $X$, and a step length $\\delta$, and returns the approximation to the derivative given by $g$.\n\n## Exercise 6\n\nThe function $f_1(x) = e^x$ has derivative with the exact value $1$ at $x=0$. Compute the approximate derivative using your function above, for $\\delta = 10^{-2 n}$ with $n = 1, \\dots, 7$. You should see the results initially improve, then get worse. Why is this?\n\n# Prime numbers\n\n## Exercise 1\n\nWrite a function that tests if a number is prime. Test it by writing out all prime numbers less than 50.\n\n## Exercise 2\n\n500 years ago some believed that the number $2^n - 1$ was prime for *all* primes $n$. Use your function to find the first prime $n$ for which this is not true.\n\n## Exercise 3\n\nThe *Mersenne* primes are those that have the form $2^n-1$, where $n$ is prime. Use your previous solutions to generate all the $n < 40$ that give Mersenne primes.\n\n## Exercise 4\n\nWrite a function to compute all prime factors of an integer $n$, including their multiplicities. Test it by printing the prime factors (without multiplicities) of $n = 17, \\dots, 20$ and the multiplicities (without factors) of $n = 48$.\n\n##### Note \n\nOne effective solution is to return a *dictionary*, where the keys are the factors and the values are the multiplicities.\n\n## Exercise 5\n\nWrite a function to generate all the integer divisors, including 1, but not including $n$ itself, of an integer $n$. Test it on $n = 16, \\dots, 20$.\n\n##### Note\n\nYou could use the prime factorization from the previous exercise, or you could do it directly.\n\n## Exercise 6\n\nA *perfect* number $n$ is one where the divisors sum to $n$. For example, 6 has divisors 1, 2, and 3, which sum to 6. Use your previous solution to find all perfect numbers $n < 10,000$ (there are only four!).\n\n## Exercise 7\n\nUsing your previous functions, check that all perfect numbers $n < 10,000$ can be written as $2^{k-1} \\times (2^k - 1)$, where $2^k-1$ is a Mersenne prime.\n\n## Exercise 8 (bonus)\n\nInvestigate the `timeit` function in python or IPython. Use this to measure how long your function takes to check that, if $k$ on the Mersenne list then $n = 2^{k-1} \\times (2^k - 1)$ is a perfect number, using your functions. Stop increasing $k$ when the time takes too long!\n\n##### Note\n\nYou could waste considerable time on this, and on optimizing the functions above to work efficiently. It is *not* worth it, other than to show how rapidly the computation time can grow!\n\n# Logistic map\n\nPartly taken from Newman's book, p 120.\n\nThe logistic map builds a sequence of numbers $\\{ x_n \\}$ using the relation\n\n\\begin{equation}\n x_{n+1} = r x_n \\left( 1 - x_n \\right),\n\\end{equation}\n\nwhere $0 \\le x_0 \\le 1$.\n\n## Exercise 1\n\nWrite a program that calculates the first $N$ members of the sequence, given as input $x_0$ and $r$ (and, of course, $N$).\n\n## Exercise 2\n\nFix $x_0=0.5$. Calculate the first 2,000 members of the sequence for $r=1.5$ and $r=3.5$ Plot the last 100 members of the sequence in both cases.\n\nWhat does this suggest about the long-term behaviour of the sequence?\n\n## Exercise 3\n\nFix $x_0 = 0.5$. For each value of $r$ between $1$ and $4$, in steps of $0.01$, calculate the first 2,000 members of the sequence. Plot the last 1,000 members of the sequence on a plot where the $x$-axis is the value of $r$ and the $y$-axis is the values in the sequence. Do not plot lines - just plot markers (e.g., use the `'k.'` plotting style).\n\n## Exercise 4\n\nFor iterative maps such as the logistic map, one of three things can occur:\n\n1. The sequence settles down to a *fixed point*.\n2. The sequence rotates through a finite number of values. This is called a *limit cycle*.\n3. The sequence generates an infinite number of values. This is called *deterministic chaos*.\n\nUsing just your plot, or new plots from this data, work out approximate values of $r$ for which there is a transition from fixed points to limit cycles, from limit cycles of a given number of values to more values, and the transition to chaos.\n\n# Mandelbrot\n\nThe Mandelbrot set is also generated from a sequence, $\\{ z_n \\}$, using the relation\n\n\\begin{equation}\n z_{n+1} = z_n^2 + c, \\qquad z_0 = 0.\n\\end{equation}\n\nThe members of the sequence, and the constant $c$, are all complex. The point in the complex plane at $c$ is in the Mandelbrot set only if the $\\|z_n\\| < 2$ for all members of the sequence. In reality, checking the first 100 iterations is sufficient.\n\nNote: the python notation for a complex number $x + \\text{i} y$ is `x + yj`: that is, `j` is used to indicate $\\sqrt{-1}$. If you know the values of `x` and `y` then `x + yj` constructs a complex number; if they are stored in variables you can use `complex(x, y)`.\n\n## Exercise 1\n\nWrite a function that checks if the point $c$ is in the Mandelbrot set.\n\n## Exercise 2\n\nCheck the points $c=0$ and $c=\\pm 2 \\pm 2 \\text{i}$ and ensure they do what you expect. (What *should* you expect?)\n\n## Exercise 3\n\nWrite a function that, given $N$\n\n1. generates an $N \\times N$ grid spanning $c = x + \\text{i} y$, for $-2 \\le x \\le 2$ and $-2 \\le y \\le 2$;\n2. returns an $N\\times N$ array containing one if the associated grid point is in the Mandelbrot set, and zero otherwise.\n\n## Exercise 4\n\nUsing the function `imshow` from `matplotlib`, plot the resulting array for a $100 \\times 100$ array to make sure you see the expected shape.\n\n## Exercise 5\n\nModify your functions so that, instead of returning whether a point is inside the set or not, it returns the logarithm of the number of iterations it takes. Plot the result using `imshow` again.\n\n## Exercise 6\n\nTry some higher resolution plots, and try plotting only a section to see the structure. **Note** this is not a good way to get high accuracy close up images!\n\n# Equivalence classes\n\nAn *equivalence class* is a relation that groups objects in a set into related subsets. For example, if we think of the integers modulo $7$, then $1$ is in the same equivalence class as $8$ (and $15$, and $22$, and so on), and $3$ is in the same equivalence class as $10$. We use the tilde $3 \\sim 10$ to denote two objects within the same equivalence class.\n\nHere, we are going to define the positive integers programmatically from equivalent sequences.\n\n## Exercise 1\n\nDefine a python class `Eqint`. This should be\n\n1. Initialized by a sequence;\n2. Store the sequence;\n3. Define its representation (via the `__repr__` function) to be the integer length of the sequence;\n4. Redefine equality (via the `__eq__` function) so that two `eqint`s are equal if their sequences have same length.\n\n## Exercise 2\n\nDefine a `zero` object from the empty list, and three `one` objects, from a single object list, tuple, and string. For example\n\n```python\none_list = Eqint([1])\none_tuple = Eqint((1,))\none_string = Eqint('1')\n```\n\nCheck that none of the `one` objects equal the zero object, but all equal the other `one` objects. Print each object to check that the representation gives the integer length.\n\n## Exercise 3\n\nRedefine the class by including an `__add__` method that combines the two sequences. That is, if `a` and `b` are `Eqint`s then `a+b` should return an `Eqint` defined from combining `a` and `b`s sequences.\n\n##### Note\n\nAdding two different *types* of sequences (eg, a list to a tuple) does not work, so it is better to either iterate over the sequences, or to convert to a uniform type before adding.\n\n## Exercise 4\n\nCheck your addition function by adding together all your previous `Eqint` objects (which will need re-defining, as the class has been redefined). Print the resulting object to check you get `3`, and also print its internal sequence.\n\n## Exercise 5\n\nWe will sketch a construction of the positive integers from *nothing*.\n\n1. Define an empty list `positive_integers`.\n2. Define an `Eqint` called `zero` from the empty list. Append it to `positive_integers`.\n3. Define an `Eqint` called `next_integer` from the `Eqint` defined by *a copy of* `positive_integers` (ie, use `Eqint(list(positive_integers))`. Append it to `positive_integers`.\n4. Repeat step 3 as often as needed.\n\nUse this procedure to define the `Eqint` equivalent to $10$. Print it, and its internal sequence, to check.\n\n# Rational numbers\n\nInstead of working with floating point numbers, which are not \"exact\", we could work with the rational numbers $\\mathbb{Q}$. A rational number $q \\in \\mathbb{Q}$ is defined by the *numerator* $n$ and *denominator* $d$ as $q = \\frac{n}{d}$, where $n$ and $d$ are *coprime* (ie, have no common divisor other than $1$).\n\n## Exercise 1\n\nFind a python function that finds the greatest common divisor (`gcd`) of two numbers. Use this to write a function `normal_form` that takes a numerator and divisor and returns the coprime $n$ and $d$. Test this function on $q = \\frac{3}{2}$, $q = \\frac{15}{3}$, and $q = \\frac{20}{42}$.\n\n## Exercise 2\n\nDefine a class `Rational` that uses the `normal_form` function to store the rational number in the appropriate form. Define a `__repr__` function that prints a string that *looks like* $\\frac{n}{d}$ (**hint**: use `len(str(number))` to find the number of digits of an integer). Test it on the cases above.\n\n## Exercise 3\n\nOverload the `__add__` function so that you can add two rational numbers. Test it on $\\frac{1}{2} + \\frac{1}{3} + \\frac{1}{6} = 1$.\n\n## Exercise 4\n\nOverload the `__mul__` function so that you can multiply two rational numbers. Test it on $\\frac{1}{3} \\times \\frac{15}{2} \\times \\frac{2}{5} = 1$.\n\n## Exercise 5\n\nOverload the [`__rmul__`](https://docs.python.org/2/reference/datamodel.html?highlight=rmul#object.__rmul__) function so that you can multiply a rational by an *integer*. Check that $\\frac{1}{2} \\times 2 = 1$ and $\\frac{1}{2} + (-1) \\times \\frac{1}{2} = 0$. Also overload the `__sub__` function (using previous functions!) so that you can subtract rational numbers and check that $\\frac{1}{2} - \\frac{1}{2} = 0$.\n\n## Exercise 6\n\nOverload the `__float__` function so that `float(q)` returns the floating point approximation to the rational number `q`. Test this on $\\frac{1}{2}, \\frac{1}{3}$, and $\\frac{1}{11}$.\n\n## Exercise 7\n\nOverload the `__lt__` function to compare two rational numbers. Create a list of rational numbers where the denominator is $n = 2, \\dots, 11$ and the numerator is the floored integer $n/2$, ie `n//2`. Use the `sorted` function on that list (which relies on the `__lt__` function).\n\n## Exercise 8\n\nThe [Wallis formula for $\\pi$](http://mathworld.wolfram.com/WallisFormula.html) is\n\n\\begin{equation}\n \\pi = 2 \\prod_{n=1}^{\\infty} \\frac{ (2 n)^2 }{(2 n - 1) (2 n + 1)}.\n\\end{equation}\n\nWe can define a partial product $\\pi_N$ as\n\n\\begin{equation}\n \\pi_N = 2 \\prod_{n=1}^{N} \\frac{ (2 n)^2 }{(2 n - 1) (2 n + 1)},\n\\end{equation}\n\neach of which are rational numbers.\n\nConstruct a list of the first 20 rational number approximations to $\\pi$ and print them out. Print the sorted list to show that the approximations are always increasing. Then convert them to floating point numbers, construct a `numpy` array, and subtract this array from $\\pi$ to see how accurate they are.\n\n# The shortest published Mathematical paper\n\nA [candidate for the shortest mathematical paper ever](http://www.ams.org/journals/bull/1966-72-06/S0002-9904-1966-11654-3/S0002-9904-1966-11654-3.pdf) shows the following result:\n\n\\begin{equation}\n 27^5 + 84^5 + 110^5 + 133^5 = 144^5.\n\\end{equation}\n\nThis is interesting as\n\n> This is a counterexample to a conjecture by Euler ... that at least $n$ $n$th powers are required to sum to an $n$th power, $n > 2$.\n\n## Exercise 1\n\nUsing python, check the equation above is true.\n\n## Exercise 2\n\nThe more interesting statement in the paper is that\n\n\\begin{equation}\n 27^5 + 84^5 + 110^5 + 133^5 = 144^5.\n\\end{equation}\n\n> [is] the smallest instance in which four fifth powers sum to a fifth power.\n\nInterpreting \"the smallest instance\" to mean the solution where the right hand side term (the largest integer) is the smallest, we want to use python to check this statement.\n\nYou may find the `combinations` function from the `itertools` package useful.\n\n\n```python\nimport numpy\nimport itertools\n```\n\nThe `combinations` function returns all the combinations (ignoring order) of `r` elements from a given list. For example, take a list of length 6, `[1, 2, 3, 4, 5, 6]` and compute all the combinations of length 4:\n\n\n```python\ninput_list = numpy.arange(1, 7)\ncombinations = list(itertools.combinations(input_list, 4))\nprint(combinations)\n```\n\n [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 3, 6), (1, 2, 4, 5), (1, 2, 4, 6), (1, 2, 5, 6), (1, 3, 4, 5), (1, 3, 4, 6), (1, 3, 5, 6), (1, 4, 5, 6), (2, 3, 4, 5), (2, 3, 4, 6), (2, 3, 5, 6), (2, 4, 5, 6), (3, 4, 5, 6)]\n\n\nWe can already see that the number of terms to consider is large.\n\nNote that we have used the `list` function to explicitly get a list of the combinations. The `combinations` function returns a *generator*, which can be used in a loop as if it were a list, without storing all elements of the list.\n\nHow fast does the number of combinations grow? The standard formula says that for a list of length $n$ there are\n\n\\begin{equation}\n \\begin{pmatrix} n \\\\ k \\end{pmatrix} = \\frac{n!}{k! (n-k)!}\n\\end{equation}\n\ncombinations of length $k$. For $k=4$ as needed here we will have $n (n-1) (n-2) (n-3) / 24$ combinations. For $n=144$ we therefore have\n\n\n```python\nn_combinations = 144*143*142*141/24\nprint(\"Number of combinations of 4 objects from 144 is {}\".format(n_combinations))\n```\n\n Number of combinations of 4 objects from 144 is 17178876\n\n\n### Exercise 2a\n\nShow, by getting python to compute the number of combinations $N = \\begin{pmatrix} n \\\\ 4 \\end{pmatrix}$ that $N$ grows roughly as $n^4$. To do this, plot the number of combinations and $n^4$ on a log-log scale. Restrict to $n \\le 50$.\n\nWith 17 million combinations to work with, we'll need to be a little careful how we compute.\n\nOne thing we could try is to loop through each possible \"smallest instance\" (the term on the right hand side) in increasing order. We then check all possible combinations of left hand sides.\n\nThis is computationally *very expensive* as we repeat a lot of calculations. We repeatedly recalculate combinations (a bad idea). We repeatedly recalculate the powers of the same number.\n\nInstead, let us try creating the list of all combinations of powers once.\n\n### Exercise 2b\n\n1. Construct a `numpy` array containing all integers in $1, \\dots, 144$ to the fifth power. \n2. Construct a list of all combinations of four elements from this array.\n3. Construct a list of sums of all these combinations.\n4. Loop over one list and check if the entry appears in the other list (ie, use the `in` keyword).\n\n# Lorenz attractor\n\nThe Lorenz system is a set of ordinary differential equations which can be written\n\n\\begin{equation}\n \\frac{\\text{d} \\vec{v}}{\\text{d} \\vec{t}} = \\vec{f}(\\vec{v})\n\\end{equation}\n\nwhere the variables in the state vector $\\vec{v}$ are\n\n\\begin{equation}\n \\vec{v} = \\begin{pmatrix} x(t) \\\\ y(t) \\\\ z(t) \\end{pmatrix}\n\\end{equation}\n\nand the function defining the ODE is\n\n\\begin{equation}\n \\vec{f} = \\begin{pmatrix} \\sigma \\left( y(t) - x(t) \\right) \\\\ x(t) \\left( \\rho - z(t) \\right) - y(t) \\\\ x(t) y(t) - \\beta z(t) \\end{pmatrix}.\n\\end{equation}\n\nThe parameters $\\sigma, \\rho, \\beta$ are all real numbers.\n\n## Exercise 1\n\nWrite a function `dvdt(v, t, params)` that returns $\\vec{f}$ given $\\vec{v}, t$ and the parameters $\\sigma, \\rho, \\beta$.\n\n## Exercise 2\n\nFix $\\sigma=10, \\beta=8/3$. Set initial data to be $\\vec{v}(0) = \\vec{1}$. Using `scipy`, specifically the `odeint` function of `scipy.integrate`, solve the Lorenz system up to $t=100$ for $\\rho=13, 14, 15$ and $28$.\n\nPlot your results in 3d, plotting $x, y, z$.\n\n## Exercise 3\n\nFix $\\rho = 28$. Solve the Lorenz system twice, up to $t=40$, using the two different initial conditions $\\vec{v}(0) = \\vec{1}$ and $\\vec{v}(0) = \\vec{1} + \\vec{10^{-5}}$.\n\nShow four plots. Each plot should show the two solutions on the same axes, plotting $x, y$ and $z$. Each plot should show $10$ units of time, ie the first shows $t \\in [0, 10]$, the second shows $t \\in [10, 20]$, and so on.\n\nThis shows the *sensitive dependence on initial conditions* that is characteristic of chaotic behaviour.\n", "meta": {"hexsha": "0ce21ae76cee1c292dfd163467c740b7d7c39659", "size": 30383, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/notebooks/Exercises.ipynb", "max_stars_repo_name": "IanHawke/maths-with-python-book", "max_stars_repo_head_hexsha": "552be64d07ff218988885f272194786b4cd30716", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-01-28T16:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-28T16:00:53.000Z", "max_issues_repo_path": "content/notebooks/Exercises.ipynb", "max_issues_repo_name": "IanHawke/maths-with-python-book", "max_issues_repo_head_hexsha": "552be64d07ff218988885f272194786b4cd30716", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-05-19T22:38:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T04:43:53.000Z", "max_forks_repo_path": "content/notebooks/Exercises.ipynb", "max_forks_repo_name": "IanHawke/maths-with-python-book", "max_forks_repo_head_hexsha": "552be64d07ff218988885f272194786b4cd30716", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4614537445, "max_line_length": 425, "alphanum_fraction": 0.5708455386, "converted": true, "num_tokens": 6099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067253, "lm_q2_score": 0.9688561701396605, "lm_q1q2_score": 0.9171160260167275}}
{"text": "# More Matrices\nThis notebook continues your exploration of matrices.\n\n## Matrix Multiplication\nMultiplying matrices is a little more complex than the operations we've seen so far. There are two cases to consider, *scalar multiplication* (multiplying a matrix by a single number), and *dot product matrix multiplication* (multiplying a matrix by another matrix.\n### Scalar Multiplication\nTo multiply a matrix by a scalar value, you just multiply each element by the scalar to produce a new matrix:\n\n\\begin{equation}2 \\times \\begin{bmatrix}1 & 2 & 3 \\\\4 & 5 & 6\\end{bmatrix} = \\begin{bmatrix}2 & 4 & 6 \\\\8 & 10 & 12\\end{bmatrix}\\end{equation}\n\nIn Python, you perform this calculation using the **\\*** operator:\n\n\n```python\nimport numpy as np\n\nA = np.array([[1,2,3],\n [4,5,6]])\nprint(2 * A)\n```\n\n### Dot Product Matrix Multiplication\nTo mulitply two matrices together, you need to calculate the *dot product* of rows and columns. This means multiplying each of the elements in each row of the first matrix by each of the elements in each column of the second matrix and adding the results. We perform this operation by applying the *RC* rule - always multiplying ***R***ows by ***C***olumns. For this to work, the number of ***columns*** in the first matrix must be the same as the number of ***rows*** in the second matrix so that the matrices are *conformable* for the dot product operation.\n\nSounds confusing, right?\n\nLet's look at an example:\n\n\\begin{equation}\\begin{bmatrix}1 & 2 & 3 \\\\4 & 5 & 6\\end{bmatrix} \\cdot \\begin{bmatrix}9 & 8 \\\\ 7 & 6 \\\\ 5 & 4\\end{bmatrix}\\end{equation}\n\nNote that the first matrix is 2x3, and the second matrix is 3x2. The important thing here is that the first matrix has two rows, and the second matrix has two columns. To perform the multiplication, we first take the dot product of the first ***row*** of the first matrix (1,2,3) and the first ***column*** of the second matrix (9,7,5):\n\n\\begin{equation}(1,2,3) \\cdot (9,7,5) = (1 \\times 9) + (2 \\times 7) + (3 \\times 5) = 38\\end{equation}\n\nIn our resulting matrix (which will always have the same number of ***rows*** as the first matrix, and the same number of ***columns*** as the second matrix), we can enter this into the first row and first column element:\n\n\\begin{equation}\\begin{bmatrix}38 & ?\\\\? & ?\\end{bmatrix} \\end{equation}\n\nNow we can take the dot product of the first row of the first matrix and the second column of the second matrix:\n\n\\begin{equation}(1,2,3) \\cdot (8,6,4) = (1 \\times 8) + (2 \\times 6) + (3 \\times 4) = 32\\end{equation}\n\nLet's add that to our resulting matrix in the first row and second column element:\n\n\\begin{equation}\\begin{bmatrix}38 & 32\\\\? & ?\\end{bmatrix} \\end{equation}\n\nNow we can repeat this process for the second row of the first matrix and the first column of the second matrix:\n\n\\begin{equation}(4,5,6) \\cdot (9,7,5) = (4 \\times 9) + (5 \\times 7) + (6 \\times 5) = 101\\end{equation}\n\nWhich fills in the next element in the result:\n\n\\begin{equation}\\begin{bmatrix}38 & 32\\\\101 & ?\\end{bmatrix} \\end{equation}\n\nFinally, we get the dot product for the second row of the first matrix and the second column of the second matrix:\n\n\\begin{equation}(4,5,6) \\cdot (8,6,4) = (4 \\times 8) + (5 \\times 6) + (6 \\times 4) = 86\\end{equation}\n\nGiving us:\n\n\\begin{equation}\\begin{bmatrix}38 & 32\\\\101 & 86\\end{bmatrix} \\end{equation}\n\nIn Python, you can use the *numpy.**dot*** function or the **@** operator to multiply matrices and two-dimensional arrays:\n\n\n```python\nimport numpy as np\n\nA = np.array([[1,2,3],\n [4,5,6]])\nB = np.array([[9,8],\n [7,6],\n [5,4]])\nprint(np.dot(A,B))\nprint(A @ B)\n```\n\nThis is one case where there is a difference in behavior between *numpy.**array*** and *numpy.**matrix***, You can also use a regular multiplication (**\\***) operator with a matrix, but not with an array:\n\n\n```python\nimport numpy as np\n\nA = np.matrix([[1,2,3]\n ,[4,5,6]])\nB = np.matrix([[9,8],\n [7,6],\n [5,4]])\nprint(A * B)\n```\n\nNote that, unlike with multiplication of regular scalar numbers, the order of the operands in a multiplication operation is significant. For scalar numbers, the *commmutative law* of multiplication applies, so for example:\n\n\\begin{equation}2 \\times 4 = 4 \\times 2\\end{equation}\n\nWith matrix multiplication, things are different, for example:\n\n\\begin{equation}\\begin{bmatrix}2 & 4 \\\\6 & 8\\end{bmatrix} \\cdot \\begin{bmatrix}1 & 3 \\\\ 5 & 7\\end{bmatrix} \\ne \\begin{bmatrix}1 & 3 \\\\ 5 & 7\\end{bmatrix} \\cdot \\begin{bmatrix}2 & 4 \\\\6 & 8\\end{bmatrix}\\end{equation}\n\nRun the following Python code to test this:\n\n\n```python\nimport numpy as np\n\nA = np.array([[2,4],\n [6,8]])\nB = np.array([[1,3],\n [5,7]])\nprint(A @ B)\nprint(B @ A)\n```\n\n## Identity Matrices\nAn *identity* matrix (usually indicated by a capital **I**) is the equivalent in matrix terms of the number **1**. It always has the same number of rows as columns, and it has the value **1** in the diagonal element positions I<sub>1,1</sub>, I<sub>2,2</sub>, etc; and 0 in all other element positions. Here's an example of a 3x3 identity matrix:\n\n\\begin{equation}\\begin{bmatrix}1 & 0 & 0\\\\0 & 1 & 0\\\\0 & 0 & 1\\end{bmatrix} \\end{equation}\n\nMultiplying any matrix by an identity matrix is the same as multiplying a number by 1; the result is the same as the original value:\n\n\\begin{equation}\\begin{bmatrix}1 & 2 & 3 \\\\4 & 5 & 6\\\\7 & 8 & 9\\end{bmatrix} \\cdot \\begin{bmatrix}1 & 0 & 0\\\\0 & 1 & 0\\\\0 & 0 & 1\\end{bmatrix} = \\begin{bmatrix}1 & 2 & 3 \\\\4 & 5 & 6\\\\7 & 8 & 9\\end{bmatrix} \\end{equation}\n\nIf you doubt me, try the following Python code!\n\n\n```python\nimport numpy as np\n\nA = np.array([[1,2,3],\n [4,5,6],\n [7,8,9]])\nB = np.array([[1,0,0],\n [0,1,0],\n [0,0,1]])\nprint(A @ B)\n```\n\n## Matrix Division\nYou can't actually divide by a matrix; but when you want to divide matrices, you can take advantage of the fact that division by a given number is the same as multiplication by the reciprocal of that number. For example:\n\n\\begin{equation}6 \\div 3 = \\frac{1}{3}\\times 6 \\end{equation}\n\nIn this case, <sup>1</sup>/<sub>3</sub> is the reciprocal of 3 (which as a fraction is <sup>3</sup>/<sub>1</sub> - we \"flip\" the numerator and denominator to get the reciprocal). You can also write <sup>1</sup>/<sub>3</sub> as 3<sup>-1</sup>.\n\n### Inverse of a Matrix\nFor matrix division, we use a related idea; we multiply by the *inverse* of a matrix:\n\n\\begin{equation}A \\div B = A \\cdot B^{-1}\\end{equation}\n\nThe inverse of B is B<sup>-1</sup> as long as the following equation is true:\n\n\\begin{equation}B \\cdot B^{-1} = B^{-1} \\cdot B = I\\end{equation}\n\n**I**, you may recall, is an *identity* matrix; the matrix equivalent of 1.\n\nSo how do you calculate the inverse of a matrix? For a 2x2 matrix, you can follow this formula:\n\n\\begin{equation}\\begin{bmatrix}a & b\\\\c & d\\end{bmatrix}^{-1} = \\frac{1}{ad-bc} \\begin{bmatrix}d & -b\\\\-c & a\\end{bmatrix}\\end{equation}\n\nWhat happened there?\n- We swapped the positions of *a* and *d*\n- We changed the signs of *b* and *c*\n- We multiplied the resulting matrix by 1 over the *determinant* of the matrix (*ad-bc*)\n\nLet's try with some actual numbers:\n\n\\begin{equation}\\begin{bmatrix}6 & 2\\\\1 & 2\\end{bmatrix}^{-1} = \\frac{1}{(6\\times2)-(2\\times1)} \\begin{bmatrix}2 & -2\\\\-1 & 6\\end{bmatrix}\\end{equation}\n\nSo:\n\n\\begin{equation}\\begin{bmatrix}6 & 2\\\\1 & 2\\end{bmatrix}^{-1} = \\frac{1}{10} \\begin{bmatrix}2 & -2\\\\-1 & 6\\end{bmatrix}\\end{equation}\n\nWhich gives us the result:\n\n\\begin{equation}\\begin{bmatrix}6 & 2\\\\1 & 2\\end{bmatrix}^{-1} = \\begin{bmatrix}0.2 & -0.2\\\\-0.1 & 0.6\\end{bmatrix}\\end{equation}\n\nTo check this, we can multiply the original matrix by its inverse to see if we get an identity matrix. This makes sense if you think about it; in the same way that 3 x <sup>1</sup>/<sub>3</sub> = 1, a matrix multiplied by its inverse results in an identity matrix:\n\n\\begin{equation}\\begin{bmatrix}6 & 2\\\\1 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}0.2 & -0.2\\\\-0.1 & 0.6\\end{bmatrix} = \\begin{bmatrix}(6\\times0.2)+(2\\times-0.1) & (6\\times-0.2)+(2\\times0.6)\\\\(1\\times0.2)+(2\\times-0.1) & (1\\times-0.2)+(2\\times0.6)\\end{bmatrix} = \\begin{bmatrix}1 & 0\\\\0 & 1\\end{bmatrix}\\end{equation}\n\nNote that not every matrix has an inverse - for example, if the determinant works out to be 0, the inverse matrix is not defined.\n\nIn Python, you can use the *numpy.linalg.**inv*** function to get the inverse of a matrix in an *array* or *matrix* object:\n\n\n```python\nimport numpy as np\n\nB = np.array([[6,2],\n [1,2]])\n\nprint(np.linalg.inv(B))\n```\n\nAdditionally, the *matrix* type has an ***I*** method that returns the inverse matrix:\n\n\n```python\nimport numpy as np\n\nB = np.matrix([[6,2],\n [1,2]])\n\nprint(B.I)\n```\n\nFor larger matrices, the process to calculate the inverse is more complex. Let's explore an example based on the following matrix:\n\n\\begin{equation}\\begin{bmatrix}4 & 2 & 2\\\\6 & 2 & 4\\\\2 & 2 & 8\\end{bmatrix} \\end{equation}\n\nThe process to find the inverse consists of the following steps:\n\n1: Create a matrix of *minors* by calculating the *determinant* for each element in the matrix based on the elements that are <u>not</u> in the same row or column; like this:\n\n\\begin{equation}\\begin{bmatrix}\\color{blue}4 & \\color{lightgray}2 & \\color{lightgray}2\\\\\\color{lightgray}6 & \\color{red}2 & \\color{red}4\\\\\\color{lightgray}2 & \\color{red}2 & \\color{red}8\\end{bmatrix}\\;\\;\\;\\;(2\\times8) - (4\\times2) = 8\\;\\;\\;\\;\\begin{bmatrix}8 & \\color{lightgray}? & \\color{lightgray}?\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\end{bmatrix} \\end{equation}\n\n\\begin{equation}\\begin{bmatrix}\\color{lightgray}4 & \\color{blue}2 & \\color{lightgray}2\\\\\\color{red}6 & \\color{lightgray}2 & \\color{red}4\\\\\\color{red}2 & \\color{lightgray}2 & \\color{red}8\\end{bmatrix}\\;\\;\\;\\;(6\\times8) - (4\\times2) = 40\\;\\;\\;\\;\\begin{bmatrix}8 & 40 & \\color{lightgray}?\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\end{bmatrix}\\end{equation}\n\n\\begin{equation}\\begin{bmatrix}\\color{lightgray}4 & \\color{lightgray}2 & \\color{blue}2\\\\\\color{red}6 & \\color{red}2 & \\color{lightgray}4\\\\\\color{red}2 & \\color{red}2 & \\color{lightgray}8\\end{bmatrix}\\;\\;\\;\\;(6\\times2) - (2\\times2) = 8\\;\\;\\;\\;\\begin{bmatrix}8 & 40 & 8\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\end{bmatrix} \\end{equation}\n\n\\begin{equation}\\begin{bmatrix}\\color{lightgray}4 & \\color{red}2 & \\color{red}2\\\\\\color{blue}6 & \\color{lightgray}2 & \\color{lightgray}4\\\\\\color{lightgray}2 & \\color{red}2 & \\color{red}8\\end{bmatrix}\\;\\;\\;\\;(2\\times8) - (2\\times2) = 12\\;\\;\\;\\;\\begin{bmatrix}8 & 40 & 8\\\\12 & \\color{lightgray}? & \\color{lightgray}?\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\end{bmatrix} \\end{equation}\n\n\\begin{equation}\\begin{bmatrix}\\color{red}4 & \\color{lightgray}2 & \\color{red}2\\\\\\color{lightgray}6 & \\color{blue}2 & \\color{lightgray}4\\\\\\color{red}2 & \\color{lightgray}2 & \\color{red}8\\end{bmatrix}\\;\\;\\;\\;(4\\times8) - (2\\times2) = 28\\;\\;\\;\\;\\begin{bmatrix}8 & 40 & 8\\\\12 & 28 & \\color{lightgray}?\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\end{bmatrix} \\end{equation}\n\n\\begin{equation}\\begin{bmatrix}\\color{red}4 & \\color{red}2 & \\color{lightgray}2\\\\\\color{lightgray}6 & \\color{lightgray}2 & \\color{blue}4\\\\\\color{red}2 & \\color{red}2 & \\color{lightgray}8\\end{bmatrix}\\;\\;\\;\\;(4\\times2) - (2\\times2) = 4\\;\\;\\;\\;\\begin{bmatrix}8 & 40 & 8\\\\12 & 28 & 4\\\\\\color{lightgray}? & \\color{lightgray}? & \\color{lightgray}?\\end{bmatrix} \\end{equation}\n\n\\begin{equation}\\begin{bmatrix}\\color{lightgray}4 & \\color{red}2 & \\color{red}2\\\\\\color{lightgray}6 & \\color{red}2 & \\color{red}4\\\\\\color{blue}2 & \\color{lightgray}2 & \\color{lightgray}8\\end{bmatrix}\\;\\;\\;\\;(2\\times4) - (2\\times2) = 4\\;\\;\\;\\;\\begin{bmatrix}8 & 40 & 8\\\\12 & 28 & 4\\\\4 & \\color{lightgray}? & \\color{lightgray}?\\end{bmatrix} \\end{equation}\n\n\\begin{equation}\\begin{bmatrix}\\color{red}4 & \\color{lightgray}2 & \\color{red}2\\\\\\color{red}6 & \\color{lightgray}2 & \\color{red}4\\\\\\color{lightgray}2 & \\color{blue}2 & \\color{lightgray}8\\end{bmatrix}\\;\\;\\;\\;(4\\times4) - (2\\times6) = 4\\;\\;\\;\\;\\begin{bmatrix}8 & 40 & 8\\\\12 & 28 & 4\\\\4 & 4 & \\color{lightgray}?\\end{bmatrix} \\end{equation}\n\n\\begin{equation}\\begin{bmatrix}\\color{red}4 & \\color{red}2 & \\color{lightgray}2\\\\\\color{red}6 & \\color{red}2 & \\color{lightgray}4\\\\\\color{lightgray}2 & \\color{lightgray}2 & \\color{blue}8\\end{bmatrix}\\;\\;\\;\\;(4\\times2) - (2\\times6) = -4\\;\\;\\;\\;\\begin{bmatrix}8 & 40 & 8\\\\12 & 28 & 4\\\\4 & 4 & -4\\end{bmatrix} \\end{equation}\n\n\n2: Apply *cofactors* to the matrix by switching the sign of every alternate element in the matrix of minors:\n\n\\begin{equation}\\begin{bmatrix}8 & -40 & 8\\\\-12 & 28 & -4\\\\4 & -4 & -4\\end{bmatrix} \\end{equation}\n\n3: *Adjugate* by transposing elements diagonally:\n\n\\begin{equation}\\begin{bmatrix}8 & \\color{green}-\\color{green}1\\color{green}2 & \\color{orange}4\\\\\\color{green}-\\color{green}4\\color{green}0 & 28 & \\color{purple}-\\color{purple}4\\\\\\color{orange}8 & \\color{purple}-\\color{purple}4 & -4\\end{bmatrix} \\end{equation}\n\n4: Multiply by 1/determinant of the original matrix. To find this, multiply each of the top row elements by their corresponding minor determinants (which we calculated earlier in the matrix of minors), and then subtract the second from the first and add the third:\n\n\\begin{equation}Determinant = (4 \\times 8) - (2 \\times 40) + (2 \\times 8) = -32\\end{equation}\n\n\n\\begin{equation}\\frac{1}{-32}\\begin{bmatrix}8 & -12 & 4\\\\-40 & 28 & -4\\\\8 & -4 & -4\\end{bmatrix} = \\begin{bmatrix}-0.25 & 0.375 & -0.125\\\\1.25 & -0.875 & 0.125\\\\-0.25 & 0.125 & 0.125\\end{bmatrix}\\end{equation}\n\nLet's verify that the original matrix multiplied by the inverse results in an identity matrix:\n\n\\begin{equation}\\begin{bmatrix}4 & 2 & 2\\\\6 & 2 & 4\\\\2 & 2 & 8\\end{bmatrix} \\cdot \\begin{bmatrix}-0.25 & 0.375 & -0.125\\\\1.25 & -0.875 & 0.125\\\\-0.25 & 0.125 & 0.125\\end{bmatrix}\\end{equation}\n\n\\begin{equation}= \\begin{bmatrix}(4\\times-0.25)+(2\\times1.25)+(2\\times-0.25) & (4\\times0.375)+(2\\times-0.875)+(2\\times0.125) & (4\\times-0.125)+(2\\times-0.125)+(2\\times0.125)\\\\(6\\times-0.25)+(2\\times1.25)+(4\\times-0.25) & (6\\times0.375)+(2\\times-0.875)+(4\\times0.125) & (6\\times-0.125)+(2\\times-0.125)+(4\\times0.125)\\\\(2\\times-0.25)+(2\\times1.25)+(8\\times-0.25) & (2\\times0.375)+(2\\times-0.875)+(8\\times0.125) & (2\\times-0.125)+(2\\times-0.125)+(8\\times0.125)\\end{bmatrix} \\end{equation}\n\n\\begin{equation}= \\begin{bmatrix}1 & 0 & 0\\\\0 & 1 & 0\\\\0 & 0 & 1\\end{bmatrix} \\end{equation}\n\nAs you can see, this can get pretty complicated - which is why we usually use a calculator or a computer program. You can run the following Python code to verify that the inverse matrix we calculated is correct:\n\n\n```python\nimport numpy as np\n\nB = np.array([[4,2,2],\n [6,2,4],\n [2,2,8]])\n\nprint(np.linalg.inv(B))\n```\n\n### Multiplying by an Inverse Matrix\nNow that you know how to calculate an inverse matrix, you can use that knowledge to multiply the inverse of a matrix by another matrix as an alternative to division:\n\n\\begin{equation}\\begin{bmatrix}1 & 2\\\\3 & 4\\end{bmatrix} \\cdot \\begin{bmatrix}6 & 2\\\\1 & 2\\end{bmatrix}^{-1} \\end{equation}\n\n\\begin{equation}=\\begin{bmatrix}1 & 2\\\\3 & 4\\end{bmatrix} \\cdot \\begin{bmatrix}0.2 & -0.2\\\\-0.1 & 0.6\\end{bmatrix} \\end{equation}\n\n\\begin{equation}=\\begin{bmatrix}(1\\times0.2)+(2\\times-0.1) & (1\\times-0.2)+(2\\times0.6)\\\\(3\\times0.2)+(4\\times-0.1) & (3\\times-0.2)+(4\\times0.6)\\end{bmatrix}\\end{equation}\n\n\\begin{equation}=\\begin{bmatrix}0 & 1\\\\0.2 & 1.8\\end{bmatrix}\\end{equation}\n\nHere's the Python code to calculate this:\n\n\n```python\nimport numpy as np\n\nA = np.array([[1,2],\n [3,4]])\n\nB = np.array([[6,2],\n [1,2]])\n\n\nC = A @ np.linalg.inv(B)\n\nprint(C)\n```\n\n## Solving Systems of Equations with Matrices\nOne of the great things about matrices, is that they can help us solve systems of equations. For example, consider the following system of equations:\n\n\\begin{equation}2x + 4y = 18\\end{equation}\n\\begin{equation}6x + 2y = 34\\end{equation}\n\nWe can write this in matrix form, like this:\n\n\\begin{equation}\\begin{bmatrix}2 & 4\\\\6 & 2\\end{bmatrix} \\cdot \\begin{bmatrix}x\\\\y\\end{bmatrix}=\\begin{bmatrix}18\\\\34\\end{bmatrix}\\end{equation}\n\nNote that the variables (***x*** and ***y***) are arranged as a column in one matrix, which is multiplied by a matrix containing the coefficients to produce as matrix containing the results. If you calculate the dot product on the left side, you can see clearly that this represents the original equations:\n\n\\begin{equation}\\begin{bmatrix}2x + 4y\\\\6x + 2y\\end{bmatrix} =\\begin{bmatrix}18\\\\34\\end{bmatrix}\\end{equation}\n\nNow. let's name our matrices so we can better understand what comes next:\n\n\\begin{equation}A=\\begin{bmatrix}2 & 4\\\\6 & 2\\end{bmatrix}\\;\\;\\;\\;X=\\begin{bmatrix}x\\\\y\\end{bmatrix}\\;\\;\\;\\;B=\\begin{bmatrix}18\\\\34\\end{bmatrix}\\end{equation}\n\nWe already know that ***A • X = B***, which arithmetically means that ***X = B ÷ A***. Since we can't actually divide by a matrix, we need to multiply by the inverse; so we can find the values for our variables (*X*) like this: ***X = A<sup>-1</sup> • B***\n\nSo, first we need the inverse of A:\n\n\\begin{equation}\\begin{bmatrix}2 & 4\\\\6 & 2\\end{bmatrix}^{-1} = \\frac{1}{(2\\times2)-(4\\times6)} \\begin{bmatrix}2 & -4\\\\-6 & 2\\end{bmatrix}\\end{equation}\n\n\\begin{equation}= \\frac{1}{-20} \\begin{bmatrix}2 & -4\\\\-6 & 2\\end{bmatrix}\\end{equation}\n\n\\begin{equation}=\\begin{bmatrix}-0.1 & 0.2\\\\0.3 & -0.1\\end{bmatrix}\\end{equation}\n\nThen we just multiply this with B:\n\n\\begin{equation}X = \\begin{bmatrix}-0.1 & 0.2\\\\0.3 & -0.1\\end{bmatrix} \\cdot \\begin{bmatrix}18\\\\34\\end{bmatrix}\\end{equation}\n\n\\begin{equation}X = \\begin{bmatrix}(-0.1 \\times 18)+(0.2 \\times 34)\\\\(0.3\\times18)+(-0.1\\times34)\\end{bmatrix}\\end{equation}\n\n\\begin{equation}X = \\begin{bmatrix}5\\\\2\\end{bmatrix}\\end{equation}\n\nThe resulting matrix (*X*) contains the values for our *x* and *y* variables, and we can check these by plugging them into the original equations:\n\n\\begin{equation}(2\\times5) + (4\\times2) = 18\\end{equation}\n\\begin{equation}(6\\times5) + (2\\times2) = 34\\end{equation}\n\nThese of course simplify to:\n\n\\begin{equation}10 + 8 = 18\\end{equation}\n\\begin{equation}30 + 4 = 34\\end{equation}\n\nSo our variable values are correct.\n\nHere's the Python code to do all of this:\n\n\n```python\nimport numpy as np\n\nA = np.array([[2,4],\n [6,2]])\n\nB = np.array([[18],\n [34]])\n\nC = np.linalg.inv(A) @ B\n\nprint(C)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "44cdd348ac3500ddbcb635f87ff5fbf2647b5ec9", "size": 24847, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Vector and Matrices by Hiren/03-04-More Matrices.ipynb", "max_stars_repo_name": "awesome-archive/Basic-Mathematics-for-Machine-Learning", "max_stars_repo_head_hexsha": "b6699a9c29ec070a0b1615c46952cb0deeb73b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 401, "max_stars_repo_stars_event_min_datetime": "2018-08-29T04:55:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:03:39.000Z", "max_issues_repo_path": "Vector and Matrices by Hiren/03-04-More Matrices.ipynb", "max_issues_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_issues_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-11-19T23:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-20T00:15:39.000Z", "max_forks_repo_path": "Vector and Matrices by Hiren/03-04-More Matrices.ipynb", "max_forks_repo_name": "aligeekk/Basic-Mathematics-for-Machine-Learning", "max_forks_repo_head_hexsha": "8662076d60e89f58a6e81e4ca1377569472760a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135, "max_forks_repo_forks_event_min_datetime": "2018-08-29T05:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:04:25.000Z", "avg_line_length": 49.694, "max_line_length": 568, "alphanum_fraction": 0.5636495352, "converted": true, "num_tokens": 6592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.971129093053712, "lm_q2_score": 0.944176855920157, "lm_q1q2_score": 0.9169176137720474}}
{"text": "### Agnostic smooth minimization\n\n**Purpose of this demo**: Motivate optimization in general (hyper-parameter selection, non-convexity)\n\n+ Disclaimer: I'm not expert in Python - I use Python/Matlab as tools to validate algorithms and theorems. \n+ Thus, my implementations are not the most efficient ones + there might be bugs\n\n**Problem definition:**. \n\n\\begin{align}\n f(x_1, x_2) = (x_1 + 2x_2 - 7)^2 + (2x_1 + x_2 - 5)^2\n\\end{align}\n\n\\begin{equation*}\n\\begin{aligned}\n& \\underset{x \\in \\mathbb{R}^2}{\\text{min}}\n& & f(x_1, x_2)\n\\end{aligned}\n\\end{equation*}\n\n+ Any properties you might extract by just looking at the function?\n\n+ Is it differentiable?\n\n\\begin{align}\n \\frac{\\partial f(x_1, x_2)}{\\partial x_1} = 2(x_1 + 2x_2 - 7) + 4(2x_1 + x_2 - 5)\n\\end{align}\n\n\\begin{align}\n \\frac{\\partial f(x_1, x_2)}{\\partial x_2} = 4(x_1 + 2x_2 - 7) + 2(2x_1 + x_2 - 5)\n\\end{align}\n\nand as a vector:\n\\begin{align}\n \\nabla f(x_1, x_2) = \\begin{bmatrix} 2(x_1 + 2x_2 - 7) + 4(2x_1 + x_2 - 5) \\\\ 4(x_1 + 2x_2 - 7) + 2(2x_1 + x_2 - 5) \\end{bmatrix}\n\\end{align}\n\n+ Is it negative-valued, positive-valued, or both?\n\n**3D plot** \n\n\n```python\n%matplotlib inline\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport random\n\nfrom matplotlib import rc\n#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\n## for Palatino and other serif fonts use:\nrc('font',**{'family':'serif','serif':['Palatino']})\nrc('text', usetex=True)\n\nfrom numpy import linalg as la\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# Make data.\nX = np.arange(-10, 10, 0.25)\nY = np.arange(-10, 10, 0.25)\nX, Y = np.meshgrid(X, Y)\nZ = (X + 2*Y - 7)**2 + (2*X + Y - 5)**2\n\nax.plot_wireframe(X, Y, Z, rstride=4, cstride=4)\nax.view_init(10, 90)\n```\n\n\n```python\n# Returns the value of the objecive function\ndef f(x):\n return (x[0] + 2*x[1] - 7)**2 + (2*x[0] + x[1] - 5)**2\n```\n\n\n```python\ndef GD_Booth(x_new, eta, iters, epsilon, verbose, x_star):\n p = 2\n \n x_list, f_list = [la.norm(x_new - x_star, 2)], [f(x_new)]\n\n for i in range(iters):\n x_old = x_new\n \n # Compute gradient\n grad = np.zeros(p)\n grad[0] = 2*(x_old[0] + 2*x_old[1] - 7) + 4*(2*x_old[0] + x_old[1] - 5)\n grad[1] = 4*(x_old[0] + 2*x_old[1] - 7) + 2*(2*x_old[0] + x_old[1] - 5)\n \n # Perform gradient step\n x_new = x_old - eta * grad \n \n if (la.norm(x_new - x_old, 2) / la.norm(x_new, 2)) < epsilon:\n break\n \n # Keep track of solutions and objective values\n x_list.append(la.norm(x_new - x_star, 2))\n f_list.append(f(x_new))\n \n if verbose:\n print(\"iter# = \"+ str(i) + \", ||x_new - x_star||_2 = \" + str(la.norm(x_new - x_star, 2)) + \", f(x_new) = \" + str(f(x_new)))\n \n print(\"Number of steps:\", len(f_list))\n return x_new, x_list, f_list\n```\n\n\n```python\n# Run algorithm\nepsilon = 1e-6 # Precision parameter\niters = 100\neta = 0.1\nx_init = np.random.randn(2) # Initial estimate\n# print(x_init)\n#x_init[0] = 1\n#x_init[1] = 1\nprint(x_init)\nx_star = [1, 3]\n \nx_GD, x_list, f_list = GD_Booth(x_init, eta, iters, epsilon, True, x_star)\n\n# Plot\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n\nxs = range(len(x_list))\nplt.plot(xs, x_list, '-o', color = '#3399FF', linewidth = 4, alpha = 0.7, markerfacecolor = 'b')\nplt.yscale('log')\nplt.xlabel('Iterations')\nplt.ylabel(r\"$\\|x^\\star - \\widehat{x}\\|_2$\")\n\n# Make room for the ridiculously large title.\nplt.subplots_adjust(top=0.8)\nplt.show()\n```\n\n**Problem definition: Weirder 2d non-convex problem**. \n\n\\begin{align}\n f(x_1, x_2) = \\sum_{i = 1}^2 \\tfrac{x_i^2}{4000} - \\prod_{i = 1}^2\\cos\\left( \\tfrac{x_i}{\\sqrt{i}} \\right) + 1\n\\end{align}\n\n\\begin{equation*}\n\\begin{aligned}\n& \\underset{x \\in \\mathbb{R}^2}{\\text{min}}\n& & f(x_1, x_2)\n\\end{aligned}\n\\end{equation*}\n\n+ Any properties you might extract by just looking at the function?\n\n+ Is it differentiable?\n\n\\begin{align}\n \\frac{\\partial f(x_1, x_2)}{\\partial x_1} = \\tfrac{x_1}{2000} + \\sin\\left(x_1\\right) \\cdot \\cos\\left(\\tfrac{x_2}{\\sqrt{2}}\\right)\n\\end{align}\n\n\\begin{align}\n \\frac{\\partial f(x_1, x_2)}{\\partial x_2} = \\tfrac{x_2}{2000} + \\cos\\left(x_1\\right) \\cdot \\frac{\\sin\\left(\\tfrac{x_2}{\\sqrt{2}}\\right)}{\\sqrt{2}}\n\\end{align}\n\nand as a vector:\n\\begin{align}\n \\nabla f(x_1, x_2) = \\begin{bmatrix} \\tfrac{x_1}{2000} + \\sin\\left(x_1\\right) \\cdot \\cos\\left(\\tfrac{x_2}{\\sqrt{2}}\\right) \\\\ \n \\tfrac{x_2}{2000} + \\cos\\left(x_1\\right) \\cdot \\frac{\\sin\\left(\\tfrac{x_2}{\\sqrt{2}}\\right)}{\\sqrt{2}} \\end{bmatrix}\n\\end{align}\n\n**3D plot** \n\n\n```python\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# Make data.\nX = np.arange(-5, 5, 0.25)\nY = np.arange(-5, 5, 0.25)\nX, Y = np.meshgrid(X, Y)\nZ = (X**2)/4000 + (Y**2)/4000 - np.cos(X)*np.cos(Y/np.sqrt(2)) + 1\n\nsurf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,\n linewidth=0, antialiased=False)\n```\n\n\n```python\n# Returns the value of the objecive function\ndef f(x):\n return (x[0]**2)/4000 + (x[1]**2)/4000 - np.cos(x[0])*np.cos(x[1]/np.sqrt(2)) + 1\n```\n\n\n```python\ndef GD_Griewank(x_new, eta, iters, epsilon, verbose, x_star):\n p = 2\n \n x_list, f_list = [la.norm(x_new - x_star, 2)], [f(x_new)]\n\n for i in range(iters):\n x_old = x_new\n \n # Compute gradient\n grad = np.zeros(p)\n grad[0] = x_old[0]/2000 + np.sin(x_old[0]) * np.cos(x_old[1]/np.sqrt(2))\n grad[1] = x_old[1]/2000 + np.cos(x_old[0]) * np.sin(x_old[1]/np.sqrt(2))/np.sqrt(2)\n \n # Perform gradient step\n x_new = x_old - eta * grad \n \n if (la.norm(x_new - x_old, 2) / la.norm(x_new, 2)) < epsilon:\n break\n \n # Keep track of solutions and objective values\n x_list.append(la.norm(x_new - x_star, 2))\n f_list.append(f(x_new))\n \n if verbose:\n print(\"iter# = \"+ str(i) + \", ||x_new - x_star||_2 = \" + str(la.norm(x_new - x_star, 2)) + \", f(x_new) = \" + str(f(x_new)))\n \n print(\"Number of steps:\", len(f_list))\n return x_new, x_list, f_list\n```\n\n\n```python\n# Run algorithm\nepsilon = 1e-6 # Precision parameter\niters = 1000\neta = 0.1\n# x_init = np.random.randn(2) # Initial estimate\n# print(x_init)\nx_init[0] = -3\nx_init[1] = 3\n# print(x_init)\nx_star = [0, 0]\n \nx_GD, x_list, f_list = GD_Griewank(x_init, eta, iters, epsilon, True, x_star)\n\n# Plot\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n\nxs = range(len(x_list))\nplt.plot(xs, x_list, '-o', color = '#3399FF', linewidth = 4, alpha = 0.7, markerfacecolor = 'b')\nplt.yscale('log')\nplt.xlabel('Iterations')\nplt.ylabel(r\"$\\|x^\\star - \\widehat{x}\\|_2$\")\n\n# Make room for the ridiculously large title.\nplt.subplots_adjust(top=0.8)\nplt.show()\n```\n\n### Non-convex Lipschitz continuous gradient function\n\n\\begin{align}\n f(x) = x^2 + 3\\sin^2(x)\n\\end{align}\n\nThen, its gradient and Hessian are calculated as:\n\\begin{align}\nf'(x) = 2x + 6\\sin(x) \\cdot \\cos(x), ~~f''(x) = 2 + 6\\cos^2(x) - 6\\sin^2(x)\n\\end{align}\n\n\n\n```python\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n# Make data.\nx = np.arange(-5, 5, 0.25)\nf = x**2 + 3*(np.sin(x))**2\n\nax.plot(x, f, color='green', marker='o', linestyle='dashed', linewidth=2, markersize=2)\n```\n\n\n```python\nfig = plt.figure()\nax = fig.add_subplot(111)\n\n# Make data.\nx = np.arange(-5, 5, 0.25)\nhessian_f = 2 + 6*(np.cos(x))**2 - 6*(np.sin(x))**2\n\nax.plot(x, hessian_f, color='green', marker='o', linestyle='dashed', linewidth=2, markersize=2)\n```\n\nWhich means that we can upper bound:\n\\begin{align}\n\\|\\nabla^2 f(x)\\|_2 \\leq 8 := L\n\\end{align}\n\n", "meta": {"hexsha": "642ecd424e160f07a1dd437f708083df43a6c111", "size": 160660, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "schedule/images/Chapter 2.ipynb", "max_stars_repo_name": "akyrillidis/comp414-514", "max_stars_repo_head_hexsha": "ed1a58cda99cb4cb14b62276eebfb4082276e9f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-26T02:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T11:10:52.000Z", "max_issues_repo_path": "schedule/images/Chapter 2.ipynb", "max_issues_repo_name": "akyrillidis/comp414-514", "max_issues_repo_head_hexsha": "ed1a58cda99cb4cb14b62276eebfb4082276e9f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "schedule/images/Chapter 2.ipynb", "max_forks_repo_name": "akyrillidis/comp414-514", "max_forks_repo_head_hexsha": "ed1a58cda99cb4cb14b62276eebfb4082276e9f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-07T05:45:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-07T05:45:48.000Z", "avg_line_length": 216.2314939435, "max_line_length": 50692, "alphanum_fraction": 0.8744615959, "converted": true, "num_tokens": 2868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422227627597, "lm_q2_score": 0.9626731149315424, "lm_q1q2_score": 0.9156390463299369}}
{"text": "## Chapter 4 - Training Models\n\n### Regularised Linear Models\n\nRecall that the cost function for:\n\n<b>Least Squares</b>\n\n$$\\begin{align}J(\\Theta) = \\text{RSS} &= \\sum_{i=1}^n \\begin{pmatrix} y_i - \\hat{y_i} \\end{pmatrix}^2\n\\\\&= \\sum_{i=1}^n \\begin{pmatrix} y_i - \\beta_0 - \\sum_{j=1}^p \\beta_j x_{ij}\\end{pmatrix}^2\\end{align}$$\n\n<b>Ridge Regression ($l_2$ normalisation)</b>\n\n$$\\begin{align}J(\\Theta) = \\text{RSS} + \\lambda \\sum_{j=1}^p\\beta^2_j &=\\sum_{i=1}^n\\begin{pmatrix} y_i - \\hat{y_i} \\end{pmatrix}^2 + \\lambda \\sum_{j=1}^p \\beta^2_j\\\\\n&= \\sum_{i=1}^n \\begin{pmatrix} y_i - \\beta_0 - \\sum_{j=1}^p \\beta_j x_{ij}\\end{pmatrix}^2 + \\lambda \\sum_{j=1}^p\\beta^2_j\\end{align}$$\n\n<b>Lasso Regression ($l_1$ normalisation)</b>\n\n$$\\begin{align}J(\\Theta) = \\text{RSS} + \\lambda \\sum_{j=1}^p|\\beta_j| &=\\sum_{i=1}^n\\begin{pmatrix} y_i - \\hat{y_i} \\end{pmatrix}^2 + \\lambda \\sum_{j=1}^p |\\beta_j|\\\\\n&= \\sum_{i=1}^n \\begin{pmatrix} y_i - \\beta_0 - \\sum_{j=1}^p \\beta_j x_{ij}\\end{pmatrix}^2 + \\lambda \\sum_{j=1}^p|\\beta_j|\\end{align}$$\n\nand the objective is to solve for $\\beta_0, \\cdots, \\beta_p$ that minimises the cost function.\n\nAnother formulation is:\n\n<b>Ridge Regression</b>\n\n\n$$\\underset{\\beta_0, \\cdots, \\beta_p}{\\text{Minimise}}\\left\\{\\sum_{i=1}^n \\begin{pmatrix} y_i - \\beta_0 - \\sum_{j=1}^p \\beta_j x_{ij}\\end{pmatrix}^2\\right\\}\\text{ s. t. } \\sum_{j=1}^p\\beta^2_j \\leq s$$\n\n<b>Lasso Regression</b>\n$$\\underset{\\beta_0, \\cdots, \\beta_p}{\\text{Minimise}}\\left\\{\\sum_{i=1}^n \\begin{pmatrix} y_i - \\beta_0 - \\sum_{j=1}^p \\beta_j x_{ij}\\end{pmatrix}^2\\right\\}\\text{ s. t. } \\sum_{j=1}^p |\\beta_j| \\leq s$$\n\nIn other words, for every value of $\\lambda$, there is some $s$ that gives the same coefficients for both sets of equations (ridge vs ridge, lasso vs lasso).\n\n<b>Graphical Representation</b>\nConsider $p=2$. The ridge minimisation constraint is now a circle $\\beta_1^2 + \\beta_2^2 \\leq s$. Similarly, the Lasso minimisation constraint is now a diamond $|\\beta_1| + |\\beta_2| \\leq s$. The coefficient estimates must be a point in these constraint regions (diamond / circle). \n\nThat means the coefficient estimates now need to satisfy the constraint bounded by $s$. If $s$ is very large, there is no restriction and the coefficient estimates could be the same as the solution without regularisation. If $s$ is small, then the coefficient estimates will be optimised within the constraint.\n\n\n\nGraphically, the red contours represent the cost function, $J(\\Theta)$. The contour lines all represent the same value of $J(\\Theta)$. Recall that it is convex. The black coordinate $\\hat{\\beta_0}$ represents the least squares estimate of $\\beta_1, \\beta_2$. The diamond and circle represent that constraints $|\\beta_1| + |\\beta_2| \\leq s$ and $\\beta_1^2 + \\beta_2^2 \\leq s$ respectively. The point (on the edge of the region that is closest to the least squares estimate) is hence the coefficient estimates of the regularised model. \n\nFrom here, observe that a large $s$ will eventually result in the least squares estimate to be in the region. That corresponds to a small $\\lambda$.\n\nAlso observe that the lasso constrains have corners on the axes. When the minimum value of $J(\\Theta)$ lies on the corners, then the coefficient estimate is $0$. In this case $\\hat{\\beta_1}=0$ and the regularised model only contains $\\hat{\\beta_2}$.\n\nWhen $p=3$ then the ridge regression constraint is a sphere and the lasso regression constraint is a polyhedron. These key ideas still hold as $p$ increases beyond geometric formulations.\n", "meta": {"hexsha": "5f3cac29535949132441da32198aab8269734be2", "size": 4842, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chap04/04-textbook-training-models-03b.ipynb", "max_stars_repo_name": "bryanblackbee/topic__hands-on-machine-learning", "max_stars_repo_head_hexsha": "3b9a2cfa011099178dd73c3366331958d49ad96f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chap04/04-textbook-training-models-03b.ipynb", "max_issues_repo_name": "bryanblackbee/topic__hands-on-machine-learning", "max_issues_repo_head_hexsha": "3b9a2cfa011099178dd73c3366331958d49ad96f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chap04/04-textbook-training-models-03b.ipynb", "max_forks_repo_name": "bryanblackbee/topic__hands-on-machine-learning", "max_forks_repo_head_hexsha": "3b9a2cfa011099178dd73c3366331958d49ad96f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-20T05:38:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-20T05:38:43.000Z", "avg_line_length": 50.4375, "max_line_length": 555, "alphanum_fraction": 0.6024370095, "converted": true, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995713428387, "lm_q2_score": 0.9449947157729751, "lm_q1q2_score": 0.9127699908863643}}
{"text": "```python\nimport sympy\n```\n\n# Item V\n\nImplement in Jupyter Notebook the Lagrange Interpolation method with *sympy*.\nThen, find the interpolation polynomial for the following points:\n* $(0,1),(1,2),(2,4)$. Is a second degree polynomial? If not, why is this?\n* $(0,1),(1,2),(2,3)$. Is a second degree polynomial? If not, why is this?\n---\n\n\n```python\ndef lagrange(xs,ys):\n assert(len(xs)==len(ys))\n n = len(xs)\n x = sympy.Symbol('x')\n \n poly = 0\n for j in range(0,n):\n lag = ys[j]\n for m in range(0,n):\n if j!=m:\n lag *= (x-xs[m])/(xs[j]-xs[m])\n poly += lag\n return sympy.simplify(poly)\n```\n\n\n```python\nlagrange([0,1,2],[1,2,4])\n```\n\n\n\n\n$\\displaystyle \\frac{x^{2}}{2} + \\frac{x}{2} + 1$\n\n\n\n\n```python\nlagrange([0,1,2],[1,2,3])\n```\n\n\n\n\n$\\displaystyle x + 1$\n\n\n\n* The first points have to be interpolated by a second degree polynomial as they are not collinear, so they cannot be interpolated by a line.\n* The second set of points are collinear, so they are interpolated by a polynomial of degree 1.\n", "meta": {"hexsha": "f0cb258e9bfd8d4b4f1e01c772846f6e08e608e2", "size": 2680, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "t1_questions/item_05.ipynb", "max_stars_repo_name": "autopawn/cc5-works", "max_stars_repo_head_hexsha": "63775574c82da85ed0e750a4d6978a071096f6e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "t1_questions/item_05.ipynb", "max_issues_repo_name": "autopawn/cc5-works", "max_issues_repo_head_hexsha": "63775574c82da85ed0e750a4d6978a071096f6e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "t1_questions/item_05.ipynb", "max_forks_repo_name": "autopawn/cc5-works", "max_forks_repo_head_hexsha": "63775574c82da85ed0e750a4d6978a071096f6e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7886178862, "max_line_length": 150, "alphanum_fraction": 0.4798507463, "converted": true, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9805806512500485, "lm_q2_score": 0.9294404082102516, "lm_q1q2_score": 0.9113912807809195}}
{"text": "## Expected value of random variable\n\nExpected value of random variable is generalization of taking average of numbers. It is similar to taking weighted average, where each value of random variable is multiplied by it's probability. \n\n$$\\mathbb{E}[X] = \\sum_{x \\in \\mathcal{X}} x \\cdot p_X(x) $$\n\nAlso in terms of conditional probability,\n$$\\mathbb{E}[X \\mid Y=y] = \\sum_{x \\in \\mathcal{X}} x \\cdot p_{X\\mid Y}(x\\mid y)$$\n\nIn general, let $f$ any function from $\\mathbb{R}$ to $\\mathbb{R}$, then \n\n$$ \\mathbb{E}[f(X)] = \\sum_{x \\in \\mathcal{X}} f(x) \\cdot p_X(x) $$\n\nThus expectection gives a single number associated with a probability table.\n\n### Exercise: Expected Value\n\nSuppose that a student's score on a test will be $100$ if she studies the week before, and $75$ if she does not. Suppose also that the student's probability of studying the week before is $0.8$. What is her expected score? (Please provide an exact answer.)\n\n\n```python\nX = {'S': 100, 'N':75}; p_X = {'S': 0.80, 'N': 0.20}\nE_X = sum([X[i] * p_X[i] for i in X]); E_X\n```\n\n\n\n\n 95.0\n\n\n\nLet's look at why the expected value of a random variable is in some sense a “good\" average value. Let $X$ be the result of a single fair six-sided die with faces $1$ up through $6$.\n\nSimulate 10,000 rolls of the die roll in Python and take the average of the faces that appeared. What do you get? (Just make a note of it. There's no answer box to enter this in.)\n\nWhat is $\\mathbb{E}[X]$? (Please provide an exact answer.)\n\n\n```python\nE_X = sum([i * 1/6 for i in range(1,7)]); E_X\n```\n\n\n\n\n 3.5\n\n\n\nYou should notice that the average you get in simulation should be very close to E[X], and in fact, if you increase the number of rolls, it will tend to get closer (it doesn't necessarily have to get closer when you do each additional roll but the trend is there as you just keep increasing the number of rolls).\n\n\n```python\nimport sys\nimport numpy as np\nsys.path.append('../comp_prob_inference')\nimport comp_prob_inference\np_X = {i: 1/6 for i in range(1, 7)}\nnum_samples = 10000\nprint(np.mean([comp_prob_inference.sample_from_finite_probability_space(p_X) for n in range(num_samples)]))\n```\n\n 3.497\n\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(8, 4))\n\nn = 5000\nx = list(range(1, n+1))\ny = []\nfor i in x:\n if i == 1:\n y.append(comp_prob_inference.sample_from_finite_probability_space(p_X))\n if i > 1:\n y.append((y[i-2] * (i-1) + comp_prob_inference.sample_from_finite_probability_space(p_X)) / i)\n \nplt.xlabel('No of dice rolled')\nplt.ylabel('Expected value')\nplt.plot(x,y)\nplt.show()\n```\n\nWe can observe that as the no of dice roll increases the become closer to $3.5$.\n\n## Variance \n\nThis exercise explores the important concept of variance, which measures how much a random variable deviates from its expectation. This can be thought of as a measure of uncertainty. Higher variance means more uncertainty.\n\nThe variance of a real-valued random variable $X$ is defined as\n\n$$\\text {var}(X) \\triangleq \\mathbb {E}[ (X - \\mathbb {E}[X])^2 ].$$\n \nNote that as we saw previously, $\\mathbb{E}[X]$ is just a single number. To keep the variance of $X$, what you could do is first compute the expectation of $X$.\n\nFor example, if $X$ takes on each of the values $3$, $5$, and $10$ with equal probability $1/3$, then first we compute $\\mathbb{E}[X]$ to get $6$, and then we compute $\\mathbb{E}[(X−6)^2]$, where we remember to use the result that for a function $f$, if $f(X)$ is a real-valued random variable, then $\\mathbb{E}[f(X)]=\\sum_x xf(x)pX(x)$. Here, $f$ is given by $f(x)=(x−6)^2$. So\n\n$$\\text {var}(X) = (3 - 6)^2 \\cdot \\frac13 + (5 - 6)^2 \\cdot \\frac13 + (10 - 6)^2 \\cdot \\frac13 = \\frac{26}{3}.$$\n\n\n```python\ndef E(p_X):\n return sum([key * value for key, value in p_X.items()]) \n \n\ndef VAR(p_X):\n avg = E(p_X)\n p_Xt = {(key - avg)**2 : value for key, value in p_X.items()}\n return E(p_Xt)\n```\n\n### Exercise \n\nLet's return to the three lotteries from earlier. Here, random variables $L_1$, $L_2$, and $L_3$ represent the amount won (accounting for having to pay \\$1):\n\n|$L_1$ | $p$ | $L_2$ | $p$ | $L_3$ | $p$ |\n|----------:|:------------------------:|-------------:|:------------------------:|--------:|:--------------:|\n| -1 | $\\frac{999999}{1000000}$ | -1 | $\\frac{999999}{1000000}$ | -1 | $\\frac{9}{10}$ |\n| -1+1000 | $\\frac{1}{1000000}$ | -1+1000000 | $\\frac{1}{1000000}$ | -1+10 | $\\frac{1}{10}$ |\n\n\nCompute the variance for each of these three random variables. (Please provide the exact answer for each of these.)\n\n- var($L_1$)= {{V_1}} \n- var($L_2$)= {{V_2}} \n- var($L_3$)= {{V_3}} \n\n\n```python\np_L1 = {-1: 999999/1000000, 999 : 1/1000000}\np_L2 = {-1: 999999/1000000, 999999: 1/1000000}\np_L3 = {-1: 9/10 , 9 : 1/10 }\n\nV_1 = VAR(p_L1)\nV_2 = VAR(p_L2)\nV_3 = VAR(p_L3)\n```\n\nWhat units is variance in? Notice that we started with dollars, and then variance is looking at the expectation of a dollar amount squared. Thus, specifically for the lottery example $\\text {var}(L_1)$, $\\text {var}(L_2)$, and $\\text {var}(L_3)$ are each in squared dollars.\n\n## Standard Deviation\n\nSome times, people prefer keeping the units the same as the original units (i.e., without squaring), which you can get by computing what's called the standard deviation of a real-valued random variable $X$:\n\n$$\\text {std}(X) \\triangleq \\sqrt {\\text {var}(X)}.$$\n\n\n```python\ndef STD(p_X):\n from sympy import sqrt \n return sqrt(VAR(p_X))\n```\n\n### Exercise \n\nCompute the following standard deviations, which are in units of dollars. (Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n- std($L_1$) = {{print(S_1)}}\n- std($L_2$) = {{print(S_2)}}\n- std($L_3$) = {{print(S_3)}}\n\n\n```python\nS_1 = STD(p_L1)\nS_2 = STD(p_L2)\nS_3 = STD(p_L3) \n```\n\n!Note \n When we first introduced the three lotteries and computed average winnings, we didn't account for the uncertainty in the average winnings. Here, it's clear that the third lottery has far smaller standard deviation and variance than the second lottery.<br>\n As a remark, often in financial applications (e.g., choosing a portfolio of stocks to invest in), accounting for uncertainty is extremely important. For example, you may want to maximize profit while ensuring that the amount of uncertainty is not too high as to not be reckless in investing.\n\nIn the case of the three lotteries, to decide between them, you could for example use a score that is of the form\n\n$$\\mathbb {E}[L_ i] - \\lambda \\cdot \\text {std}(L_ i) \\qquad \\text {for }i = 1,2,3,$$\n \nwhere $λ≥0$ is some parameter that you choose for how much you want to penalize uncertainty in the lottery outcome. Then you could choose the lottery with the highest score.\n\nFinally, a quick sanity check (this is more for you to think about the definition of variance rather than to compute anything out):\n\n**Question:** Can variance be negative? If yes, give a specific distribution as a Python dictionary for which the variance is negative. If no, enter the text \"no\" (all lowercase, one word, no spaces).\n\n**Answer:** NO\n\n## The Law of Total Expectation\n\nRemember the law of total probability? For a set of events $\\mathcal{B}_{1},\\dots ,\\mathcal{B}_{n}$ that partition the sample space $Ω$ (so the Bi's don't overlap and together they fully cover the full space of possible outcomes),\n\n$$\\mathbb {P}(\\mathcal{A})=\\sum _{i=1}^{n}\\mathbb {P}(\\mathcal{A}\\cap \\mathcal{B}_{i})=\\sum _{i=1}^{n}\\mathbb {P}(\\mathcal{A}\\mid \\mathcal{B}_{i})\\mathbb {P}(\\mathcal{B}_{i}),$$\n \nwhere the second equality uses the product rule.\n\nA similar statement is true for the expected value of a random variable, called the law of total expectation: for a random variable $X$ (with alphabet $\\mathcal{X}$) and a partition $\\mathcal{B}_1,\\dots ,\\mathcal{B}_ n$ of the sample space,\n\n$$\\mathbb {E}[X]=\\sum _{i=1}^{n}\\mathbb {E}[X\\mid \\mathcal{B}_{i}]\\mathbb {P}(\\mathcal{B}_{i}),$$\n \nwhere\n\n$$\\mathbb {E}[X\\mid \\mathcal{B}_{i}] = \\sum _{x\\in \\mathcal{X}}xp_{X\\mid \\mathcal{B}_{i}}(x) = \\sum _{x\\in \\mathcal{X}}x\\frac{\\mathbb {P}(X=x,\\mathcal{B}_{i})}{\\mathbb {P}(\\mathcal{B}_{i})}.$$\n \nWe will be using this result in the section “Towards Infinity in Modeling Uncertainty\".\n\nShow that the law of total expectation is true.\n\n**Solution:** There are different ways to prove the law of total expectation. We take a fairly direct approach here, first writing everything in terms of outcomes in the sample space.\n\nThe main technical hurdle is that the events $\\mathcal{B}_1, \\dots , \\mathcal{B}_ n$ are specified directly in the sample space, whereas working with values that $X$ takes on requires mapping from the sample space to the alphabet of $X$.\n\nWe will derive the law of total expectation starting from the right-hand side of the equation above, i.e., $\\sum _{i=1}^{n}\\mathbb {E}[X\\mid \\mathcal{B}_{i}]\\mathbb {P}(\\mathcal{B}_{i})$.\n\nWe first write $\\mathbb {E}[X\\mid \\mathcal{B}_{i}]$ in terms of a summation over outcomes in $\\Omega$:\n\n$$\\begin{align}\n\\mathbb {E}[X\\mid \\mathcal{B}_{i}]\t=& \\sum _{x\\in \\mathcal{X}}x\\frac{\\mathbb {P}(X=x,\\mathcal{B}_{i})}{\\mathbb {P}(\\mathcal{B}_{i})}\\\\ \t \n=& \\sum _{x\\in \\mathcal{X}}x\\frac{\\mathbb {P}(\\{ \\omega \\in \\Omega \\; :\\; X(\\omega )=x\\} \\cap \\mathcal{B}_{i})}{\\mathbb {P}(\\mathcal{B}_{i})}\\\\ \t \n=& \\sum _{x\\in \\mathcal{X}}x\\frac{\\mathbb {P}(\\{ \\omega \\in \\Omega \\; :\\; X(\\omega )=x\\text { and }\\omega \\in \\mathcal{B}_{i}\\} )}{\\mathbb {P}(\\mathcal{B}_{i})}\\\\ \t \n=& \\sum _{x\\in \\mathcal{X}}x\\frac{\\mathbb {P}(\\{ \\omega \\in \\mathcal{B}_{i}\\; :\\; X(\\omega )=x\\} )}{\\mathbb {P}(\\mathcal{B}_{i})}\\\\\t \t \n=& \\sum _{x\\in \\mathcal{X}}x\\cdot \\frac{\\sum _{\\omega \\in \\mathcal{B}_{i}\\text { such that }X(\\omega )=x}\\mathbb {P}(\\{ \\omega \\} )}{\\mathbb {P}(\\mathcal{B}_{i})}\t\\\\ \t \n=& \\frac{1}{\\mathbb {P}(\\mathcal{B}_{i})}\\sum _{x\\in \\mathcal{X}}x\\sum _{\\omega \\in \\mathcal{B}_{i}\\text { such that }X(\\omega )=x}\\mathbb {P}(\\{ \\omega \\} )\\\\ \t \n=& \\frac{1}{\\mathbb {P}(\\mathcal{B}_{i})}\\sum _{\\omega \\in \\mathcal{B}_{i}}X(\\omega )\\mathbb {P}(\\{ \\omega \\} ).\n\\end{align}$$\n\nThus,\n\n$$\\begin{align}\n\\sum _{i=1}^{n}\\mathbb {E}[X\\mid \\mathcal{B}_{i}]\\mathbb {P}(\\mathcal{B}_{i})=& \\sum _{i=1}^{n}\\bigg(\\frac{1}{\\mathbb {P}(\\mathcal{B}_{i})}\\sum _{\\omega \\in \\mathcal{B}_{i}}X(\\omega )\\mathbb {P}(\\{ \\omega \\} )\\bigg)\\mathbb {P}(\\mathcal{B}_{i})\\\\\t \t \n=& \\sum _{i=1}^{n}\\sum _{\\omega \\in \\mathcal{B}_{i}}X(\\omega )\\mathbb {P}(\\{ \\omega \\} )\\\\\n=& \\sum _{\\omega \\in \\Omega }X(\\omega )\\mathbb {P}(\\{ w\\} )\\\\\n=& \\sum _{x\\in \\mathcal{X}}x\\mathbb {P}(\\{ \\omega \\in \\Omega \\text { such that }X(\\omega )=x\\} )\\\\\t \t \n=& \\sum _{x\\in \\mathcal{X}}xp_{X}(x)\\\\\t \t \n=&\\mathbb {E}[X].\n\\end{align}$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "95b6006f5e19631a8e79b179ae13879152d7bb24", "size": 36290, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week04/01 Expected Value.ipynb", "max_stars_repo_name": "infimath/Computational-Probability-and-Inference", "max_stars_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-04T03:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-04T03:07:47.000Z", "max_issues_repo_path": "week04/01 Expected Value.ipynb", "max_issues_repo_name": "infimath/Computational-Probability-and-Inference", "max_issues_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week04/01 Expected Value.ipynb", "max_forks_repo_name": "infimath/Computational-Probability-and-Inference", "max_forks_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-27T05:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T05:33:49.000Z", "avg_line_length": 76.0796645702, "max_line_length": 19276, "alphanum_fraction": 0.7550289336, "converted": true, "num_tokens": 3566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995733060718, "lm_q2_score": 0.9433475786738345, "lm_q1q2_score": 0.9111790237203727}}
{"text": "```python\nfrom sympy import *\ninit_printing(use_latex='mathjax')\nn = symbols('n', integer=True)\nx, y, z = symbols('x,y,z')\n```\n\n## Integrales\n\nEn la primera sección aprendimos diferenciación simbólica con `diff`. Aquí abordaremos la integración simbólica con `integrate`. \n\nAsí es cómo escribimos la integral indefinida\n\n$$ \\int x^2 dx = \\frac{x^3}{3}$$\n\n\n```python\n# Integral indefinida\nintegrate(x**2, x)\n```\n\ny la integral definida\n\n$$ \\int_0^3 x^2 dx = \\left.\\frac{x^3}{3} \\right|_0^3 = \\frac{3^3}{3} - \\frac{0^3}{3} = 9 $$\n\n\n```python\n# Integral definida\nintegrate(x**2, (x, 0, 3))\n```\n\nComo siempre, debido a que estamos usando símbolos, podríamos usar un símbolo donde sea que hayamos usado un número\n\n$$ \\int_y^z x^n dx $$\n\n\n```python\nintegrate(x**n, (x, y, z))\n```\n\n### Ejercicio\n\nCalcule las siguientes integrales:\n\n$$ \\int \\sin(x) dx $$\n$$ \\int_0^{\\pi} \\sin(x) dx $$\n$$ \\int_0^y x^5 + 12x^3 - 2x + 1 $$\n$$ \\int e^{\\frac{(x - \\mu)^2}{\\sigma^2}} $$\n\nSiéntete libre de jugar con varios parámetros y configuraciones y ver cómo cambian los resultados.\n\n\n```python\n# Usa `integrate` para resolver las integrales anteriores\n\n\n```\n\n¿Hay algunas integrales que *SymPy* no puede hacer? Encuentra alguna.\n\n\n```python\n# Usa `integrate` en otras ecuaciones. La integración simbólica tiene sus límites, encuéntralos.\n```\n", "meta": {"hexsha": "801e8d4939094f8696e2cf0f2ae182eeccc97134", "size": 3123, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial_exercises/03-Integrals.ipynb", "max_stars_repo_name": "t3rodrig/sympy-tutorial-es", "max_stars_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial_exercises/03-Integrals.ipynb", "max_issues_repo_name": "t3rodrig/sympy-tutorial-es", "max_issues_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial_exercises/03-Integrals.ipynb", "max_forks_repo_name": "t3rodrig/sympy-tutorial-es", "max_forks_repo_head_hexsha": "5cd5497f799e889d758a26539781cdc72b1e6a74", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5379310345, "max_line_length": 135, "alphanum_fraction": 0.516490554, "converted": true, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9648551546097942, "lm_q2_score": 0.9433475723029411, "lm_q1q2_score": 0.9101937677251283}}
{"text": "# Applications\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.linalg as la\n```\n\n## Polynomial Interpolation\n\n[Polynomial interpolation](https://en.wikipedia.org/wiki/Polynomial_interpolation) finds the unique polynomial of degree $n$ which passes through $n+1$ points in the $xy$-plane. For example, two points in the $xy$-plane determine a line and three points determine a parabola.\n\n### Formulation\n\nSuppose we have $n + 1$ points in the $xy$-plane\n\n$$\n(x_0,y_0),(x_1,y_1),\\dots,(x_n,y_n)\n$$\n\nsuch that all the $x$ values are distinct ($x_i \\not= x_j$ for $i \\not= j$). The general form of a degree $n$ polynomial is\n\n$$\np(x) = a_0 + a_1 x + a_2x^2 + \\cdots + a_n x^n\n$$\n\nIf $p(x)$ is the unique degree $n$ polynomial which interpolates all the points, then the coefficients $a_0$, $a_1$, $\\dots$, $a_n$ satisfy the following equations:\n\n\\begin{align}\na_0 + a_1x_0 + a_2x_0^2 + \\cdots + a_n x_0^n &= y_0 \\\\\\\na_0 + a_1x_1 + a_2x_1^2 + \\cdots + a_n x_1^n &= y_1 \\\\\\\n& \\ \\ \\vdots \\\\\\\na_0 + a_1x_n + a_2x_n^2 + \\cdots + a_n x_n^n &= y_n\n\\end{align}\n\nTherefore the vector of coefficients\n\n$$\n\\mathbf{a} =\n\\begin{bmatrix}\na_0 \\\\\\\na_1 \\\\\\\n\\vdots \\\\\\\na_n\n\\end{bmatrix}\n$$\n\nis the unique the solution of the linear system of equations\n\n$$\nX \\mathbf{a}=\\mathbf{y}\n$$\n\nwhere $X$ is the [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix) and $\\mathbf{y}$ is the vector of $y$ values\n\n$$\nX =\n\\begin{bmatrix}\n1 & x_0 & x_0^2 & \\dots & x_0^n \\\\\\\n1 & x_1 & x_1^2 & \\dots & x_1^n \\\\\\\n & \\vdots & & & \\vdots \\\\\\\n1 & x_n & x_n^2 & \\dots & x_n^n \\\\\\\n\\end{bmatrix}\n\\ \\ \\mathrm{and} \\ \\\n\\mathbf{y} =\n\\begin{bmatrix}\ny_0 \\\\\\\ny_1 \\\\\\\ny_2 \\\\\\\n\\vdots \\\\\\\ny_n\n\\end{bmatrix}\n$$\n\n### Examples\n\n**Simple Parabola**\n\nLet's do a simple example. We know that $y=x^2$ is the unique degree 2 polynomial that interpolates the points $(-1,1)$, $(0,0)$ and $(1,1)$. Let's compute the polynomial interpolation of these points and verify the expected result $a_0=0$, $a_1=0$ and $a_2=1$.\n\nCreate the Vandermonde matrix $X$ with the array of $x$ values:\n\n\n```python\nx = np.array([-1,0,1])\nX = np.column_stack([[1,1,1],x,x**2])\nprint(X)\n```\n\n [[ 1 -1 1]\n [ 1 0 0]\n [ 1 1 1]]\n\n\nCreate the vector $\\mathbf{y}$ of $y$ values:\n\n\n```python\ny = np.array([1,0,1]).reshape(3,1)\nprint(y)\n```\n\n [[1]\n [0]\n [1]]\n\n\nWe expect the solution $\\mathbf{a} = [0,0,1]^T$:\n\n\n```python\na = la.solve(X,y)\nprint(a)\n```\n\n [[0.]\n [0.]\n [1.]]\n\n\nSuccess!\n\n**Another Parabola**\n\nThe polynomial interpolation of 3 points $(x_0,y_0)$, $(x_1,y_1)$ and $(x_2,y_2)$ is the parabola $p(x) = a_0 + a_1x + a_2x^2$ such that the coefficients satisfy\n\n\\begin{align}\na_0 + a_1x_0 + a_2x_0^2 = y_0 \\\\\\\na_0 + a_1x_1 + a_2x_1^2 = y_1 \\\\\\\na_0 + a_1x_2 + a_2x_2^2 = y_2\n\\end{align}\n\nLet's find the polynomial interpolation of the points $(0,6)$, $(3,1)$ and $(8,2)$.\n\nCreate the Vandermonde matrix $X$:\n\n\n```python\nx = np.array([0,3,8])\nX = np.column_stack([[1,1,1],x,x**2])\nprint(X)\n```\n\n [[ 1 0 0]\n [ 1 3 9]\n [ 1 8 64]]\n\n\nAnd the vector of $y$ values:\n\n\n```python\ny = np.array([6,1,2]).reshape(3,1)\nprint(y)\n```\n\n [[6]\n [1]\n [2]]\n\n\nCompute the vector $\\mathbf{a}$ of coefficients:\n\n\n```python\na = la.solve(X,y)\nprint(a)\n```\n\n [[ 6. ]\n [-2.36666667]\n [ 0.23333333]]\n\n\nAnd plot the result:\n\n\n```python\nxs = np.linspace(0,8,20)\nys = a[0] + a[1]*xs + a[2]*xs**2\nplt.plot(xs,ys,x,y,'b.',ms=20)\nplt.show()\n```\n\n**Over Fitting 10 Random Points**\n\nNow let's interpolate points with $x_i=i$, $i=0,\\dots,9$, and 10 random integers sampled from $[0,10)$ as $y$ values:\n\n\n```python\nN = 10\nx = np.arange(0,N)\ny = np.random.randint(0,10,N)\nplt.plot(x,y,'r.')\nplt.show()\n```\n\nCreate the Vandermonde matrix and verify the first 5 rows and columns:\n\n\n```python\nX = np.column_stack([x**k for k in range(0,N)])\nprint(X[:5,:5])\n```\n\n [[ 1 0 0 0 0]\n [ 1 1 1 1 1]\n [ 1 2 4 8 16]\n [ 1 3 9 27 81]\n [ 1 4 16 64 256]]\n\n\nWe could also use the NumPy function [`numpy.vander`](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.vander.html). We specify the option `increasing=True` so that powers of $x_i$ increase left-to-right:\n\n\n```python\nX = np.vander(x,increasing=True)\nprint(X[:5,:5])\n```\n\n [[ 1 0 0 0 0]\n [ 1 1 1 1 1]\n [ 1 2 4 8 16]\n [ 1 3 9 27 81]\n [ 1 4 16 64 256]]\n\n\nSolve the linear system:\n\n\n```python\na = la.solve(X,y)\n```\n\nPlot the interpolation:\n\n\n```python\nxs = np.linspace(0,N-1,200)\nys = sum([a[k]*xs**k for k in range(0,N)])\nplt.plot(x,y,'r.',xs,ys)\nplt.show()\n```\n\nSuccess! But notice how unstable the curve is. That's why it better to use a [cubic spline](https://en.wikipedia.org/wiki/Spline_%28mathematics%29) to interpolate a large number of points.\n\nHowever real-life data is usually very noisy and interpolation is not the best tool to fit a line to data. Instead we would want to take a polynomial with smaller degree (like a line) and fit it as best we can without interpolating the points.\n\n## Least Squares Linear Regression\n\nSuppose we have $n+1$ points\n\n$$\n(x_0,y_0) , (x_1,y_1) , \\dots , (x_n,y_n)\n$$\n\nin the $xy$-plane and we want to fit a line\n\n$$\ny=a_0 + a_1x\n$$\n\nthat \"best fits\" the data. There are different ways to quantify what \"best fit\" means but the most common method is called [least squares linear regression](https://en.wikipedia.org/wiki/Linear_regression). In least squares linear regression, we want to minimize the sum of squared errors\n\n$$\nSSE = \\sum_i (y_i - (a_0 + a_1 x_i))^2\n$$\n\n### Formulation\n\nIf we form matrices\n\n$$\nX =\n\\begin{bmatrix}\n1 & x_0 \\\\\\\n1 & x_1 \\\\\\\n\\vdots & \\vdots \\\\\\\n1 & x_n\n\\end{bmatrix}\n\\ , \\ \\\n\\mathbf{y} =\n\\begin{bmatrix}\ny_0 \\\\\\\ny_1 \\\\\\\n\\vdots \\\\\\\ny_n\n\\end{bmatrix}\n\\ , \\ \\\n\\mathbf{a} = \n\\begin{bmatrix}\na_0 \\\\\\ a_1\n\\end{bmatrix}\n$$\n\nthen the sum of squared errors can be expressed as\n\n$$\nSSE = \\Vert \\mathbf{y} - X \\mathbf{a} \\Vert^2\n$$\n\n---\n\n**Theorem.** (Least Squares Linear Regression) Consider $n+1$ points\n\n$$\n(x_0,y_0) , (x_1,y_1) , \\dots , (x_n,y_n)\n$$\n\nin the $xy$-plane. The coefficients $\\mathbf{a} = [a_0,a_1]^T$ which minimize the sum of squared errors\n\n$$\nSSE = \\sum_i (y_i - (a_0 + a_1 x_i))^2\n$$\n\nis the unique solution of the system\n\n$$\n\\left( X^T X \\right) \\mathbf{a} = X^T \\mathbf{y}\n$$\n\n*Sketch of Proof.* The product $X\\mathbf{a}$ is in the column space of $X$. The line connecting $\\mathbf{y}$ to the nearest point in the column space of $X$ is perpendicluar to the column space of $X$. Therefore\n\n$$\nX^T \\left( \\mathbf{y} - X \\mathbf{a} \\right) = \\mathbf{0}\n$$\n\nand so\n\n$$\n\\left( X^T X \\right) \\mathbf{a} = X^T \\mathbf{y}\n$$\n\n---\n\n### Examples\n\n**Fake Noisy Linear Data**\n\nLet's do an example with some fake data. Let's build a set of random points based on the model\n\n$$\ny = a_0 + a_1x + \\epsilon\n$$\n\nfor some arbitrary choice of $a_0$ and $a_1$. The factor $\\epsilon$ represents some random noise which we model using the [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution). We can generate random numbers sampled from the standard normal distribution using the NumPy function [`numpy.random.rand`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html).\n\nThe goal is to demonstrate that we can use linear regression to retrieve the coefficeints $a_0$ and $a_1$ from the linear regression calculation.\n\n\n```python\na0 = 2\na1 = 3\nN = 100\nx = np.random.rand(100)\nnoise = 0.1*np.random.randn(100)\ny = a0 + a1*x + noise\nplt.scatter(x,y);\nplt.show()\n```\n\nLet's use linear regression to retrieve the coefficients $a_0$ and $a_1$. Construct the matrix $X$:\n\n\n```python\nX = np.column_stack([np.ones(N),x])\nprint(X.shape)\n```\n\n (100, 2)\n\n\nLet's look at the first 5 rows of $X$ to see that it is in the correct form:\n\n\n```python\nX[:5,:]\n```\n\n\n\n\n array([[1. , 0.92365627],\n [1. , 0.78757973],\n [1. , 0.51506055],\n [1. , 0.51540875],\n [1. , 0.86563343]])\n\n\n\nUse `scipy.linalg.solve` to solve $\\left(X^T X\\right)\\mathbf{a} = \\left(X^T\\right)\\mathbf{y}$ for $\\mathbf{a}$:\n\n\n```python\na = la.solve(X.T @ X, X.T @ y)\nprint(a)\n```\n\n [2.02783873 2.95308228]\n\n\nWe have retrieved the coefficients of the model almost exactly! Let's plot the random data points with the linear regression we just computed.\n\n\n```python\nxs = np.linspace(0,1,10)\nys = a[0] + a[1]*xs\nplt.plot(xs,ys,'r',linewidth=4)\nplt.scatter(x,y);\nplt.show()\n```\n\n**Real Kobe Bryant Data**\n\nLet's work with some real data. [Kobe Bryant](https://www.basketball-reference.com/players/b/bryanko01.html) retired in 2016 with 33643 total points which is the [third highest total points in NBA history](https://en.wikipedia.org/wiki/List_of_National_Basketball_Association_career_scoring_leaders). How many more years would Kobe Bryant have to had played to pass [Kareem Abdul-Jabbar's](https://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar) record 38387 points?\n\nKobe Bryant's peak was the 2005-2006 NBA season. Let's look at Kobe Bryant's total games played and points per game from 2006 to 2016.\n\n\n```python\nyears = np.array([2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016])\ngames = [80,77,82,82,73,82,58,78,6,35,66]\npoints = np.array([35.4,31.6,28.3,26.8,27,25.3,27.9,27.3,13.8,22.3,17.6])\n\nfig = plt.figure(figsize=(12,10))\naxs = fig.subplots(2,1,sharex=True)\naxs[0].plot(years,points,'b.',ms=15)\naxs[0].set_title('Kobe Bryant, Points per Game')\naxs[0].set_ylim([0,40])\naxs[0].grid(True)\naxs[1].bar(years,games)\naxs[1].set_title('Kobe Bryant, Games Played')\naxs[1].set_ylim([0,100])\naxs[1].grid(True)\nplt.show()\n```\n\nKobe was injured for most of the 2013-2014 NBA season and played only 6 games. This is an outlier and so we can drop this data point:\n\n\n```python\nyears = np.array([2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2016])\ngames = np.array([80,77,82,82,73,82,58,78,35,66])\npoints = np.array([35.4,31.6,28.3,26.8,27,25.3,27.9,27.3,22.3,17.6])\n```\n\nLet's compute the average games played per season over this period:\n\n\n```python\navg_games_per_year = np.mean(games)\nprint(avg_games_per_year)\n```\n\n 71.3\n\n\nCompute the linear model for points per game:\n\n\n```python\nX = np.column_stack([np.ones(len(years)),years])\na = la.solve(X.T @ X, X.T @ points)\nmodel = a[0] + a[1]*years\n\nplt.plot(years,model,years,points,'b.',ms=15)\nplt.title('Kobe Bryant, Points per Game')\nplt.ylim([0,40])\nplt.grid(True)\nplt.show()\n```\n\nNow we can extrapolate to future years and multiply points per games by games per season and compute the cumulative sum to see Kobe's total points:\n\n\n```python\nfuture_years = np.array([2017,2018,2019,2020,2021])\nfuture_points = (a[0] + a[1]*future_years)*avg_games_per_year\ntotal_points = 33643 + np.cumsum(future_points)\nkareem = 38387*np.ones(len(future_years))\n\nplt.plot(future_years,total_points,future_years,kareem)\nplt.grid(True)\nplt.xticks(future_years)\nplt.title('Kobe Bryant Total Points Prediction')\nplt.show()\n```\n\nOnly 4 more years!\n\n## Polynomial Regression\n\n### Formulation\n\nThe same idea works for fitting a degree $d$ polynomial model\n\n$$\ny = a_0 + a_1x + a_2x^2 + \\cdots + a_dx^d\n$$\n\nto a set of $n+1$ data points\n\n$$\n(x_0,y_0), (x_1,y_1), \\dots , (x_n,y_n)\n$$\n\nWe form the matrices as before but now the Vandermonde matrix $X$ has $d+1$ columns\n\n$$\nX =\n\\begin{bmatrix}\n1 & x_0 & x_0^2 & \\cdots & x_0^d \\\\\\\n1 & x_1 & x_1^2 & \\cdots & x_1^d \\\\\\\n & \\vdots & & & \\vdots \\\\\\\n1 & x_n & x_n^2 & \\cdots & x_n^d\n\\end{bmatrix}\n\\ , \\ \\\n\\mathbf{y} =\n\\begin{bmatrix}\ny_0 \\\\\\\ny_1 \\\\\\\n\\vdots \\\\\\\ny_n\n\\end{bmatrix}\n\\ , \\ \\\n\\mathbf{a} =\n\\begin{bmatrix}\na_0 \\\\\\\na_1 \\\\\\\na_2 \\\\\\\n\\vdots \\\\\\\na_d\n\\end{bmatrix}\n$$\n\nThe coefficients $\\mathbf{a} = [a_0,a_1,a_2,\\dots,a_d]^T$ which minimize the sum of squared errors $SSE$ is the unique solution of the linear system\n\n$$\n\\left( X^T X \\right) \\mathbf{a} = \\left( X^T \\right) \\mathbf{y}\n$$\n\n### Example\n\n**Fake Noisy Quadratic Data**\n\nLet's build some fake data using a quadratic model $y = a_0 + a_1x + a_2x^2 + \\epsilon$ and use linear regression to retrieve the coefficients $a_0$, $a_1$ and $a_2$.\n\n\n```python\na0 = 3\na1 = 5\na2 = 8\nN = 1000\nx = 2*np.random.rand(N) - 1 # Random numbers in the interval (-1,1)\nnoise = np.random.randn(N)\ny = a0 + a1*x + a2*x**2 + noise\nplt.scatter(x,y,alpha=0.5,lw=0);\nplt.show()\n```\n\nConstruct the matrix $X$:\n\n\n```python\nX = np.column_stack([np.ones(N),x,x**2])\n```\n\nUse `scipy.linalg.solve` to solve $\\left( X^T X \\right) \\mathbf{a} = \\left( X^T \\right) \\mathbf{y}$:\n\n\n```python\na = la.solve((X.T @ X),X.T @ y)\n```\n\nPlot the result:\n\n\n```python\nxs = np.linspace(-1,1,20)\nys = a[0] + a[1]*xs + a[2]*xs**2\nplt.plot(xs,ys,'r',linewidth=4)\nplt.scatter(x,y,alpha=0.5,lw=0)\nplt.show()\n```\n\n## Graph Theory\n\nA [graph](https://en.wikipedia.org/wiki/Graph_%28discrete_mathematics%29) is a set of vertices and a set of edges connecting some of the vertices. We will consider simple, undirected, connected graphs:\n\n* a graph is [simple](https://en.wikipedia.org/wiki/Graph_%28discrete_mathematics%29#Simple_graph) if there are no loops or multiple edges between vertices\n* a graph is [undirected](https://en.wikipedia.org/wiki/Graph_%28discrete_mathematics%29#Undirected_graph) if the edges do not have an orientation\n* a graph is [connected](https://en.wikipedia.org/wiki/Graph_%28discrete_mathematics%29#Connected_graph) if each vertex is connected to every other vertex in the graph by a path\n\nWe can visualize a graph as a set of vertices and edges and answer questions about the graph just by looking at it. However this becomes much more difficult with a large graphs such as a [social network graph](https://en.wikipedia.org/wiki/Social_network_analysis). Instead, we construct matrices from the graph such as the [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix) and the [Laplacian matrix](https://en.wikipedia.org/wiki/Laplacian_matrix) and study their properties.\n\n[Spectral graph theory](https://en.wikipedia.org/wiki/Spectral_graph_theory) is the study of the eigenvalues of the adjacency matrix (and other associated matrices) and the relationships to the structure of $G$.\n\n### NetworkX\n\nLet's use the Python package [NetworkX](https://networkx.github.io/) to construct and visualize some simple graphs.\n\n\n```python\nimport networkx as nx\n```\n\n### Adjacency Matrix\n\nThe [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix) $A_G$ of a graph $G$ with $n$ vertices is the square matrix of size $n$ such that $A_{i,j} = 1$ if vertices $i$ and $j$ are connected by an edge, and $A_{i,j} = 0$ otherwise.\n\nWe can use `networkx` to create the adjacency matrix of a graph $G$. The function `nx.adjacency_matrix` returns a [sparse matrix](https://docs.scipy.org/doc/scipy/reference/sparse.html) and we convert it to a regular NumPy array using the `todense` method.\n\nFor example, plot the [complete graph](https://en.wikipedia.org/wiki/Complete_graph) with 5 vertices and compute the adjacency matrix:\n\n\n```python\nG = nx.complete_graph(5)\nnx.draw(G,with_labels=True)\n```\n\n\n```python\nA = nx.adjacency_matrix(G).todense()\nprint(A)\n```\n\n [[0 1 1 1 1]\n [1 0 1 1 1]\n [1 1 0 1 1]\n [1 1 1 0 1]\n [1 1 1 1 0]]\n\n\n### Length of the Shortest Path\n\nThe length of the [shortest path](https://en.wikipedia.org/wiki/Shortest_path_problem) between vertices in a simple, undirected graph $G$ can be easily computed from the adjacency matrix $A_G$. In particular, the length of shortest path from vertex $i$ to vertex $j$ ($i\\not=j$) is the smallest positive integer $k$ such that $A^k_{i,j} \\not= 0$.\n\nPlot the [dodecahedral graph](https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph):\n\n\n```python\nG = nx.dodecahedral_graph()\nnx.draw(G,with_labels=True)\n```\n\n\n```python\nA = nx.adjacency_matrix(G).todense()\nprint(A)\n```\n\n [[0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1]\n [1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]\n [0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]\n [0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0]\n [0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0]\n [0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0]\n [0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 0]\n [1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0]\n [0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0]\n [0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0]\n [0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0]\n [0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0]\n [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0]\n [0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1]\n [1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0]]\n\n\nWith this labelling, let's find the length of the shortest path from vertex $0$ to $15$:\n\n\n```python\ni = 0\nj = 15\nk = 1\nAk = A\nwhile Ak[i,j] == 0:\n Ak = Ak @ A\n k = k + 1\nprint('Length of the shortest path is',k)\n```\n\n Length of the shortest path is 5\n\n\n### Triangles in a Graph\n\nA simple result in spectral graph theory is the number of [triangles](https://en.wikipedia.org/wiki/Adjacency_matrix#Matrix_powers) in a graph $T(G)$ is given by:\n\n$$\nT(G) = \\frac{1}{6} ( \\lambda_1^3 + \\lambda_2^3 + \\cdots + \\lambda_n^3)\n$$\n\nwhere $\\lambda_1 \\leq \\lambda_2 \\leq \\cdots \\leq \\lambda_n$ are the eigenvalues of the adjacency matrix.\n\nLet's verify this for the simplest case, the complete graph on 3 vertices:\n\n\n```python\nC3 = nx.complete_graph(3)\nnx.draw(C3,with_labels=True)\n```\n\n\n```python\nA3 = nx.adjacency_matrix(C3).todense()\neigvals, eigvecs = la.eig(A3)\nint(np.round(np.sum(eigvals.real**3)/6,0))\n```\n\n\n\n\n 1\n\n\n\nLet's compute the number of triangles in the complete graph 7 vertices:\n\n\n```python\nC7 = nx.complete_graph(7)\nnx.draw(C7,with_labels=True)\n```\n\n\n```python\nA7 = nx.adjacency_matrix(C7).todense()\neigvals, eigvecs = la.eig(A7)\nint(np.round(np.sum(eigvals.real**3)/6,0))\n```\n\n\n\n\n 35\n\n\n\nThere are 35 triangles in the complete graph with 7 vertices!\n\nLet's write a function called `triangles` which takes a square matrix `M` and return the sum\n\n$$\n\\frac{1}{6} ( \\lambda_1^3 + \\lambda_2^3 + \\cdots + \\lambda_n^3)\n$$\n\nwhere $\\lambda_i$ are the eigenvalues of the symmetric matrix $A = (M + M^T)/2$. Note that $M = A$ if $M$ is symmetric. The return value is the number of triangles in the graph $G$ if the input $M$ is the adjacency matrix.\n\n\n```python\ndef triangles(M):\n A = (M + M.T)/2\n eigvals, eigvecs = la.eig(A)\n eigvals = eigvals.real\n return int(np.round(np.sum(eigvals**3)/6,0))\n```\n\nNext, let's try a [Turan graph](https://en.wikipedia.org/wiki/Tur%C3%A1n_graph).\n\n\n```python\nG = nx.turan_graph(10,5)\nnx.draw(G,with_labels=True)\n```\n\n\n```python\nA = nx.adjacency_matrix(G).todense()\nprint(A)\n```\n\n [[0 0 1 1 1 1 1 1 1 1]\n [0 0 1 1 1 1 1 1 1 1]\n [1 1 0 0 1 1 1 1 1 1]\n [1 1 0 0 1 1 1 1 1 1]\n [1 1 1 1 0 0 1 1 1 1]\n [1 1 1 1 0 0 1 1 1 1]\n [1 1 1 1 1 1 0 0 1 1]\n [1 1 1 1 1 1 0 0 1 1]\n [1 1 1 1 1 1 1 1 0 0]\n [1 1 1 1 1 1 1 1 0 0]]\n\n\nFind the number of triangles:\n\n\n```python\ntriangles(A)\n```\n\n\n\n\n 80\n\n\n\nFinally, let's compute the number of triangles in the dodecahedral graph:\n\n\n```python\nG = nx.dodecahedral_graph()\nnx.draw(G,with_labels=True)\n```\n\n\n```python\nA = nx.adjacency_matrix(G).todense()\nprint(A)\n```\n\n [[0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1]\n [1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]\n [0 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]\n [0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0]\n [0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0]\n [0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0]\n [0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 0 0]\n [1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0]\n [0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0]\n [0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0]\n [0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0]\n [0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0]\n [0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 0 0]\n [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0]\n [0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1]\n [1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0]]\n\n\n\n```python\nnp.round(triangles(A),2)\n```\n\n\n\n\n 0\n\n\n", "meta": {"hexsha": "19ac5b66b4d4f688081094b56a8694591f5d40e1", "size": 498807, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Python/3. Computational Sciences and Mathematics/Linear Algebra/Various Applications -- Polynomial Interpolation, Least Squares Linear Regression, Polynomial Regression, Graph Theory, Network Visualizations with NetworkX.ipynb", "max_stars_repo_name": "okara83/Becoming-a-Data-Scientist", "max_stars_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Python/3. Computational Sciences and Mathematics/Linear Algebra/Various Applications -- Polynomial Interpolation, Least Squares Linear Regression, Polynomial Regression, Graph Theory, Network Visualizations with NetworkX.ipynb", "max_issues_repo_name": "okara83/Becoming-a-Data-Scientist", "max_issues_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Python/3. Computational Sciences and Mathematics/Linear Algebra/Various Applications -- Polynomial Interpolation, Least Squares Linear Regression, Polynomial Regression, Graph Theory, Network Visualizations with NetworkX.ipynb", "max_forks_repo_name": "okara83/Becoming-a-Data-Scientist", "max_forks_repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2022-02-09T15:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T07:47:40.000Z", "avg_line_length": 315.7006329114, "max_line_length": 77760, "alphanum_fraction": 0.9309652832, "converted": true, "num_tokens": 8124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9740426450627306, "lm_q2_score": 0.9343951625409307, "lm_q1q2_score": 0.9101407356551883}}
{"text": "# Aula 3\n## Ferramentas básicas de cálculo\nA biblioteca Sympy disponibiliza algumas ferramentas para cálculo integral e diferencial, dentre outras.\n\n\n```python\nfrom sympy import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\nA linha abaixo realiza modificações para que as expressões matemáticas fiquem em formato legível\n\n\n```python\ninit_printing(use_unicode=False, \n wrap_line=False, no_global=True) # Faz com que as expressoes sejam exibidas e formato legivel\n```\n\nÉ necessário também declarar símbolos e constatens que serão utilizados.\n\n\n```python\nx, y, z, t, theta = symbols('x y z t theta') # Declaracao de variaveis\nk1, k2, m, n, a = symbols('k1 k2 m n a', integer=True) # Declaracao de constantes\n```\n\nPara realizar uma integral indefinida utiliza-se a função integrate(formula, variavel de integracao)\n\n\n```python\nintegrate(x**2,x)\n```\n\nNo caso de integral definida, deve ser passado uma tupla no formato (variavel de integracao, lim. inferior, lim. superior)\n\n\n```python\nintegrate(x**2,(x,-1, 1))\n```\n\nIntegrais multivariadas funcionam de maneira similar:\n\n\n```python\nintegrate(x*y, (x,-7,3),(y,-13,5))\n```\n\nÉ possível também definir funções como variáveis, desde que o parâmetro passado seja um símbolo definido anteriormente.\n\n\n```python\nf = x**3+x**2+x+5\nf\n```\n\nÉ possível integrar,diferenciar ou simplesmente avaliar a expressão criada:\n\n\n```python\nintegrate(f, (x,-10,10)) # Integracao\n\n```\n\n\n```python\nf.diff(x) # Diferenciacao\n```\n\n\n```python\nf.subs(x,1) # Avaliacao da expressao em x=1\n```\n\nFunções trigonométricas também são válidas\n\n\n```python\nh = cos(theta)\nh.subs(theta, pi)\n```\n\n## Exercício 1: Calcule a Série de Taylor para a expressão $cos(\\theta)$ com três termos em torno de um ponto $a$ arbitrário:\n\n\n```python\n\n```\n\n## Exercício 2: Plote a fução de erro para a aproximação por Série de Taylor no intervalo entre -pi e pi:\n\nDica: você pode usar uma estratégia similar a utilizada na Aula 1 para plotar o gráfico de Força vs Distância.\n\n\n```python\n\n```\n\n## Exercício 3: Crie uma função que receba uma expressão e um número inteiro $n$ e que calcule os $n$ primeiros elementos da Série de Taylor para aquela expressão em torno do ponto $a$ e retorne a expressão completa:\n\n\n```python\ndef CalcularTaylor(expr, n, a):\n ## complete a funcao\n```\n\n### Material de consulta\nhttps://en.wikipedia.org/wiki/Taylor_series - teoria de Série de Taylor\n\nhttps://www.youtube.com/watch?v=3d6DsjIBzJ4 - vídeo explicativo\n\nhttp://docs.sympy.org/latest/index.html - documentação da biblioteca sympy\n", "meta": {"hexsha": "fdd1332663071b70b5e8567c5963da8742483362", "size": 14378, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Aula3.ipynb", "max_stars_repo_name": "hudsonmiranda291/eletropythonufmg", "max_stars_repo_head_hexsha": "6eb254a23ef3918547d6da82db10231bd9c9c154", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Aula3.ipynb", "max_issues_repo_name": "hudsonmiranda291/eletropythonufmg", "max_issues_repo_head_hexsha": "6eb254a23ef3918547d6da82db10231bd9c9c154", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Aula3.ipynb", "max_forks_repo_name": "hudsonmiranda291/eletropythonufmg", "max_forks_repo_head_hexsha": "6eb254a23ef3918547d6da82db10231bd9c9c154", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6785714286, "max_line_length": 1312, "alphanum_fraction": 0.7080261511, "converted": true, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109728022221, "lm_q2_score": 0.9572778055005742, "lm_q1q2_score": 0.9098073303677771}}
{"text": "```python\nfrom scipy import linalg as la\nfrom scipy import optimize\n\nimport sympy\nsympy.init_printing()\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n```\n\n\n```python\n# Graphical solution\n\nx = np.arange(-4, 2, 1)\nx2 = np.arange(-2, 6, 1)\n\ny1 = (4 - 2*x) / 3\ny2 = (3 - 5*x) / 4\n\nfig, ax = plt.subplots(figsize=(10, 5))\n\nax.set_xlabel(\"${x_1}$\")\nax.set_ylabel(\"${x_2}$\")\n\nax.plot(x, y2, 'r', label=\"$2{x_1}+3{x_2}-4=0$\")\nax.plot(x, y1, 'b', label=\"$5{x_1}+4{x_2}-3=0$\")\n\nax.plot(-1, 2, 'black', lw=5, marker='o')\n\nax.annotate(\"The intersection point\\nof the two lines is the solution\\nto the system of equations\", fontsize=14, family=\"serif\", xy=(-1, 2),\n xycoords=\"data\", xytext=(-150, -80),\n textcoords=\"offset points\", arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3, rad=-.5\"))\n\nax.set_xticks(x)\nax.set_yticks(x2)\n\nax.legend()\n```\n\n### Squared system\n\n\n```python\nA = sympy.Matrix([[2, 3], [5, 4]])\nb = sympy.Matrix([4, 3])\n\nA.rank()\n```\n\n\n```python\nA.condition_number()\n```\n\n\n```python\nsympy.N(_)\n```\n\n\n```python\nA.norm()\n```\n\n\n```python\nA = np.array([[2, 3], [5, 4]])\nb = np.array([4, 3])\n```\n\n\n```python\nnp.linalg.matrix_rank(A)\n```\n\n\n\n\n 2\n\n\n\n\n```python\nnp.linalg.cond(A)\n```\n\n\n```python\nnp.linalg.norm(A)\n```\n\n\n```python\n# LU factorization\n\nA = sympy.Matrix([[2, 3], [5, 4]])\nb = sympy.Matrix([4, 3])\n\nL, U, _ = A.LUdecomposition()\nL\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 0\\\\\\frac{5}{2} & 1\\end{matrix}\\right]$\n\n\n\n\n```python\nU\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}2 & 3\\\\0 & - \\frac{7}{2}\\end{matrix}\\right]$\n\n\n\n\n```python\nL * U == A\n```\n\n\n\n\n True\n\n\n\n\n```python\nx = A.solve(b)\nx\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}-1\\\\2\\end{matrix}\\right]$\n\n\n\n\n```python\nA = np.array([[2, 3], [5, 4]])\nb = np.array([4, 3])\nP, L, U = la.lu(A)\nL\n```\n\n\n\n\n array([[1. , 0. ],\n [0.4, 1. ]])\n\n\n\n\n```python\nP.dot(L.dot(U))\n```\n\n\n\n\n array([[2., 3.],\n [5., 4.]])\n\n\n\n\n```python\nla.solve(A, b)\n```\n\n\n\n\n array([-1., 2.])\n\n\n\n\n```python\n# Symbolic vs Numerical\np = sympy.symbols(\"p\", positive=True)\nA = sympy.Matrix([[1, sympy.sqrt(p)], [1, 1/sympy.sqrt(p)]])\nb = sympy.Matrix([1, 2])\nx = A.solve(b)\nx\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{2 p - 1}{p - 1}\\\\\\frac{1}{- \\sqrt{p} + \\frac{1}{\\sqrt{p}}}\\end{matrix}\\right]$\n\n\n\n\n```python\n#Symbolic problem specification\np = sympy.symbols(\"p\", positive=True)\nA = sympy.Matrix([[1, sympy.sqrt(p)], [1, 1/sympy.sqrt(p)]])\nb = sympy.Matrix([1, 2])\n\n# Solve symbolically\nx_sym_sol = A.solve(b)\nAcond = A.condition_number().simplify()\n\n# Numerical problem specification\nAA = lambda p: np.array([[1, np.sqrt(p)], [1, 1/np.sqrt(p)]])\nbb = np.array([1, 2])\nx_num_sol = lambda p: np.linalg.solve(AA(p), bb)\n\n# Graph the difference between the symbolic (exact) and numerical results.\nfig, axes = plt.subplots(1, 2, figsize=(12, 4))\n\np_vec = np.linspace(0.9, 1.1, 200)\n\nfor n in range(2):\n x_sym = np.array([x_sym_sol[n].subs(p, pp).evalf() for pp in p_vec])\n x_num = np.array([x_num_sol(pp)[n] for pp in p_vec])\n\naxes[0].plot(p_vec, (x_num - x_sym)/x_sym, 'k')\naxes[0].set_title(\"Error in solution\\n(numerical - symbolic)/symbolic\")\naxes[0].set_xlabel(r'$p$', fontsize=18)\n\naxes[1].plot(p_vec, [Acond.subs(p, pp).evalf() for pp in p_vec])\naxes[1].set_title(\"Condition number\")\naxes[1].set_xlabel(r'$p$', fontsize=18)\n\n```\n\n### Rectangular system\n\n\n\n```python\nx_vars = sympy.symbols(\"x_1, x_2, x_3\")\n\nA = sympy.Matrix([[1, 2, 3], [4, 5, 6]])\nx = sympy.Matrix(x_vars)\nb = sympy.Matrix([7, 8])\n\nsympy.solve(A*x - b, x_vars)\n```\n\n### Least squares\n\n\n```python\n# define true model parameters\n\nx = np.linspace(-1, 1, 100)\na, b, c = 1, 2, 3\ny_exact = a + b * x + c * x**2\n\n# Simulate noisy data\nm = 100\nX = 1 - 2 * np.random.rand(m)\n\nY = a + b * X + c * X**2 + np.random.randn(m)\n# fit the data to the model using linear least square\nA = np.vstack([X**0, X**1, X**2]) # see np.vander for alternative\n```\n\n\n```python\nsol, r, rank, sv = la.lstsq(A.T, Y)\n\ny_fit = sol[0] + sol[1] * x + sol[2] * x**2\n\nfig, ax = plt.subplots(figsize=(12, 4))\n\nax.plot(X, Y, 'go', alpha=0.5, label='Simulated data')\nax.plot(x, y_exact, 'k', lw=2, label='True value $y = 1 + 2x + 3x^2$')\nax.plot(x, y_fit, 'b', lw=2, label='Least square fit')\n\nax.set_xlabel(r\"$x$\", fontsize=18)\nax.set_ylabel(r\"$y$\", fontsize=18)\nax.legend(loc=2)\n```\n\n\n```python\n# fit the data to the model using linear least square:\n# 1st order polynomial\nA = np.vstack([X**n for n in range(2)])\nsol, r, rank, sv = la.lstsq(A.T, Y)\n\ny_fit1 = sum([s * x**n for n, s in enumerate(sol)])\n```\n\n\n```python\n# 15th order polynomial\nA = np.vstack([X**n for n in range(16)])\n\nsol, r, rank, sv = la.lstsq(A.T, Y)\n\ny_fit15 = sum([s * x**n for n, s in enumerate(sol)])\n\nfig, ax = plt.subplots(figsize=(12, 4))\n\nax.plot(X, Y, 'go', alpha=0.5, label='Simulated data')\n\nax.plot(x, y_exact, 'k', lw=2, label='True value $y = 1 + 2x +3x^2$')\n\nax.plot(x, y_fit1, 'b', lw=2, label='Least square fit [1st order]')\n\nax.plot(x, y_fit15, 'm', lw=2, label='Least square fit [15th order]')\n\nax.set_xlabel(r\"$x$\", fontsize=18)\nax.set_ylabel(r\"$y$\", fontsize=18)\n\nax.legend(loc=2)\n\n```\n\n### Eigenvalues / Eigenvectors\n\n\n```python\neps, delta = sympy.symbols(\"epsilon, Delta\")\nH = sympy.Matrix([[eps, delta], [delta, -eps]])\nH\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\epsilon & \\Delta\\\\\\Delta & - \\epsilon\\end{matrix}\\right]$\n\n\n\n\n```python\nH.eigenvals()\n```\n\n\n```python\nH.eigenvects()\n```\n\n\n\n\n$\\displaystyle \\left[ \\left( - \\sqrt{\\Delta^{2} + \\epsilon^{2}}, \\ 1, \\ \\left[ \\left[\\begin{matrix}- \\frac{\\Delta}{\\epsilon + \\sqrt{\\Delta^{2} + \\epsilon^{2}}}\\\\1\\end{matrix}\\right]\\right]\\right), \\ \\left( \\sqrt{\\Delta^{2} + \\epsilon^{2}}, \\ 1, \\ \\left[ \\left[\\begin{matrix}- \\frac{\\Delta}{\\epsilon - \\sqrt{\\Delta^{2} + \\epsilon^{2}}}\\\\1\\end{matrix}\\right]\\right]\\right)\\right]$\n\n\n\n\n```python\n(eval1, _, evec1), (eval2, _, evec2) = H.eigenvects()\n\n# Orthogonality\nsympy.simplify(evec1[0].T * evec2[0])\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}0\\end{matrix}\\right]$\n\n\n\n\n```python\nA = np.array([[1, 3, 5], [3, 5, 3], [5, 3, 9]])\nevals, evecs = la.eig(A)\n\nevals\n```\n\n\n\n\n array([13.35310908+0.j, -1.75902942+0.j, 3.40592034+0.j])\n\n\n\n\n```python\nevecs\n```\n\n\n\n\n array([[ 0.42663918, 0.90353276, -0.04009445],\n [ 0.43751227, -0.24498225, -0.8651975 ],\n [ 0.79155671, -0.35158534, 0.49982569]])\n\n\n\n\n```python\nla.eigvalsh(A)\n```\n\n\n\n\n array([-1.75902942, 3.40592034, 13.35310908])\n\n\n\n### Nonlinear equations\n\n\n```python\nx, a, b, c = sympy.symbols(\"x, a, b, c\")\nsympy.solve(a + b*x + c*x**2, x)\n```\n\n\n```python\nsympy.solve(a * sympy.cos(x) - b * sympy.sin(x), x)\n```\n\n\n```python\nx = np.linspace(-2, 2, 1000)\n# four examples of nonlinear functions\n\nf1 = x**2 - x - 1\nf2 = x**3 - 3 * np.sin(x)\nf3 = np.exp(x) - 2\nf4 = 1 - x**2 + np.sin(50 / (1 + x**2))\n\n# plot each function\nfig, axes = plt.subplots(1, 4, figsize=(12, 3), sharey=True)\n\nfor n, f in enumerate([f1, f2, f3, f4]):\n axes[n].plot(x, f, lw=1.5)\n axes[n].axhline(0, ls=':', color='k')\n axes[n].set_ylim(-5, 5)\n axes[n].set_xticks([-2, -1, 0, 1, 2])\n axes[n].set_xlabel(r'$x$', fontsize=18)\n\naxes[0].set_ylabel(r'$f(x)$', fontsize=18)\n\ntitles = [\n r'$f(x)=x^2-x-1$',\n r'$f(x)=x^3-3\\sin(x)$',\n r'$f(x)=\\exp(x)-2$',\n r'$f(x)=\\sin\\left(50/(1+x^2)\\right)+1-x^2$'\n]\n\nfor n, title in enumerate(titles):\n axes[n].set_title(title)\n\n```\n", "meta": {"hexsha": "92d4e4f0ef8cf72a53270c688c2146d6f6e720ae", "size": 468510, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "NumericalPython/4.EquationSolving.ipynb", "max_stars_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_stars_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:00:11.000Z", "max_issues_repo_path": "NumericalPython/4.EquationSolving.ipynb", "max_issues_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_issues_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NumericalPython/4.EquationSolving.ipynb", "max_forks_repo_name": "nickovchinnikov/Computational-Science-and-Engineering", "max_forks_repo_head_hexsha": "45620e432c97fce68a24e2ade9210d30b341d2e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:21:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:21:40.000Z", "avg_line_length": 473.2424242424, "max_line_length": 60786, "alphanum_fraction": 0.7608674308, "converted": true, "num_tokens": 2773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9532750440288019, "lm_q2_score": 0.9539660990731174, "lm_q1q2_score": 0.9093920750959104}}
{"text": "```\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sympy import *\n```\n\n## Introduction\n\nDerivatives are used whenever we need to deal with rates of change (like velocity and acceleration, biological and economic growth, heat transfer, etc.). \n\nThey are useful in processes of optimization in Operation Research and Computer Science and learning algorithms for Artificial Intelligence.\n\nIn Mathematics derivatives are widely used to locally approximate/estimate nonlinear functions (which are hard to use) with linear functions (which are easy to use). This is an important part of Calculus (eg, Taylor Series).\n\nHow programmers, namely in Python, deal with derivatives?\n\n\n## Symbolic Differentiation\n\nPython's module `sympy` includes function `Derivative` that performs symbolic differentiation, ie, it performs the algebraic manipulation and returns an expression with the derivative:\n\n\n```\nx, y = symbols('x y') \nexpr = y*x**2 + 2 * y + y**3\nprint(\"Expression : {} \".format(expr)) \n \nexpr_diff = diff(expr, x) \nprint(\"derivative : {}\".format(expr_diff)) \n\nvalue_diff = expr_diff.evalf(subs={x:1,y:4})\nprint(\"Value of derivative at (1,4): {0:3.2f}\".format(value_diff))\n```\n\n Expression : x**2*y + y**3 + 2*y \n derivative : 2*x*y\n Value of derivative at (1,4): 8.00\n\n\nWe can use it to compute a second derivative, in this case $$\\frac{\\partial^2 f}{\\partial x \\partial y}$$\n\n\n```\nsecond_diff = Derivative(expr_diff, y)\nprint(\"Value of the 2nd derivative : {} \".format(second_diff.doit())) \n```\n\n Value of the derivative : 2*x \n\n\nOne potential problem is that differential expressions can increase expontentially making them, on those cases, prohibitively slow.\n\n## Numerical Differentiation\n\nThis process uses the math formula that defines differentials\n\n$$f'(a) = \\lim_{h \\rightarrow 0} \\frac{f(a+h) - f(a)}{h}$$\n\nThere is more than one expression to approximate this value. Here is the _central difference_ formula:\n\n$$f'(a) \\approx \\frac{1}{2} \\left( \\frac{f(a + h) - f(a)}{h} + \\frac{f(a) - f(a - h)}{h} \\right) = \\frac{f(a + h) - f(a - h)}{2h}$$\n\nWe can implement this easily on Python:\n\n\n```\ndef derivative(f, a, h=1e-7):\n return (f(a + h) - f(a - h))/(2*h)\n```\n\nWhat is the derivative of $f(x) = x^2 + 5$ at $x=2.5$? We know by the definition that $f'(x) = 2x$ so the result should be $5$.\n\nLet's check the approximation:\n\n\n```\ndef f(x):\n return x**2 + 5\n\nprint(derivative(f, 2.5)) \n```\n\n 4.9999999873762135\n\n\nModule `scipy` has a function that does this for us:\n\n\n```\nimport scipy.misc as spm\n\nspm.derivative(f, 2.5, dx=1e-3)\n```\n\n\n\n\n 4.999999999999893\n\n\n\nAnd what about numerical differentiation on second order derivatives?\n\nCan we compute, say, $\\frac{\\partial^2 f}{\\partial x \\partial y}$ numerically?\n\nFor second derivative over the same variable, there are again several approximations. This is one:\n\n$$\\frac{\\partial^2 f}{\\partial x^2}(a,b) \\approx \\frac{-f(a-h,b) + 2f(a,b)-f(a+h,b)}{h^2}$$\n\nFor mixed variables we can use the next formula [[ref](https://www.uio.no/studier/emner/matnat/math/MAT-INF1100/h07/undervisningsmateriale/kap7.pdf)]\n\n$$\\frac{\\partial^2 f}{\\partial x \\partial y}(a,b) \\approx \\frac{f(a+h_1,b+h_2) - f(a+h_1,b-h_2) - f(a-h_1,b+h_2) + f(a-h_1,b-h_2)}{4h_1 h_2}$$\n\nModule `numdifftools` solves automatic numerical differentiation problems in one or more variables. [website](https://pypi.org/project/numdifftools/)\n\n### Example: Taylor Expansion\n\nDerivatives are essential to compute the Taylor expansion of functions. [[ref](https://www.math.ubc.ca/~pwalls/math-python/differentiation/differentiation/)]\n\nThe Taylor expansion is the infinite series\n\n$$f(x) \\approx f(a) + f^{'}(a)(x - a) + \\frac{1}{2!} f^{''}(a) (x - a)^{2} + \\frac{1}{3!} f^{(3)}(a) (x - a)^{3} \\ldots$$\n\nLet's say we wish the approximate function\n\n$$f(x) = \\frac{3e^x}{x^2 + x + 1}$$\n\naround $x=1$\n\n\n\n```\nxs = np.linspace(-4,4,100)\nf = lambda x : 3*np.exp(x) / (x**2 + x + 1)\n\nfig, ax = plt.subplots(figsize=(10, 4))\nax.plot(xs, f(xs));\n```\n\nThe Taylor expansion needs the coefficients $$a_n = \\frac{1}{n!} f^{(n)}(1)$$ \n\nLet's make the approximation of degree 3\n\n\n```\nx = 1\n\na0 = f(x)\na1 = spm.derivative(f, x, dx=1e-3, n=1)\na2 = spm.derivative(f, x, dx=1e-3, n=2) / 2\na3 = spm.derivative(f, x, dx=1e-3, n=3, order=5) / 6\n```\n\nWith the coefficients, we can plot the approximation:\n\n\n```\ntaylor3 = a0 + a1*(xs-x) + a2*(xs-x)**2 + a3*(xs-x)**3\n\nfig, ax = plt.subplots(figsize=(10, 4))\nplt.xlim([-4,4])\nplt.ylim([0,8])\nax.plot(xs,ys, xs,taylor3);\n```\n\nWhat happened is that, around $x=1$, we can use a much simpler function (a polinomial of degree 3) instead of the original function (which includes exponentiation and division by a quadratic polynomial). We can zoom around $x=1$ to check how good this approximation is: \n\n\n```\nfig, ax = plt.subplots(figsize=(10, 4))\nax.plot(xs,ys, xs,taylor3), plt.xlim([0.5,1.5]), plt.ylim([2.7,2.85]);\n```\n\n## Automatic Differentiation\n\nAutomatic differentiation (autodiff) is a tecnique capable of giving an exact answer to differential values in constant time.\n\n### Dual Numbers\n\nDual numbers have form $a + b \\epsilon$, where $\\epsilon^2=0$.\n\nWe can compute the value of arithmetic expressions over dual numbers.\n\nEg: \n\n* $(a+b\\epsilon) + (c+d\\epsilon) = (a+c) + (b+d) \\epsilon$\n\n* $(a+b\\epsilon) \\times (c+d\\epsilon) = ac + (ad+bc) \\epsilon$\n\nNow consider the Taylor Expansion of a function $f(a)$ at value $a+\\epsilon$:\n\n$$f(a+\\epsilon) = f(a) + \\frac{f'(a)}{1!} \\epsilon + \\frac{f''(a)}{2!}\\epsilon^2 + \\ldots$$\n\nbut all $\\epsilon^n$, with $n>1$, will be zero, so:\n\n$$f(a+\\epsilon) = f(a) + f'(a) \\epsilon$$\n\nThis is an exact solution, not an approximation (!!)\n\nLet's check an example, $f(x) = x^2+1$:\n\n$f(x+\\epsilon) = (x+\\epsilon)^2 + 1 = x^2 + \\epsilon^2 + 2x\\epsilon + 1 = x^2 + 1 + 2x\\epsilon$\n\nThis means that $2x$ is the derivative of $x^2+1$\n\nHowever, for more complex expressions there is a more efficient algorithm.\n\n### Reverse Mode Differentiation\n\nThe Jacobian Matrix is a matrix that takes the partial derivatives of each element of a function $f : \\mathbb{R}^n \\rightarrow \\mathbb{R}^m$\n\n$$J_f=\\begin{bmatrix} \n\\frac{\\partial y_1}{\\partial x_1} & \\ldots & \\frac{\\partial y_1}{\\partial x_n} \\\\ \n\\vdots & \\ddots & \\vdots \\\\\n\\frac{\\partial y_m}{\\partial x_1} & \\ldots & \\frac{\\partial y_m}{\\partial x_n} \n\\end{bmatrix}$$\n\nwhere $x_i$ is the i-th input and $y_j$ the j-th output.\n\nAn example with `sympy`:\n\n\n```\nfrom IPython.display import display, Math, Latex\nfrom ipywidgets import interact, widgets\nfrom sympy import sin, cos, Matrix, latex\nfrom sympy.abc import rho, phi\n\nX = Matrix([rho*cos(phi), rho*sin(phi), rho**2])\nY = Matrix([rho, phi])\n\ndisplay(Math('\\\\text{The Jacobian of } f(\\\\rho,\\\\phi) = ' + latex(X) \n + '\\\\text{ is }' + latex(X.jacobian(Y)) ))\n```\n\n\n$$\\text{The Jacobian of } f(\\rho,\\phi) = \\left[\\begin{matrix}\\rho \\cos{\\left (\\phi \\right )}\\\\\\rho \\sin{\\left (\\phi \\right )}\\\\\\rho^{2}\\end{matrix}\\right]\\text{ is }\\left[\\begin{matrix}\\cos{\\left (\\phi \\right )} & - \\rho \\sin{\\left (\\phi \\right )}\\\\\\sin{\\left (\\phi \\right )} & \\rho \\cos{\\left (\\phi \\right )}\\\\2 \\rho & 0\\end{matrix}\\right]$$\n\n\nLet's apply autodiff to compute the Jacobian of a vector valued function using a technique denoted **reverse mode differentiation**.\n\nOur example function will be $f(x_1, x_2) = x_1x_2 - \\sin(x_2)$. \n\nWe would like to evaluate $f^´(2,3)$.\n\nFirst we need the respective [computational graph](https://medium.com/tebs-lab/deep-neural-networks-as-computational-graphs-867fcaa56c9):\n\n\n\n\nThen we compute the *primal trace*, which is the set of intermediate values at each node:\n\n$$\\begin{array}{ccccc}\nv_1 &=& x_1 &=& 2 \\\\\nv_2 &=& x_2 &=&3 \\\\\nv_3 &=& v_1 \\times v_2 &=& 6 \\\\\nv_4 &=& \\sin v_2 &\\approx& 0.14 \\\\\nv_5 &=& v_3 - v_4 &\\approx& 5.86 \\\\\ny &=& v_5 &\\approx& 5.86\n\\end{array}$$\n\nSince each node corresponds to a single operation, all derivatives are easily known.\n\nThe next step is to compute the dual trace.\n\nThe *dual trace* measures how much each intermediate node varies with respect to the input\n\n$$\\frac{\\partial v_i}{\\partial x}$$\n\nTo compute the dual trace we need to apply the chain rule:\n\n> The chain rule is a technique to break apart a derivative we don’t know how to solve into derivatives that we do know how to solve.\n\nHerein, \n\n$$\\frac{\\partial y_j}{\\partial v_i} = \\frac{\\partial y_j}{\\partial v_k} \\frac{\\partial v_k}{\\partial v_i}$$\n\nwhere $v_k$ is the parent of $v_i$ in the computational graph. If $v_i$ has more than one parent, we sum all contributions,\n\n$$\\frac{\\partial y_j}{\\partial v_i} = \\sum_{p \\in \\text{parents}(i)} \\frac{\\partial y_j}{\\partial v_p} \\frac{\\partial v_p}{\\partial v_i}$$\n\nThis expression is called the *adjoint* of $v_i$ and denoted as $\\overline{v_i}$.\n\nIt's possible to define the adjoint of a node in terms of the adjoints of its parents (eg: $v_3$ is parent of $v_1$ and $v_2$)\n\n$$\\overline{v_i} = \\sum_p \\overline{v_p}\\frac{\\partial v_p}{\\partial v_i}$$\n\nwhich give us a recursive algorithm. [ref](https://stats.stackexchange.com/questions/224140/step-by-step-example-of-reverse-mode-automatic-differentiation)\n\nThe dual trace starts at the end, at node $y$, and propagates backwards to its dependencies.\n\nSo the seed is $\\frac{\\partial y}{\\partial y} = 1$ which means a change in $y$ results in exactly the same change in $y$ (duh!).\n\nSince $y = v_5$, \n\n$$\\overline{v_5} = \\overline{y} \\times \\frac{\\partial y}{\\partial v_5} = 1 \\times 1 = 1$$\n\nSince $v_5 = v_3 - v_4$,\n\n$$\\overline{v_3} = \\overline{v_5} \\times \\frac{\\partial v_5}{\\partial v_3} = 1 \\times 1 = 1$$\n\n$$\\overline{v_4} = \\overline{v_4} \\times \\frac{\\partial v_5}{\\partial v_4} = 1 \\times -1 = -1$$\n\nSince $v_3 = v_1 \\times v_2$ and $v_4 = \\sin v_2$, $v_2$ has parents $v_3$ and $v_4$,\n\n$$\\overline{v_2} = \\overline{v_3} \\times \\frac{\\partial v_3}{\\partial v_2} + \\overline{v_4} \\times \\frac{\\partial v_4}{\\partial v_2} = 1 \\times v_1 - \\cos v_2 = v_1 - \\cos v_2$$\n\nNotice that we already know the values of $v_1$ and $v_2$ from the primal trace,\n\n$$\\overline{v_2} = 2 - \\cos(3) \\approx 2.99$$\n\nFor $v_1$ its only parent is $v_3$,\n\n$$\\overline{v_1} = \\overline{v_3} \\times \\frac{\\partial v_3}{\\partial v_1} = 1 \\times v_2 = v_2 = 3$$\n\nAnd the dual trace is done.\n\nWe wish to evaluate $f^´(2,3)$, ie, \n\n$$\\frac{\\partial y}{\\partial x_1}, \\frac{\\partial y}{\\partial x_2}$$\n\nthese values are given by $\\overline{v_1}$ and $\\overline{v_2}$, that is, \n\n$$\\frac{\\partial y}{\\partial x_1} = 3, \\frac{\\partial y}{\\partial x_2} \\approx 2.99$$\n\nJust to check the result against `sympy`:\n\n\n```\nfrom sympy import symbols\nx1, x2 = symbols('x1 x2')\n\nf = x1*x2 - sin(x2)\nX = Matrix([f])\nY = Matrix([x1, x2])\njacobian = X.jacobian(Y)\n\ndisplay(Math('\\\\text{The Jacobian of } f(x_1,x_2) = ' + latex(f) \n + '\\\\text{ is }' + latex(jacobian) ))\n\ndiffValue = jacobian.evalf(subs={x1:2, x2:3})\n\nprint('\\nDerivate of f at point (2,3): ', end=\" \")\nprint(np.array(diffValue).astype(np.float64).round(2))\n```\n\n\n$$\\text{The Jacobian of } f(x_1,x_2) = x_{1} x_{2} - \\sin{\\left (x_{2} \\right )}\\text{ is }\\left[\\begin{matrix}x_{2} & x_{1} - \\cos{\\left (x_{2} \\right )}\\end{matrix}\\right]$$\n\n\n \n Derivate of f at point (2,3): [[3. 2.99]]\n\n\nThe advantage of autodiff is that this process can be automated, while *keeping the complexity proportional to the number of nodes*.\n\nOf course, there are modules that perform autodiff:\n\n\n```\nfrom autograd import grad\nimport autograd.numpy as np\n\nhelp(grad)\n```\n\n Help on function grad in module autograd.wrap_util:\n \n grad(fun, argnum=0, *nary_op_args, **nary_op_kwargs)\n Returns a function which computes the gradient of `fun` with respect to\n positional argument number `argnum`. The returned function takes the same\n arguments as `fun`, but returns the gradient instead. The function `fun`\n should be scalar-valued. The gradient has the same type as the argument.\n \n\n\n\n```\ndef f(x1, x2):\n return x1*x2 - np.sin(x2)\n\ngradF = grad(f, [0,1])\ndiffValue = gradF(2.0,3.0)\nprint(\"Gradient of f(2,3) is\", np.array(diffValue).astype(np.float64).round(2) )\n```\n\n Gradient of f(2,3) is [3. 2.99]\n\n\nAn important point is that autodiff is able to find the derivative/gradient of a Python function even if the function includes conditionals, while loops and even recursion (!)\n\nOne immediate application for autodiff would be finding minimums of functions using [gradient descent](https://tillbe.github.io/python-gradient-descent.html).\n\nFor those readers that think this reminds you of backpropagation, the classical learning algorithm for Neural Networks, it is not a coincidence: [backpropagation is a subset of reverse mode differentiation](https://stackoverflow.com/questions/49926192).\n\n## References\n\n* Mark Saroufim, [Automatic Differentiation Step by Step](https://medium.com/@marksaroufim/automatic-differentiation-step-by-step-24240f97a6e6) (2019)\n\n* [Automatic Differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation) @ wikipedia\n\n* [Step-by-step example of reverse-mode automatic differentiation](https://stats.stackexchange.com/questions/224140) @ StackExchange\n\n* Peter Sharpe, [Autograd tutorial](https://github.com/HIPS/autograd/blob/master/docs/tutorial.md) (2019)\n\n\n", "meta": {"hexsha": "12f3aafc3d49a376176a338148baa8096ba33141", "size": 105662, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Differentiation.ipynb", "max_stars_repo_name": "jpneto/topicsInPython", "max_stars_repo_head_hexsha": "1d51a821c602aac175a8f18a8cb491a982403da2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Differentiation.ipynb", "max_issues_repo_name": "jpneto/topicsInPython", "max_issues_repo_head_hexsha": "1d51a821c602aac175a8f18a8cb491a982403da2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/Differentiation.ipynb", "max_forks_repo_name": "jpneto/topicsInPython", "max_forks_repo_head_hexsha": "1d51a821c602aac175a8f18a8cb491a982403da2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 119.122886133, "max_line_length": 24775, "alphanum_fraction": 0.836639473, "converted": true, "num_tokens": 4253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.9511422267444467, "lm_q1q2_score": 0.9092742289026811}}
{"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\nsns.set()\n```\n\n# 1. Fair coin from biased coin\n\n$P(h) = p, \\ P(t) = q = 1 - p$\n\n$P(ht) = P(th) = pq \\ \\rightarrow$ use for fair generation $\\rightarrow \\ P(\\text{dif}) = 2pq, \\ P(\\text{same}) = 1 - 2pq$\n\n$P(hh) = p^2, \\ P(tt) = q^2$\n\n**Idea:** Flip twice -> if different outcomes, report the first one, otherwise repeat.\n\n$\n\\begin{align}\n\\mathbb{E}[\\text{flips}] = e &= \\texttt{succeed_first_try} \\ \\lor \\ \\texttt{repeat} \\\\\ne &= 2 \\cdot P(\\text{dif}) + P(\\text{same}) \\cdot (2 + e) \\\\\ne &= 2 \\cdot 2pq + (1-2pq) \\cdot (2 + e) \\\\\ne (1 - 1 + 2pq) &= 4pq + 2 - 4pq \\\\\ne \\cdot 2pq &= 2 \\\\\ne &= \\frac{1}{pq} = \\frac{1}{p \\cdot (1-p)}\n\\end{align}\n$\n\n\n```python\nx = 0.05\nps = np.linspace(x, 1-x, 100)\nes = 1 / (ps * (1 - ps))\nplt.plot(ps, es)\nplt.xlabel('$p$', fontsize=14)\nplt.ylabel('expected', fontsize=14)\npass\n```\n\n# 2. `rand10` from `rand7` (1)\n\n**Idea:** call `rand7` twice -> if $x \\leq 40$, ok, otherwise repeat\n\n$\n\\begin{align}\n\\mathbb{E}[\\text{calls}] = e &= \\texttt{succeed_first_try} \\ \\lor \\ \\texttt{repeat} \\\\\ne &= 2 \\cdot P(x \\leq 40) + P(x > 40) \\cdot (2 + e)\\\\\ne &= 2 \\cdot \\frac{40}{49} + 2\\cdot\\frac{9}{49} + e \\cdot \\frac{9}{49} \\\\\ne \\cdot \\frac{40}{49} &= 2 \\\\\ne &= \\frac{49}{20} = 2.45\n\\end{align}\n$\n\n### Ref\n- https://leetcode.com/problems/implement-rand10-using-rand7/\n\n\n```python\nrand7 = lambda: np.random.randint(low=1, high=8)\n\ndef rand10():\n # idea: use [1,40], discard and repeat for [41,49]\n \n n = ((rand7() - 1) * 7) + rand7()\n \n if n <= 40:\n return 1 + n % 10\n else:\n return rand10()\n```\n\n\n```python\nxs = np.array([rand10() for _ in range(100000)])\nsupport = np.unique(xs)\nplt.figure(figsize=(8,3))\nbins = np.arange(support.max() + 2) - 0.5\nplt.hist(xs, bins=bins, rwidth=0.25, color='b', density=True)\nplt.xticks(support)\npass\n```\n\n# 3. Random points in a circle\n\n\n```python\nPI = np.arccos(-1)\nrand = lambda: np.random.uniform()\n\ndef show(gen_func, circle, N=10_000):\n xs, ys = zip(*[gen_func(circle) for _ in range(N)])\n plt.figure(figsize=(5,5))\n plt.scatter(xs, ys, s=0.2)\n plt.grid(False)\n pass\n```\n\n### 3.1. Using polar coordinates\n\n\n```python\ndef polar_coordinates(circle):\n \"\"\"\n see: https://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly\n \"\"\"\n cx, cy, r = circle\n \n l = np.sqrt(rand()) * r\n a = 2 * PI * rand()\n \n x = cx + l * np.cos(a)\n y = cy + l * np.sin(a)\n \n return x, y\n\nshow(polar_coordinates, circle=(0,0,1), N=10_000)\n```\n\n## 3.2. Using rejection sampling\n\n- Given a circle $\\mathcal{C}$ centered in $(c_x, c_y)$ of radius $r$, we can enclose it in a square $\\mathcal{S}$ of size $2r$\n- One possible method for generating random points in $\\mathcal{C}$ is to generate random points in the square and discard those outside the circle\n- For each step we need to generate 2 points $(x, y)$\n- Thus, the expected number of trials for getting $(x, y) \\in \\mathcal{C}$ is $e = 2 \\cdot p + (1-p) \\cdot (2 + e)$, where $p = P((x,y) \\in \\mathcal{C}) = \\mathcal{A}_{\\mathcal{C}} \\ / \\ \\mathcal{A}_{\\mathcal{S}} = \\pi \\ / \\ 4$\n- We find that $e = 8 \\ / \\ \\pi$\n\n\n```python\ndef rejection_sampling(circle):\n cx, cy, r = circle\n \n xm, xM = cx-r, cx+r\n ym, yM = cy-r, cy+r\n \n rx = xm + rand() * (xM - xm)\n ry = ym + rand() * (yM - ym)\n \n dist = (cx - rx) ** 2 + (cy - ry) ** 2\n if dist <= r ** 2:\n return rx, ry\n \n return rejection_sampling(circle) # discard + repeat\n\nshow(rejection_sampling, circle=(0,0,1), N=10_000)\n```\n\n# What we notice\n\n- [Law of total expectation](https://en.wikipedia.org/wiki/Law_of_total_expectation)\n- [Finding expected value with recursion](https://math.stackexchange.com/q/521609).\n\n$\n\\begin{align}\ne &= \\texttt{success}_1 \\ \\lor \\ \\texttt{repeat} \\\\\ne &= \\texttt{success}_1 \\ \\lor \\ (\\texttt{fail}_1 \\ \\land \\ (\\texttt{success}_2 \\ \\lor \\ \\texttt{repeat})) \\\\\ne &= \\texttt{success}_1 \\ \\lor \\ (\\texttt{fail}_1 \\ \\land \\ (\\texttt{fail}_2 \\ \\land \\ (\\texttt{success}_3 \\ \\lor \\ \\texttt{repeat}))) \\\\\ne &= \\texttt{success}_1 \\ \\lor \\ (\\texttt{fail}_1 \\ \\land \\ (\\texttt{fail}_2 \\ \\land \\ (\\texttt{fail}_3 \\ \\lor \\ (\\texttt{success}_4 \\ \\lor \\ \\texttt{repeat}))))\n\\end{align}\n$\n\n$\\vdots$\n\nTherefore, if we let $n =$ number of samples in one step (e.g. calls to `rand7`, coin tosses), and $p = P(\\texttt{success})$, then:\n\n$\n\\begin{align}\ne &= p \\cdot n + (1-p) \\cdot (n + e) \\\\\ne &= p \\cdot n + n + e - p \\cdot n - p \\cdot e \\\\\ne \\cdot p &= n \\Rightarrow e = n \\ / \\ p\n\\end{align}\n$\n\nThus, $\\mathbb{E}[\\texttt{trials}] = n \\ / \\ P(\\texttt{success})$\n\nThis essentially forms a Markov Chain, so we are interested in expected number of transitions until we reach a certain state. See [this answer](https://math.stackexchange.com/a/947339).\n\n\n```python\n\n```\n", "meta": {"hexsha": "e526ea0da2853cae420ba805d2888c2db3f0dba4", "size": 8179, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/expected_value.ipynb", "max_stars_repo_name": "alexandru-dinu/notebooks", "max_stars_repo_head_hexsha": "7e963f482158db8f86efa3a706ad2b85f82241e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/expected_value.ipynb", "max_issues_repo_name": "alexandru-dinu/notebooks", "max_issues_repo_head_hexsha": "7e963f482158db8f86efa3a706ad2b85f82241e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-11T19:24:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T19:24:10.000Z", "max_forks_repo_path": "src/expected_value.ipynb", "max_forks_repo_name": "alexandru-dinu/notebooks", "max_forks_repo_head_hexsha": "7e963f482158db8f86efa3a706ad2b85f82241e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4208633094, "max_line_length": 251, "alphanum_fraction": 0.4774422301, "converted": true, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422234552271, "lm_q2_score": 0.9546474207360067, "lm_q1q2_score": 0.9080054703746432}}
{"text": "# Quadrature\n\n\n```python\n%matplotlib inline\n\nimport os\nimport glob\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_context('notebook', font_scale=1.5)\n```\n\n## Numerical integration (Quadrature)\n\nYou may recall from Calculus that integrals can be numerically evaluated using quadrature methods such as Trapezoid and Simpson's's rules. This is easy to do in Python, but has the drawback of the complexity growing as $O(n^d)$ where $d$ is the dimensionality of the data, and hence infeasible once $d$ grows beyond a modest number.\n\n### Integrating functions\n\n\n```python\nfrom scipy.integrate import quad\n```\n\n\n```python\ndef f(x):\n return x * np.cos(71*x) + np.sin(13*x)\n```\n\n\n```python\nx = np.linspace(0, 1, 100)\nplt.plot(x, f(x))\npass\n```\n\n#### Exact solution\n\n\n```python\nfrom sympy import sin, cos, symbols, integrate\n\nx = symbols('x')\nintegrate(x * cos(71*x) + sin(13*x), (x, 0,1)).evalf(6)\n```\n\n\n\n\n 0.0202549\n\n\n\n#### Using quadrature\n\n\n```python\ny, err = quad(f, 0, 1.0)\ny\n```\n\n\n\n\n 0.02025493910239419\n\n\n\n#### Multiple integration\n\nFollowing the `scipy.integrate` [documentation](http://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html), we integrate\n\n$$\nI=\\int_{y=0}^{1/2}\\int_{x=0}^{1-2y} x y \\, dx\\, dy\n$$\n\n\n```python\nx, y = symbols('x y')\nintegrate(x*y, (x, 0, 1-2*y), (y, 0, 0.5))\n```\n\n\n\n\n 0.0104166666666667\n\n\n\n\n```python\nfrom scipy.integrate import nquad\n\ndef f(x, y):\n return x*y\n\ndef bounds_y():\n return [0, 0.5]\n\ndef bounds_x(y):\n return [0, 1-2*y]\n\ny, err = nquad(f, [bounds_x, bounds_y])\ny\n```\n\n\n\n\n 0.010416666666666668\n\n\n", "meta": {"hexsha": "9202e75265313b8529634e701e4914d9c103d2c1", "size": 27739, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/T08B_Numerical_integration.ipynb", "max_stars_repo_name": "rjl910/sta-663-2021", "max_stars_repo_head_hexsha": "d9dd12144b7baaf56f235018ac36dd42722035e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2021-01-19T16:35:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T02:12:30.000Z", "max_issues_repo_path": "notebooks/T08B_Numerical_integration.ipynb", "max_issues_repo_name": "rjl910/sta-663-2021", "max_issues_repo_head_hexsha": "d9dd12144b7baaf56f235018ac36dd42722035e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/T08B_Numerical_integration.ipynb", "max_forks_repo_name": "rjl910/sta-663-2021", "max_forks_repo_head_hexsha": "d9dd12144b7baaf56f235018ac36dd42722035e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2021-01-19T16:26:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T05:10:14.000Z", "avg_line_length": 115.0995850622, "max_line_length": 23060, "alphanum_fraction": 0.8937236382, "converted": true, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422172230208, "lm_q2_score": 0.9539661008726658, "lm_q1q2_score": 0.9073574323396273}}
{"text": "# Quadrature\n\n\n```python\n%matplotlib inline\n\nimport os\nimport glob\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_context('notebook', font_scale=1.5)\n```\n\n## Numerical integration (Quadrature)\n\nYou may recall from Calculus that integrals can be numerically evaluated using quadrature methods such as Trapezoid and Simpson's's rules. This is easy to do in Python, but has the drawback of the complexity growing as $O(n^d)$ where $d$ is the dimensionality of the data, and hence infeasible once $d$ grows beyond a modest number.\n\n### Integrating functions\n\n\n```python\nfrom scipy.integrate import quad\n```\n\n\n```python\ndef f(x):\n return x * np.cos(71*x) + np.sin(13*x)\n```\n\n\n```python\nx = np.linspace(0, 1, 100)\nplt.plot(x, f(x))\npass\n```\n\n#### Exact solution\n\n\n```python\nfrom sympy import sin, cos, symbols, integrate\n\nx = symbols('x')\nintegrate(x * cos(71*x) + sin(13*x), (x, 0,1)).evalf(6)\n```\n\n\n\n\n$\\displaystyle 0.0202549$\n\n\n\n#### Using quadrature\n\n\n```python\ny, err = quad(f, 0, 1.0)\ny\n```\n\n\n\n\n 0.02025493910239419\n\n\n\n#### Multiple integration\n\nFollowing the `scipy.integrate` [documentation](http://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html), we integrate\n\n$$\nI=\\int_{y=0}^{1/2}\\int_{x=0}^{1-2y} x y \\, dx\\, dy\n$$\n\n\n```python\nx, y = symbols('x y')\nintegrate(x*y, (x, 0, 1-2*y), (y, 0, 0.5))\n```\n\n\n\n\n$\\displaystyle 0.0104166666666667$\n\n\n\n\n```python\nfrom scipy.integrate import nquad\n\ndef f(x, y):\n return x*y\n\ndef bounds_y():\n return [0, 0.5]\n\ndef bounds_x(y):\n return [0, 1-2*y]\n\ny, err = nquad(f, [bounds_x, bounds_y])\ny\n```\n\n\n\n\n 0.010416666666666668\n\n\n", "meta": {"hexsha": "1770d71a3e50d6ddcd8a04a2e88219b9bdd79ca9", "size": 27227, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/copies/lectures/T08B_Numerical_integration.ipynb", "max_stars_repo_name": "robkravec/sta-663-2021", "max_stars_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/copies/lectures/T08B_Numerical_integration.ipynb", "max_issues_repo_name": "robkravec/sta-663-2021", "max_issues_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/copies/lectures/T08B_Numerical_integration.ipynb", "max_forks_repo_name": "robkravec/sta-663-2021", "max_forks_repo_head_hexsha": "4dc8018f7b172eaf81da9edc33174768ff157939", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 111.1306122449, "max_line_length": 22444, "alphanum_fraction": 0.876042164, "converted": true, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768557238084, "lm_q2_score": 0.9609517116071399, "lm_q1q2_score": 0.9073083655676413}}
{"text": "---\nauthor: Nathan Carter (ncarter@bentley.edu)\n---\n\nThis answer assumes you have imported SymPy as follows.\n\n\n```python\nfrom sympy import * # load all math functions\ninit_printing( use_latex='mathjax' ) # use pretty math output\n```\n\nLet's define an example function whose Taylor series we'd like to compute.\n\n\n```python\nvar( 'x' )\nformula = exp( 2*x + 1 )\nformula\n```\n\n\n\n\n$\\displaystyle e^{2 x + 1}$\n\n\n\nLet's ask for a degree-5 Taylor series centered at $x=2$. From the code below,\nyou can tell that the third parameter is the center point and the fourth\nparameter is the degree.\n\n\n```python\nseries( formula, x, 2, 5 )\n```\n\n\n\n\n$\\displaystyle e^{5} + 2 \\left(x - 2\\right) e^{5} + 2 \\left(x - 2\\right)^{2} e^{5} + \\frac{4 \\left(x - 2\\right)^{3} e^{5}}{3} + \\frac{2 \\left(x - 2\\right)^{4} e^{5}}{3} + O\\left(\\left(x - 2\\right)^{5}; x\\rightarrow 2\\right)$\n\n\n\nThe final term (starting with O---oh, not zero) means that there are more terms\nin the infinite Taylor series not shown in this finite approximation.\nIf you want to show just the approximation, you can tell it to remove the O term.\n\n\n```python\nseries( formula, x, 2, 5 ).removeO()\n```\n\n\n\n\n$\\displaystyle \\frac{2 \\left(x - 2\\right)^{4} e^{5}}{3} + \\frac{4 \\left(x - 2\\right)^{3} e^{5}}{3} + 2 \\left(x - 2\\right)^{2} e^{5} + 2 \\left(x - 2\\right) e^{5} + e^{5}$\n\n\n\nYou can also compute individual coefficients in a Taylor series\nby remembering the formula for the $n^\\text{th}$ term in the series and applying it,\nas follows. The formula for a series centered on $x=a$ is $\\frac{f^{(n)}(a)}{n!}$.\n\nFrom the answer above, we can see that the coefficient on the $n=3$ term is $\\frac43e^5$.\n\n\n```python\nn = 3\na = 2\ndiff( formula, x, n ).subs( x, a ) / factorial( n )\n```\n\n\n\n\n$\\displaystyle \\frac{4 e^{5}}{3}$\n\n\n", "meta": {"hexsha": "118273e60145cf84412ed75063b60a78dce45b48", "size": 4996, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "database/tasks/How to compute the Taylor series for a function/Python, using SymPy.ipynb", "max_stars_repo_name": "nathancarter/how2data", "max_stars_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "database/tasks/How to compute the Taylor series for a function/Python, using SymPy.ipynb", "max_issues_repo_name": "nathancarter/how2data", "max_issues_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "database/tasks/How to compute the Taylor series for a function/Python, using SymPy.ipynb", "max_forks_repo_name": "nathancarter/how2data", "max_forks_repo_head_hexsha": "7d4f2838661f7ce98deb1b8081470cec5671b03a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-18T19:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:47:11.000Z", "avg_line_length": 27.0054054054, "max_line_length": 262, "alphanum_fraction": 0.4463570857, "converted": true, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338057771059, "lm_q2_score": 0.9425067262462462, "lm_q1q2_score": 0.9062520794580741}}
{"text": "# Automatic Differentiation (AD)\n\nIn short, the promise of AD is\n\n```julia\nf(x) = 4x + x^2\n\ndf(x) = derivative(f, x)\n```\n\nsuch that\n\n```julia\ndf(3) = 4 + 2*3 = 10\n```\n\n### What AD is not\n\n**Symbolic rewriting:**\n$$ f(x) = 4x + x^2 \\quad \\rightarrow \\quad df(x) = 4 + 2x $$\n\n**Numerical differentiation:**\n$$ \\frac{df}{dx} \\approx \\frac{f(x+h) - f(x)}{\\Delta h} $$\n\n## Forward mode AD\n\nKey to AD is the application of the chain rule\n$$\\dfrac{d}{dx} f(g(x)) = \\dfrac{df}{dg} \\dfrac{dg}{dx}$$\n\nConsider the function $f(a,b) = \\ln(ab + \\sin(a))$.\n\n\n```julia\nf(a,b) = log(a*b + sin(a))\n```\n\n\n```julia\nf_derivative(a,b) = 1/(a*b + sin(a)) * (b + cos(a))\n```\n\n\n```julia\na = 3.1\nb = 2.4\nf_derivative(a,b)\n```\n\nDividing the function into the elementary steps, it corresponds to the following \"*computational graph*\":\n\n\n\n\n```julia\nfunction f_graph(a,b)\n c1 = a*b\n c2 = sin(a)\n c3 = c1 + c2\n c4 = log(c3)\nend\n```\n\n\n```julia\nf(a,b) == f_graph(a,b)\n```\n\nTo calculate $\\frac{\\partial f}{\\partial a}$ we have to apply the chain rule multiple times.\n\n$\\dfrac{\\partial f}{\\partial a} = \\dfrac{\\partial f}{\\partial c_4} \\dfrac{\\partial c_4}{\\partial a} = \\dfrac{\\partial f}{\\partial c_4} \\left( \\dfrac{\\partial c_4}{\\partial c_3} \\dfrac{\\partial c_3}{\\partial a} \\right) = \\dfrac{\\partial f}{\\partial c_4} \\left( \\dfrac{\\partial c_4}{\\partial c_3} \\left( \\dfrac{\\partial c_3}{\\partial c_2} \\dfrac{\\partial c_2}{\\partial a} + \\dfrac{\\partial c_3}{\\partial c_1} \\dfrac{\\partial c_1}{\\partial a}\\right) \\right)$\n\n\n```julia\nfunction f_graph_derivative(a,b)\n c1 = a*b\n c1_ϵ = b\n \n c2 = sin(a)\n c2_ϵ = cos(a)\n \n c3 = c1 + c2\n c3_ϵ = c1_ϵ + c2_ϵ\n \n c4 = log(c3)\n c4_ϵ = 1/c3 * c3_ϵ\n \n c4, c4_ϵ\nend\n```\n\n\n```julia\nf_graph_derivative(a,b)[2] == f_derivative(a,b)\n```\n\n**How can we automate this?**\n\n\n```julia\n# D for \"dual number\", invented by Clifford in 1873.\nstruct D <: Number\n x::Float64 # value\n ϵ::Float64 # derivative\nend\n```\n\n\n```julia\nimport Base: +, *, /, -, sin, log, convert, promote_rule\n\na::D + b::D = D(a.x + b.x, a.ϵ + b.ϵ) # sum rule\na::D - b::D = D(a.x - b.x, a.ϵ - b.ϵ)\na::D * b::D = D(a.x * b.x, a.x * b.ϵ + a.ϵ * b.x) # product rule\na::D / b::D = D(a.x / b.x, (b.x * a.ϵ - a.x * b.ϵ)/b.x^2) # quotient rule\n\nsin(a::D) = D(sin(a.x), cos(a.x) * a.ϵ)\nlog(a::D) = D(log(a.x), 1/a.x * a.ϵ)\n\nBase.convert(::Type{D}, x::Real) = D(x, zero(x))\nBase.promote_rule(::Type{D}, ::Type{<:Number}) = D\n```\n\n\n```julia\nf(D(a,1), b)\n```\n\nBoom! That was easy!\n\n\n```julia\nf_derivative(a,b)\n```\n\n\n```julia\nf(D(a,1), b).ϵ ≈ f_derivative(a,b)\n```\n\n**How does this work?!**\n\nThe trick of forward mode AD is to let Julia implicitly perform the mapping `f -> f_graph_derivative` for you and then let the compiler optimize the resulting code structure (that's what compilers do!).\n\n\n```julia\n@code_typed f(D(a,1), b)\n```\n\nWhile this is somewhat hard to parse, plugging these operations manually into each other we find that this code equals\n\n```julia\nD.x = log(a.x*b + sin(a.x))\nD.ϵ = 1/(a.x*b + sin(a.x)) * (a.x*0 + (a.ϵ*b) + cos(a.x)*a.ϵ)\n```\n\nwhich, if we drop `a.x*0`, set `a.ϵ = 1`, and rename `a.x` $\\rightarrow$ `a`, reads\n\n```julia\nD.x = log(a*b + sin(a))\nD.ϵ = 1/(a*b + sin(a)) * (b + cos(a)\n```\n\nThis precisely matches our definitions from above:\n\n```julia\nf(a,b) = log(a*b + sin(a))\n\nf_derivative(a,b) = 1/(a*b + sin(a)) * (b + cos(a))\n```\n\nImportantly, the compiler sees the entire \"rewritten\" code and can therefore apply optimizations. In this simple example, we find that the code produced by our simple Forward mode AD is essentially identical to the explicit implementation.\n\n\n```julia\n@code_llvm debuginfo=:none f_graph_derivative(a,b)\n```\n\n\n```julia\n@code_llvm debuginfo=:none f(D(a,1), b)\n```\n\nOur AD is alreadly pretty powerful and general. Let's define the promised function `derivative`:\n\n\n```julia\nderivative(f::Function, x::Number) = f(D(x, one(x))).ϵ\n```\n\n\n```julia\ng(x) = x + x^2\n```\n\n\n```julia\nderivative(g, 3.0)\n```\n\nAnonymous function oft come in handy here:\n\n\n```julia\nderivative(x->3*x^2+4x+5, 2)\n```\n\n\n```julia\nderivative(x->sin(x)*log(x), 3)\n```\n\nWe can also define the partial derivative $\\frac{df(a,b)}{da}$ from above:\n\n\n```julia\ndf(x) = derivative(a->f(a,b),x)\n```\n\nHere, `b` is \"wrapped into a closure\".\n\n\n```julia\ndf(1.23)\n```\n\n## Taking the derivative of *code*\n\n> Repeat $t \\leftarrow (t + x/2)/2$ until $t$ converges to $\\sqrt{x}$.\n\n\n```julia\n@inline function Babylonian(x; N = 10)\n t = (1+x)/2\n for i = 2:N\n t = (t + x/t)/2\n end\n t\nend\n```\n\n\n```julia\nBabylonian(2)\n```\n\n\n```julia\nsqrt(2)\n```\n\nUsing our forward mode AD, that is our dual numbers, we can compute the derivative of `Babylonian` **with no rewrite at all**.\n\n\n```julia\nBabylonian(D(5, 1))\n```\n\n\n```julia\nsqrt(5)\n```\n\n\n```julia\n1 / (2*sqrt(5))\n```\n\n**It just works and is efficient!**\n\n\n```julia\n@code_native debuginfo=:none Babylonian(D(5, 1))\n```\n\nRecursion? Works as well...\n\n\n```julia\nfunction power(x, n)\n if n <= 0\n return 1\n else\n return x*power(x, n-1)\n end\nend\n```\n\n\n```julia\n4.0^3\n```\n\n\n```julia\nderivative(x -> power(x,3), 4.0)\n```\n\n\n```julia\n3*4.0^2 # 3*x^2\n```\n\nDeriving our Vandermonde matrix from yesterday?\n\n\n```julia\nfunction vander_generic(x::AbstractVector{T}) where T\n m = length(x)\n V = Matrix{T}(undef, m, m)\n for j = 1:m\n V[j,1] = one(x[j])\n end\n for i= 2:m\n for j = 1:m\n V[j,i] = x[j] * V[j,i-1]\n end\n end\n return V\nend\n```\n\n\\begin{align}V=\\begin{bmatrix}1&a&a^{2} &a^3\\\\1&b&b^{2} &b^3\\\\1&c&c^{2} &c^3\\\\1&d&d^{2} &d^3\\end{bmatrix}\\end{align}\n\n\\begin{align}\\frac{dV}{da}=\\begin{bmatrix}0&1&2a &3a^2\\\\0&0&0 &0\\\\0&0&0 &0\\\\0&0&0 &0\\end{bmatrix}\\end{align}\n\n\n```julia\na, b, c, d = 2, 3, 4, 5\nV = vander_generic([D(a,1), D(b,0), D(c,0), D(d,0)])\n```\n\n\n```julia\n[V[i,j].ϵ for i in axes(V,1), j in axes(V,2)]\n```\n\n## Symbolically (because we can)\n\nThe below is mathematically equivalent, **though not exactly what the computation is doing**. Our AD isn't performing symbolic manipulations.\n\n\n```julia\nusing SymPy\n```\n\n\n```julia\n@vars x\n```\n\n\n```julia\nBabylonian(x; N=1)\n```\n\n\n```julia\ndiff(Babylonian(x; N=1))\n```\n\n\n```julia\nsimplify(Babylonian(x; N=5))\n```\n\n\n```julia\nsimplify(diff(simplify(Babylonian(x; N=5)), x))\n```\n\n## Don't reinvent the wheel: ForwardDiff.jl\n\nNow that we have understood how forward AD works, we can use the more feature complete package [ForwardDiff.jl](https://github.com/JuliaDiff/ForwardDiff.jl).\n\n\n```julia\nusing ForwardDiff\n```\n\n\n```julia\nForwardDiff.derivative(Babylonian, 2)\n```\n\n\n```julia\n@edit ForwardDiff.derivative(Babylonian, 2)\n```\n\n(Note: [DiffRules.jl](https://github.com/JuliaDiff/DiffRules.jl))\n\n## If time permits: Reverse mode AD\n\nForward mode:\n$\\dfrac{\\partial f}{\\partial x} = \\dfrac{\\partial f}{\\partial c_4} \\dfrac{\\partial c_4}{\\partial x} = \\dfrac{\\partial f}{\\partial c_4} \\left( \\dfrac{\\partial c_4}{\\partial c_3} \\dfrac{\\partial c_3}{\\partial x} \\right) = \\dfrac{\\partial f}{\\partial c_4} \\left( \\dfrac{\\partial c_4}{\\partial c_3} \\left( \\dfrac{\\partial c_3}{\\partial c_2} \\dfrac{\\partial c_2}{\\partial x} + \\dfrac{\\partial c_3}{\\partial c_1} \\dfrac{\\partial c_1}{\\partial x}\\right) \\right)$\n\nReverse mode:\n$\\dfrac{\\partial f}{\\partial x} = \\dfrac{\\partial f}{\\partial c_4} \\dfrac{\\partial c_4}{\\partial x} = \\left( \\dfrac{\\partial f}{\\partial c_3}\\dfrac{\\partial c_3}{\\partial c_4} \\right) \\dfrac{\\partial c_4}{\\partial x} = \\left( \\left( \\dfrac{\\partial f}{\\partial c_2} \\dfrac{\\partial c_2}{\\partial c_3} + \\dfrac{\\partial f}{\\partial c_1} \\dfrac{\\partial c_1}{\\partial c_3} \\right) \\dfrac{\\partial c_3}{\\partial c_4} \\right) \\dfrac{\\partial c_4}{\\partial x}$\n\nForward mode AD requires $n$ passes in order to compute an $n$-dimensional\ngradient.\n\nReverse mode AD requires only a single run in order to compute a complete gradient but requires two passes through the graph: a forward pass during which necessary intermediate values are computed and a backward pass which computes the gradient.\n\n*Rule of thumb:*\n\nForward mode is good for $\\mathbb{R} \\rightarrow \\mathbb{R}^n$ while reverse mode is good for $\\mathbb{R}^n \\rightarrow \\mathbb{R}$.\n\nAn efficient source-to-source reverse mode AD is implemented in [Zygote.jl](https://github.com/FluxML/Zygote.jl), the AD underlying [Flux.jl](https://fluxml.ai/) (since version 0.10).\n\n\n```julia\nusing Zygote\n```\n\n\n```julia\nf(x) = 5*x + 3\n```\n\n\n```julia\ngradient(f, 5)\n```\n\n\n```julia\n@code_llvm debuginfo=:none gradient(f,5)\n```\n\n\n```julia\n@code_llvm debuginfo=:none derivative(f,5)\n```\n\n## Some nice reads\n\nPapers:\n* https://www.jmlr.org/papers/volume18/17-468/17-468.pdf\n\nLectures:\n\n\n* https://mitmath.github.io/18337/lecture8/automatic_differentiation.html\n\nBlog posts:\n\n* ML in Julia: https://julialang.org/blog/2018/12/ml-language-compiler\n\n* Nice example: https://fluxml.ai/2019/03/05/dp-vs-rl.html\n\n* Nice interactive examples: https://fluxml.ai/experiments/\n\n* Why Julia for ML? https://julialang.org/blog/2017/12/ml&pl\n\n* Neural networks with differential equation layers: https://julialang.org/blog/2019/01/fluxdiffeq\n\n* Implement Your Own Automatic Differentiation with Julia in ONE day : http://blog.rogerluo.me/2018/10/23/write-an-ad-in-one-day/\n\n* Implement Your Own Source To Source AD in ONE day!: http://blog.rogerluo.me/2019/07/27/yassad/\n\nRepositories:\n\n* AD flavors, like forward and reverse mode AD: https://github.com/MikeInnes/diff-zoo (Mike is one of the smartest Julia ML heads)\n\nTalks:\n\n* AD is a compiler problem: https://juliacomputing.com/assets/pdf/CGO_C4ML_talk.pdf\n", "meta": {"hexsha": "44b2f002236f480247e4a09b76a84b31c82c4b84", "size": 20120, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Day2/4a_automatic_differentiation.ipynb", "max_stars_repo_name": "tbdrstl/JuliaCologne21", "max_stars_repo_head_hexsha": "0e2778cd8d0601291dcc8573c20469b3fb84ebe7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-03-09T19:05:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T05:00:07.000Z", "max_issues_repo_path": "Day2/4a_automatic_differentiation.ipynb", "max_issues_repo_name": "tbdrstl/JuliaCologne21", "max_issues_repo_head_hexsha": "0e2778cd8d0601291dcc8573c20469b3fb84ebe7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-18T09:27:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T09:37:47.000Z", "max_forks_repo_path": "Day2/4a_automatic_differentiation.ipynb", "max_forks_repo_name": "tbdrstl/JuliaCologne21", "max_forks_repo_head_hexsha": "0e2778cd8d0601291dcc8573c20469b3fb84ebe7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-03-18T09:30:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-18T06:50:58.000Z", "avg_line_length": 22.4804469274, "max_line_length": 508, "alphanum_fraction": 0.5011928429, "converted": true, "num_tokens": 3427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731126558705, "lm_q2_score": 0.9407897459384732, "lm_q1q2_score": 0.9056729930773156}}
{"text": "<a href=\"https://colab.research.google.com/github/seanie12/linear-algebra/blob/master/linear_regression.ipynb\" target=\"_parent\"></a>\n\n# Linear Regression with Normal Equation and Gradient Descent\n\n$X \\in \\mathfrak{M}_{m\\times n}(\\mathbb{R}), \\mathbf{y} \\in \\mathbb{R}^m, \\theta \\in \\mathbb{R}^n$ \n\\begin{equation}\n\\mathcal{L(\\theta) = || \\mathbf{X}\\theta - \\mathbf{y} ||^2}\n\\end{equation}\n\nWe want to find $\\theta$ which minizes the error function $\\mathcal{L}(\\theta)$.\n\n\n```\nimport numpy as np\nfrom numpy.linalg import inv\n```\n\n\n```\nnum_features = 5\nX = np.random.randn(100, num_features)\nY = np.random.randn(100)\ntheta = np.random.randn(num_features)\n\n```\n\n\n```\nerror = np.sum((Y - np.dot(X, theta))**2, axis=0)\nerror\n```\n\n\n\n\n 441.1478116816043\n\n\n\n## Normal Equation\n\n It has closed-form solution as follows, which is Normal Equation :\n\\begin{align*}\n\\text{argmin}_{\\theta} \\mathcal{L}(\\theta) = (X^tX)^{-1}X^t\\mathbf{y}\n\\end{align*}\n\n\n```\ntheta_hat = np.dot(inv(X.T @ X) @ X.T, Y)\nfinal_loss = np.sum((Y - np.dot(X, theta_hat))**2, axis=0)\nfinal_loss \n```\n\n\n\n\n 88.15259780536041\n\n\n\n## Gradient Descent\n\nSince $\\mathcal{L}(\\theta)$ is differentiable function, we can find find the parameter $\\theta$ by gradient descent as follows, where $\\eta$ is learning rate:\n\\begin{align*}\n\\nabla_\\theta \\mathcal{L}(\\theta) := (\\frac{\\partial \\mathcal{L}(\\theta)}{\\partial \\theta_1}, \\ldots, \\frac{\\partial \\mathcal{L}(\\theta)}{\\partial \\theta_n}, )\n\\end{align*}\n\\begin{equation}\n\\theta^{(t+1)} = \\theta^{(t)} - \\eta \\nabla_{\\theta}\\mathcal{L}(\\theta^{(t)})\n\\end{equation}\n\nLet $\\mathbf{x_i}$ the ith row vector of $X$.\n\\begin{align*}\n\\frac{\\partial \\mathcal{L}(\\theta)}{\\partial \\theta_j} &= \\sum\\limits_{i=1}^m (\\mathbf{x}_i\\cdot \\theta - y_i)^2 \\\\\n&= \\sum\\limits_{i=1}^m \\frac{\\partial (\\mathbf{x}_i \\cdot \\theta - y_i)^2}{\\partial \\theta_j} \\\\\n&= \\sum\\limits_{i=1}^m 2(\\mathbf{x}_i \\cdot \\theta - y_i) \\frac{\\partial (\\mathbf{x}_i \\cdot \\theta - y_i)}{\\partial \\theta_j} \\\\\n&= \\sum\\limits_{i=1}^m 2(\\mathbf{x}_i \\cdot \\theta - y_i) X_{ij} \\:\\: \\text{ where } X_{ij} \\text{ is } (i,j) \\text{ entry of } X \\\\\n&= 2 [X]^j \\cdot (X\\theta - \\mathbf{y}) \\text{ where } [X]^j \\text{is the jth column vector of }X \\\\\n\\end{align*}\n\n\n\\begin{equation}\\therefore \\nabla_{\\theta}\\mathcal{L}(\\theta) = 2X^t(X\\theta - \\mathbf{y})\n\\end{equation}\n\n\n```\nclass Regression(object):\n def __init__(self, num_features, lr=0.001):\n self.weight = np.random.randn(num_features)\n self.lr = lr\n\n\n def forward(self, x):\n self.logits = np.dot(x, self.weight)\n \n return self.logits\n\n def backward(self, x, y):\n grad = 2 * x.T @ (self.logits - y)\n self.weight = self.weight - self.lr * grad\n return grad\n\n```\n\n\n```\nnet = Regression(num_features, lr=0.001)\n\nfor _ in range(100):\n logits = net.forward(X)\n loss = np.sum((logits - Y) ** 2, 0)\n grad = net.backward(X, Y)\n\nlogits = net.forward(X)\nsgd_loss = np.sum((logits - Y)**2, axis=0)\nprint(sgd_loss)\n```\n\n 88.15259780539971\n\n\n\n```\nabs(final_loss - sgd_loss)\n```\n\n\n\n\n 3.929301328753354e-11\n\n\n\n\n", "meta": {"hexsha": "760b6ec470fc1a84e24b3e17debcccde827c5039", "size": 9045, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "linear_regression.ipynb", "max_stars_repo_name": "seanie12/linear-algebra", "max_stars_repo_head_hexsha": "e6ca8c99cb077a4c6183d7b32bb7edb3ad589b51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2019-07-08T15:14:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T02:38:30.000Z", "max_issues_repo_path": "linear_regression.ipynb", "max_issues_repo_name": "seanie12/linear-algebra", "max_issues_repo_head_hexsha": "e6ca8c99cb077a4c6183d7b32bb7edb3ad589b51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_regression.ipynb", "max_forks_repo_name": "seanie12/linear-algebra", "max_forks_repo_head_hexsha": "e6ca8c99cb077a4c6183d7b32bb7edb3ad589b51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.745398773, "max_line_length": 239, "alphanum_fraction": 0.4382531786, "converted": true, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399069145609, "lm_q2_score": 0.933430805473952, "lm_q1q2_score": 0.9056518178142308}}
{"text": "# Potential flow\n\n\n## Potencial functions\n\n**Uniform flow**:\n\n$w = U\\exp{(-i\\alpha)}z$\n\n**Line source**:\n\n$w = \\dfrac{\\dot{Q}}{2\\pi}\\ln z$\n\n## Velocity fields\n\n$\\dfrac{dw}{dz} = u + iv$\n\n**Uniform flow:**\n\n$\\dfrac{dw}{dz} = U\\left(\\cos{\\alpha}-i\\sin{\\alpha}\\right)$ \n\n**Line source:**\n\n$\\dfrac{dw}{dz} = \\dfrac{\\dot{Q}}{2\\pi}\\dfrac{1}{z}$\n\n## Combine potentials \n\nConsider a potential flow with a sink at $(0,0)$ and a source at $(r,0)$, under the influence of a horizontal uniform flow going from left to right ($\\alpha = \\pi$). The potential that describes that system is given by:\n\n$w = w_{\\rm uniform} + w_{\\rm source} + w_{\\rm sink}$\n\nHence, \n\n$w = U\\exp{(-i\\alpha)}z + \\dfrac{\\dot{Q_{\\rm in}}}{2\\pi}\\ln (z-r) - \\dfrac{\\dot{Q_{\\rm out}}}{2\\pi}\\ln z$\n\n$w = -Uz + \\dfrac{\\dot{Q_{\\rm in}}}{2\\pi}\\ln (z-r) - \\dfrac{\\dot{Q_{\\rm out}}}{2\\pi}\\ln z$\n\nThe uniform flow component will represent the regional flow, which can be described using Darcy's law as $U=-K\\dot{I}$, where $K$ is the hydraulic conductivity (m/s) and $\\dot{I}$ is the water table gradient (m/m). The source and sink wells represent injection and extraction points, characterized by flow rates per unit depth $\\dot{Q_{\\rm in}}$ and $\\dot{Q_{\\rm out}}$ (m²/s). For an aquifer of depth $H$, the volumetric flow rate $Q$ is $\\dot{Q}=Q/H$. Now, the extraction rate can be expressed as a proportion to the injection rate as $Q_{\\rm out} = fQ_{\\rm in}$. With all this replacements, the potential function can be rewritten as:\n\n$w = K\\dot{I}z + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left( \\ln(z-r) - f \\ln z \\right)$\n\nNotice that in our case, the gradient $\\dot{I}$ must be negative so the regional flow goes indeed from right to left. To avoid confusion, let's rewrite it in terms of the abs value of the gradient $I$:\n\n$w = -KIz + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left( \\ln(z-r) - f \\ln z \\right)$\n\n## Velocity field \n\n$\\dfrac{dw}{dz} = \\dfrac{d}{dz}\\left(-KIz + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left( \\ln(z-r) - f \\ln z \\right)\\right)$\n\n$\\dfrac{dw}{dz} = -KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\dfrac{d}{dz}\\left( \\ln(z-r) - f \\ln z \\right)$\n\n$\\dfrac{dw}{dz} = -KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{z-r} - \\dfrac{f}{z} \\right)$\n\n## Velocity at the midpoint\n\nWe'll pick the velocity in the midpoint between the extraction and injection points as the characteristic velocity of the system. This means that we want to evaluate the velocity field at $z = r/2 + 0i$\n\n\\begin{equation}\n\\begin{array}{rl}\n \\dfrac{dw}{dz}\\bigg\\rvert_{z=r/2+0i} =& -KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{r/2-r} - \\dfrac{f}{r/2} \\right)\\\\\n =& -KI - \\dfrac{Q_{\\rm in}}{\\pi H} \\left(\\dfrac{1+f}{r}\\right)\n\\end{array}\n\\end{equation}\n\nNotice that this velocity can be split into the contribution of the regional flow and the contribution from the wells:\n\n\\begin{equation}\n\\begin{array}{rl}\n w'_{\\rm regional} =& -KI \\\\\n w'_{\\rm wells} =& -\\dfrac{1}{\\pi}\\dfrac{Q_{\\rm in} (1+f)}{r H}\n\\end{array}\n\\end{equation}\n\n\n### Non-dimensional flow number ($\\mathcal{F}_L$)\n\nA comparison between the component in the velocity due regional flow and the component due the wells as a ratio between them two. \n\n\\begin{equation}\n\\begin{array}{rl}\n\\mathcal{F}_L =& \\dfrac{\\text{Velocity due regional flow}}{\\text{Velocity due well couple}} \\\\\n=& \\dfrac{w'_{\\rm regional}}{w'_{\\rm wells}} \\\\\n=& \\dfrac{-KI}{-\\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1+f}{r}\\right)} \\\\\n=& \\dfrac{\\pi K I H r}{Q_{in}(1+f)}\n\\end{array}\n\\end{equation}\n\nIf $\\mathcal{F}_L \\to 0$, the flow induced by the wells rule the system, whereas if $\\mathcal{F}_L \\to \\infty$, the regional flow rule the system.\n\n## Minimum velocity along a streamline\n\nThe minimum velocity is found at:\n\n\\begin{equation}\n\\begin{array}{rl}\n \\dfrac{d}{dx}\\dfrac{dw}{dz}\\bigg\\rvert_{z=x+0i} =& 0 \\\\\n \\dfrac{d}{dx}\\left(-KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{x-r} - \\dfrac{f}{x} \\right)\\right) =& 0\\\\\n \\dfrac{Q_{\\rm in}}{2 \\pi H} \\dfrac{d}{dx}\\left(\\dfrac{1}{x-r} - \\dfrac{f}{x} \\right) =& 0\\\\\n \\dfrac{Q_{\\rm in}}{2 \\pi H} \\left(\\dfrac{f}{x^2} - \\dfrac{1}{\\left(x-r\\right)^2}\\right) =& 0\\\\\n \\\\\n \\dfrac{f}{x^2} =& \\dfrac{1}{\\left(x-r\\right)^2}\\\\\n x^2 =& f \\left( x-r \\right) ^2\\\\\n x =& \\dfrac{\\sqrt{f}}{\\sqrt{f}\\pm1}r\n \\\\\n x < r \\Rightarrow x =& \\dfrac{\\sqrt{f}}{\\sqrt{f}+1}r\n\\end{array}\n\\end{equation}\n\nDefining $m = \\dfrac{\\sqrt{f}}{\\sqrt{f}+1}$, evaluating at $z = mr + 0i$ gives the minimum velocity.\n\n\n\\begin{equation}\n\\begin{array}{rl}\n \\dfrac{dw}{dz}\\bigg\\rvert_{z=mr+0i} =& -KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{mr-r} - \\dfrac{f}{mr} \\right)\\\\\n =& -KI + \\dfrac{Q_{\\rm in}}{2 \\pi H} \\left(\\dfrac{m-fm+f}{m(m-1)}\\right)\\\\\n =& -KI - \\dfrac{Q_{\\rm in}}{2 \\pi H} \\left(\\dfrac{\\left(\\sqrt{f}+f\\right)\\left(\\sqrt{f}+1\\right)}{\\sqrt{f}}\\right)\\\\\n =& -KI - \\dfrac{Q_{\\rm in}}{2 \\pi H} \\left( \\left( 1+ \\sqrt{f}\\right)\\left( 1 + \\dfrac{\\sqrt{f}}{f} \\right) \\right)\\\\\n =& -KI - \\dfrac{ Q_{\\rm in}\\left( 1 + \\tfrac{\\sqrt{f}}{f} \\right) } {\\pi H r}\n\\end{array}\\\\\n\\end{equation}\n\nThis velocity can also be split into the contribution of the regional flow and the contribution from the wells:\n\n\\begin{equation}\n\\begin{array}{rl}\n w'_{\\rm regional} =& -KI \\\\\n w'_{\\rm wells} =& -\\dfrac{Q_{\\rm in} }{\\pi r H}\\left(1+\\tfrac{\\sqrt{f}}{f}\\right)\n\\end{array}\n\\end{equation}\n\n## Mean velocity along a streamline\n\nConsider the streamline that connects the sink and source points. It cannot be measured at those points because those are poles in the system, hence, some separation $\\delta$ from those points has to be considered: the well radius should be the straighforward election so we'll adopt it and assume that both injection and extraction wells have the same diameter.\n\nNow, with $z = x+iy$, the streamline exists at $y=0$ and $\\delta<x<r-\\delta$, hence, the mean velocity can be derived as follows:\n\n\\begin{equation}\n\\begin{array}{rl}\n\\bar{u} =& \\dfrac{1}{r-2\\delta} \\int_{\\delta}^{r-\\delta}\\dfrac{dw}{dz}dx\\\\\n=& \\dfrac{1}{r-2\\delta} \\int_{\\delta}^{r-\\delta} \\left(-KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{z-r} - \\dfrac{f}{z} \\right)\\right)dx\\\\\n=& -KI + \\dfrac{Q_{\\rm in}}{2\\pi (r-2\\delta) H}\\int_{\\delta}^{r-\\delta}\\left(\\dfrac{1}{x-r} - \\dfrac{f}{x} \\right)dx\\\\\n=& -KI + \\dfrac{Q_{\\rm in}}{2\\pi H}\\left(\\ln({x-r}) - f\\ln{x} \\right)\\bigg\\rvert_{x=\\delta}^{x=r-\\delta}\\\\\n=& -KI + \\dfrac{Q_{\\rm in}}{2\\pi H}\\left[ (1+f)(\\ln(\\delta) -\\ln(r-\\delta) \\right]\\\\\n=& -KI - \\dfrac{Q_{\\rm in}(1+f)}{2\\pi H}\\ln\\left(\\dfrac{r-\\delta}{\\delta}\\right)\\\\\n\\end{array}\n\\end{equation}\n\nNotice that this velocity can be split into the contribution of the regional flow and the contribution from the wells:\n\n\\begin{equation}\n\\begin{array}{rl}\n w'_{\\rm regional} =& -KI \\\\\n w'_{\\rm wells} =& -\\dfrac{Q_{\\rm in}(1+f)}{2\\pi H}\\ln\\left(\\dfrac{r-\\delta}{\\delta}\\right)\n\\end{array}\n\\end{equation}\n\n### Non-dimensional flow number ($\\mathcal{F}_L$)\n\nA comparison between the component in the velocity due regional flow and the component due the wells as a ratio between them two. \n\n\\begin{equation}\n\\begin{array}{rl}\n\\mathcal{F}_L =& \\dfrac{\\text{Velocity due regional flow}}{\\text{Velocity due well couple}} \\\\\n=& \\dfrac{w'_{\\rm regional}}{w'_{\\rm wells}} \\\\\n=& \\dfrac{-KI}{-\\dfrac{Q_{\\rm in}(1+f)}{2\\pi H}\\ln\\left(\\dfrac{r-\\delta}{\\delta}\\right)} \\\\\n=& \\dfrac{2 \\pi K I H (r-2\\delta)}{Q_{in}(1+f)\\ln\\left(\\frac{r-\\delta}{\\delta}\\right)}\n\\end{array}\n\\end{equation}\n\nIf $\\mathcal{F}_L \\to 0$, the flow induced by the wells rule the system, whereas if $\\mathcal{F}_L \\to \\infty$, the regional flow rule the system.\n\n## Mass flow through an infinite line\n\nThe previous choice of characteristic velocity seems arbitrary in the sense it overestimates the effect of the potential induced by the wells on the system. This is because the streamline along the x-axis has the highest velocity magnitude (the sharpest potential gradient), if we were to pick a point elsewhere, the veloicty form the wells would be less. But in the same sense, for $f=1$, this point represents the lowest velocity along that streamline. \n\nTo avoid this apparent bias, let's consider the totality of the flow that crosses an infinite vertical line at $z=r/2+iy$. This won't give us a useful insight on the regional flow as that mass flow will diverge, but it will give us a point of comparison to the wells contribution to the total mass balance in the system. \n\nSo, the velocity field along that vertical line is \n\n\\begin{equation}\n\\begin{array}{rl}\n\\dfrac{dw}{dz}\\bigg\\rvert_{z=\\tfrac{r}{2}+iy} =& -KI - \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{z-r} - \\dfrac{f}{z} \\right)\\bigg\\rvert_{z=\\tfrac{r}{2}+iy}\\\\\n=& - KI + \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{1}{\\tfrac{r}{2}+iy-r} - \\dfrac{f}{\\tfrac{r}{2}+iy} \\right)\\\\\n=& -KI - \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{\\tfrac{r}{2}(1+f) + iy(1-f)}{\\tfrac{r^2}{4}-y^2}\\right)\n\\end{array}\n\\end{equation}\n\nThe mass flow through that vertical line will require only the horizontal component of the velocity field $u$ at that point, meaning that we are only intereste in the real component of the function above:\n\n$u = -KI - \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{\\tfrac{r}{2}(1+f)}{\\tfrac{r^2}{4}-y^2}\\right) = -KI - \\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\left(\\dfrac{1}{\\tfrac{r^2}{4}-y^2}\\right) $\n\nThe mass flow will be described as:\n\n\\begin{equation}\n\\begin{array}{rl}\n \\int_{-\\infty}^{\\infty} u \\, dy =& \\int_{-\\infty}^{\\infty}\\left[ -KI - \\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\left(\\dfrac{1}{\\tfrac{r^2}{4}-y^2}\\right)\\right] \\, dy \\\\\n =& -\\underbrace{\\int_{-\\infty}^{\\infty}KI \\, dy}_{\\text{Diverges}} - \\underbrace{\\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\int_{-\\infty}^{\\infty}\\left(\\dfrac{1}{\\tfrac{r^2}{4}-y^2}\\right) \\, dy}_{\\text{Converges}}\\\\\n =& -\\int_{-\\infty}^{\\infty}KI \\, dy - \\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\left[ \\dfrac{2}{r} \\tan^{-1}{\\left(\\dfrac{2y}{r}\\right)}\\right]\\bigg\\rvert_{y \\to -\\infty}^{y \\to \\infty}\\\\\n =& -\\int_{-\\infty}^{\\infty}KI \\, dy - \\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\left[ \\dfrac{2\\pi}{r} \\right] \\\\\n =& -\\int_{-\\infty}^{\\infty}KI \\, dy - \\dfrac{Q_{\\rm in}(1+f)}{2 H}\n\\end{array}\n\\end{equation}\n\nThis end term, we can divide it by the lenght of the line $l_r$ in order to obtain a velocity, hence, the contribution from the wells are:\n\n\\begin{equation}\n\\begin{array}{rl}\n w'_{\\rm regional} =& -\\dfrac{1}{l_r}\\int_{-\\infty}^{\\infty}KI \\, dy \\\\\n w'_{\\rm wells} =& -\\dfrac{1}{2l_r}\\dfrac{Q_{\\rm in}(1+f)}{rH}\n\\end{array}\n\\end{equation}\n\n\n\n### Non-dimensional flow number ($\\mathcal{F}_L$)\n\nIn this case, this comparison don't make much sense as one of the integrals diverged. \n\n\\begin{equation}\n\\begin{array}{rl}\n\\mathcal{F}_L =& \\dfrac{\\text{Velocity due regional flow}}{\\text{Velocity due well couple}} \\\\\n=& \\dfrac{w'_{\\rm regional}}{w'_{\\rm wells}} \\\\\n=& \\dfrac{-\\dfrac{1}{l_r}\\int_{-\\infty}^{\\infty}KI \\, dy }{-\\dfrac{1}{2l_r}\\dfrac{Q_{\\rm in}(1+f)}{rH}} \\\\\n=& \\dfrac{2rH \\int_{-\\infty}^{\\infty}KI \\, dy}{Q_{in}(1+f)}\n\\end{array}\n\\end{equation}\n\nWe could infer that in this approach, the regional flow will always dwarf the potential induced by the pair of wells. But this is not useful for our purpose :(\n\n## Mass flow through an finite line\n\nIn order to obtain a convergent integral for the regional component, let's pick a vertical line that spans from $r/2(1-i)$ to $r/2(1+i)$, that way, the mass flow will be described as:\n\n\\begin{equation}\n\\begin{array}{rl}\n \\int_{-r/2}^{r/2} u \\, dy =& \\int_{-r/2}^{r/2}\\left[ -KI - \\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\left(\\dfrac{1}{\\tfrac{r^2}{4}-y^2}\\right)\\right] \\, dy \\\\\n =& \\int_{-r/2}^{r/2}KI \\, dy - \\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\int_{-r/2}^{r/2}\\left(\\dfrac{1}{\\tfrac{r^2}{4}-y^2}\\right) \\, dy\\\\\n =& -KIy\\bigg\\rvert_{y = -r/2}^{y = r/2} - \\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\left[ \\dfrac{2}{r} \\tan^{-1}{\\left(\\dfrac{2y}{r}\\right)}\\right]\\bigg\\rvert_{y = -r/2}^{y = r/2}\\\\\n =& -KIr - \\dfrac{Q_{\\rm in}r(1+f)}{4\\pi H} \\left[ \\dfrac{\\pi}{r} \\right] \\\\\n =& -KIr - \\dfrac{Q_{\\rm in}(1+f)}{4 H}\n\\end{array}\n\\end{equation}\n\nJusy as before, this end term can be divided by $r$ in order to obtain a velocity, hence, both contributions are:\n\n\\begin{equation}\n\\begin{array}{rl}\n w'_{\\rm regional} =& -KI \\\\\n w'_{\\rm wells} =& -\\dfrac{1}{4}\\dfrac{Q_{\\rm in}(1+f)}{rH}\n\\end{array}\n\\end{equation}\n\n\n### Non-dimensional flow number (2) ($\\mathcal{F}_L$)\n\nFrom this analysis we could also draw a comparison between the two contributors of the system:\n\n\\begin{equation}\n\\begin{array}{rl}\n\\mathcal{F}_L =& \\dfrac{\\text{Velocity due regional flow}}{\\text{Velocity due well couple}}\\\\\n=& \\dfrac{w'_{\\rm regional}}{w'_{wells}}\\\\\n=& \\dfrac{-KI}{-\\dfrac{Q_{\\rm in}}{4 H} \\left(\\dfrac{1+f}{r}\\right)} \\\\\n=& \\dfrac{4 K I H r}{Q_{in}(1+f)}\n\\end{array}\n\\end{equation}\n\nThere is not much of a difference in this \"more conservative\" approach, and it holds that if $\\mathcal{F}_L \\to 0$, the flow induced by the wells rule the system, whereas if $\\mathcal{F}_L \\to \\infty$, the regional flow rule the system. We well conserve the first non-dimensional flow number definition, i.e., \n\n\\begin{equation}\n\\mathcal{F}_L = \\dfrac{4 K I H r}{Q_{in}(1+f)}\n\\end{equation}\n\n## Characteristic velocity ($q_c$)\n\nWe found out before an expression for the velocity at the midpoint between the well couple. This will be used as our characteristic velocity, which can be rewritten in terms of the non-dimensional flow number:\n\n\\begin{equation}\n\\begin{array}{rl}\n q_c =& \\dfrac{1}{r}\\int_{-r/2}^{r/2}\\dfrac{dw}{dz}dy\\\\\n =& -KI - \\dfrac{Q_{\\rm in}(1+f)}{4 r H}\\\\\n =& -KI \\left( 1 + \\dfrac{1}{\\mathcal{F}_L} \\right)\\\\\n =& - KI \\left( \\dfrac{\\mathcal{F}_L}{\\mathcal{F}_L + 1} \\right)\n\\end{array}\n\\end{equation}\n\nThe actual pore-water velocity $u_c$ is found by dividing by the porosity $\\theta$\n\n\\begin{equation}\n\\begin{array}{rl}\n u_c =& \\dfrac{q_c}{\\theta}\\\\\n =& - \\dfrac{KI}{\\theta} \\left( \\dfrac{\\mathcal{F}_L}{\\mathcal{F}_L + 1} \\right)\n\\end{array}\n\\end{equation}\n\n## Flow time scale ($\\tau$)\nPicking the half-distance between the two wells as our characteristic lenght $r/2$, a characteristic time $\\tau$ can be derived from $u_c$\n\n\\begin{equation}\n\\begin{array}{rl}\n \\tau =& \\dfrac{r}{|u_c|}\\\\\n =& \\dfrac{r\\theta}{KI} \\left( \\dfrac{\\mathcal{F}_L + 1}{\\mathcal{F}_L} \\right)\\\\\n\\end{array}\n\\end{equation}\n\n## Decay rate and timescale comparison\n\nConsidering a tracer $C$ that is injected in the source point. This tracer follows a first-order decay reaction with a rate $\\lambda$. \n\n$\\dfrac{dC}{dt} = -\\lambda C$\n\nWith an initial condition $C(0) = C_0$, the concentration of that tracer as a function of space and time is,\n\n$C(t) = C_{0}\\exp{-\\lambda t}$\n\n$C_\\tau = C_0 \\exp{-\\lambda \\tau} = C_0 \\exp{\\left(-\\lambda\\dfrac{r}{|u_c|}\\right)}$\n\nHence, for our characteristic time ($t=\\tau$), the relative concentration of that tracer will be:\n\n$C_\\tau = C_0\\exp{ \\left( - \\lambda \\dfrac{r \\theta (\\mathcal{F}_L + 1)}{KI \\mathcal{F}_L} \\right) }$\n\n## Attachment rate\n\nConsidering a tracer $C$ that is injected in the source point. This tracer follows a first-order decay reaction with a rate $\\lambda$. \n\n\\begin{equation}\n\\begin{array}{rl}\n \\dfrac{dC}{dt} =& -k_{\\rm att} C\n\\end{array}\n\\end{equation}\n\n\\begin{equation}\n\\begin{array}{rl}\n k_{\\rm att} =& \\dfrac{3(1-\\theta)}{2d}\\alpha\\eta_0 |u_c|\\\\\n\\end{array}\n\\end{equation}\n\n- $d$ : collector diameter (soil grain size)\n- $\\alpha$ : collision/attachment efficiency\n- $\\eta_0$ : collector efficiency\n\nWith an initial condition $C(0) = C_0$, the concentration of that tracer as a function of space and time is,\n\n\\begin{equation}\n\\begin{array}{rl}\n C(t) =& C_{0}\\exp{(-k_{\\rm att} t)}\\\\\n C_\\tau =& C_{0}\\exp{(-k_{\\rm att} \\tau)}\\\\\n =& C_0 \\exp\\left(-\\dfrac{3(1-\\theta)}{2d}\\alpha\\eta_0 |u_c| \\dfrac{r}{\\theta |u_c|}\\right)\\\\\n =& C_0 \\exp\\left(-\\dfrac{3(1-\\theta)r}{2d\\theta}\\alpha\\eta_0\\right)\\\\\n\\end{array}\n\\end{equation}\n\n\n\n## Dilution effect\n\nAssuming that perfect mixing has between the injection point and the distance between the wells, we could calculate a relative concentration that takes into account this mass balance. Notice that this analysis cannot be done directly from our previous assumptions because there is no mixing in potential flow. However, we can keep the characteristic velocity.\n\n\\begin{equation}\n\\begin{array}{rl}\n C_0 u_c \\Delta y \\Delta z \\theta=& C_{\\rm in} Q_{\\rm in} + C_{\\rm reg} Q_{\\rm reg}\\\\\n C_0 u_c \\Delta y \\Delta z \\theta=& C_{\\rm in} Q_{\\rm in}\\\\\n C_0 =& \\dfrac{Q_{\\rm in}}{u_c \\Delta y \\Delta z \\theta} C_{in} \\\\\n =& \\dfrac{Q_{\\rm in}}{u_c \\Delta y \\Delta z \\theta} C_{\\rm in}\\\\\n =& \\dfrac{Q_{\\rm in}}{- \\dfrac{KI}{\\theta} \\left( \\dfrac{\\mathcal{F}_L}{\\mathcal{F}_L + 1} \\right) \\Delta y \\Delta z \\theta} C_{\\rm in}\\\\\n =& \\dfrac{Q_{\\rm in}(\\mathcal{F}_L + 1)}{KI \\mathcal{F}_L \\Delta y \\Delta z} C_{\\rm in}\n\\end{array}\n\\end{equation}\n\n$\\Delta y$ and $\\Delta z$ are just lenghts around the arbitrary control volume. For our 2D case, $\\Delta z = H$ and $\\Delta y = $ size of the element in PFLOTRAN\n\n$C_0 =\n\\dfrac{Q_{\\rm in}(\\mathcal{F}_L + 1)}{KI \\mathcal{F}_L \\Delta y H} C_{\\rm in}$\n\n### Which process is more dominant?\n\nThe effects of each process is more enhanced dependind of the system. For example, if $I$ is big, our characteristic time will be small, then, decay won't be as important as dilution could be in the aquifer. We are interested in finding which set of parameters maximize $C_\\tau$, or minimize the log-reductions of the tracer concentration.\n\n\\begin{equation}\n\\begin{array}{rl}\nC_\\tau =& C_0 \\exp{\\left(-\\left(\\lambda + k_{\\rm att}\\right)\\dfrac{r}{|u_c|}\\right)}\\\\\nC_\\tau =& \\dfrac{C_{\\rm in}Q_{\\rm in}}{u_c \\Delta y H \\theta} \\exp{\\left(-\\left(\\lambda + k_{\\rm att}\\right)\\dfrac{r}{|u_c|}\\right)}\n\\end{array}\n\\end{equation}\n\n# Potential flow visualization\n\n## Well flow is dominant \n\n\\begin{equation}\n\\begin{array}{rl}\n\\dfrac{dw}{dz} =& -KI - \\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{f}{z} - \\dfrac{1}{z-r}\\right)\\\\\n\\\\\n\\mathcal{F}_L =& \\dfrac{K I}{\\dfrac{Q_{\\rm in}}{2\\pi H} \\left(\\dfrac{f}{z} - \\dfrac{1}{z-r}\\right)}\n\\end{array}\n\\end{equation}\n\n\n```python\n%reset -f\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\ndef ZFix(x,y):\n XX,YY = np.meshgrid(X,Y)\n return XX + (YY*1j)\n \ndef regionalFlow():\n return -K*I\n\ndef wellFlow(z):\n w = -(QIN/(2*PI*H))*(F/z - 1/(z-R))\n wAbs = np.abs(w) \n return (w, w.real, -w.imag, wAbs)\n\ndef totalFlow(z):\n reg = regionalFlow()\n well = wellFlow(z)\n tot = reg + well[0]\n totAbs = np.abs(tot)\n return (tot, tot.real,-tot.imag,totAbs)\n\ndef flowNumber(z):\n reg = regionalFlow() \n well = wellFlow(z)[3]\n FL = np.abs(reg)/well\n return FL\n```\n\n\n```python\n''' GLOBAL CONSTANTS '''\nPI = 3.141592\nK = 1.0E-2\n#I = 6.6E-14\nI = 1.0E-10\nR = 40.\nF = 1.5\nQIN = 1.0/86400.\nH = 1\n#H = 20.\n\nPOINT_OUT = {\"x\":0,\n \"y\":0,\n \"c\":\"r\",\n \"s\":100,\n \"linewidths\":1,\n \"edgecolors\":\"w\",\n \"label\":\"Extraction\"}\n\nPOINT_QIN = {\"x\":R,\n \"y\":0,\n \"c\":\"b\",\n \"s\":80,\n \"linewidths\":1,\n \"edgecolors\":\"w\",\n \"label\":\"Injection\"}\n\nX = np.linspace(-50,150,151)\nY = np.linspace(-100,100,33)\nZ = ZFix(X,Y)\n_,U,V,C = totalFlow(Z)\nFL = flowNumber(Z)\n\nfig, axs = plt.subplots(2,1,figsize=(12,10))\nax = axs[0]\nst = ax.streamplot(X,Y,U,V,color=\"k\",density=[0.8, 0.8])\nfi = ax.pcolormesh(X,Y,C,shading='auto',vmin=0,vmax=5.0E-7,cmap=\"cool\")\npi = ax.scatter(**POINT_QIN,zorder=3)\npo = ax.scatter(**POINT_OUT,zorder=3)\n\ncbar = ax.figure.colorbar(fi,ax=ax,orientation=\"vertical\")\ncbar.set_label(r'$\\bf{|U|}$')\n\nax.legend(loc='lower right')\n\nax = axs[1]\nfi = ax.pcolormesh(X,Y,np.log10(FL),shading='auto')\npi = ax.scatter(**POINT_QIN)\npo = ax.scatter(**POINT_OUT)\n\nax.xaxis.set_tick_params(which=\"both\",labelbottom=False,bottom=False)\nax.yaxis.set_tick_params(which=\"both\",labelleft=False,left=False)\ncbar = ax.figure.colorbar(fi,ax=ax,orientation=\"vertical\")\nax.legend(loc='lower right')\n\nplt.show()\n```\n\n\n```python\nX = np.linspace(0.01,R-0.01,151)\nY = np.array([0.])\nZ = ZFix(X,Y)\n_,U,V,C = totalFlow(Z)\nFL = flowNumber(Z)\nfig, axs = plt.subplots(2,1,figsize=(8,6),sharex=True,\\\n gridspec_kw={\"height_ratios\":[3,1],\"hspace\":0})\nax = axs[0]\nli = ax.plot(X,C[0],lw=5)\nax.set(xlim=[0,R],ylim=[0,1.0E-6],ylabel=r\"$\\bf{|U|}$ [m/s]\")\n\nax = axs[1]\nli = ax.plot(X,np.log10(FL[0]),lw=3,c=\"gray\")\nax.set(ylim=[-7.5,-4.5],xlabel=r\"$\\bf{X}$ [m]\",ylabel=r\"$\\bf{\\log(\\mathcal{F}_L)}$\")\n\nplt.show()\n```\n\n## Regional flow is dominant\n\n\n```python\n%reset -f\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\ndef ZFix(x,y):\n XX,YY = np.meshgrid(X,Y)\n return XX + (YY*1j)\n \ndef regionalFlow():\n return -K*I\n\ndef wellFlow(z):\n w = -(QIN/(2*PI*H))*(F/z - 1/(z-R))\n wAbs = np.abs(w) \n return (w, w.real, -w.imag, wAbs)\n\ndef totalFlow(z):\n reg = regionalFlow()\n well = wellFlow(z)\n tot = reg + well[0]\n totAbs = np.abs(tot)\n return (tot, tot.real,-tot.imag,totAbs)\n\ndef flowNumber(z):\n reg = regionalFlow() \n well = wellFlow(z)[3]\n FL = np.abs(reg)/well\n return FL\n```\n\n\n```python\n''' GLOBAL CONSTANTS '''\nPI = 3.141592\nK = 1.0E-2\nI = 6.6E-4\nR = 40.\nF = 10\nQIN = 1.0/86400.\nH = 20.\n\nPOINT_OUT = {\"x\":0,\n \"y\":0,\n \"c\":\"r\",\n \"s\":100,\n \"linewidths\":1,\n \"edgecolors\":\"w\",\n \"label\":\"Extraction\"}\n\nPOINT_QIN = {\"x\":R,\n \"y\":0,\n \"c\":\"b\",\n \"s\":80,\n \"linewidths\":1,\n \"edgecolors\":\"w\",\n \"label\":\"Injection\"}\n\nX = np.linspace(-50,150,151)\nY = np.linspace(-100,100,33)\nZ = ZFix(X,Y)\n_,U,V,C = totalFlow(Z)\nFL = flowNumber(Z)\n\nfig, axs = plt.subplots(2,1,figsize=(12,10))\nax = axs[0]\nst = ax.streamplot(X,Y,U,V,color=\"k\",density=[0.8, 0.8])\nfi = ax.pcolormesh(X,Y,C,shading='auto',vmin=0,vmax=2.0E-5,cmap=\"cool\")\npi = ax.scatter(**POINT_QIN,zorder=3)\npo = ax.scatter(**POINT_OUT,zorder=3)\n\ncbar = ax.figure.colorbar(fi,ax=ax,orientation=\"vertical\")\ncbar.set_label(r'$\\bf{|U|}$')\n\nax.legend(loc='lower right')\n\nax = axs[1]\nfi = ax.pcolormesh(X,Y,np.log10(FL),shading='auto')\npi = ax.scatter(**POINT_QIN)\npo = ax.scatter(**POINT_OUT)\n\nax.xaxis.set_tick_params(which=\"both\",labelbottom=False,bottom=False)\nax.yaxis.set_tick_params(which=\"both\",labelleft=False,left=False)\ncbar = ax.figure.colorbar(fi,ax=ax,orientation=\"vertical\")\nax.legend(loc='lower right')\n\nplt.show()\n```\n\n\n```python\nX = np.linspace(0.01,R-0.01,151)\nY = np.array([0.])\nZ = ZFix(X,Y)\n_,U,V,C = totalFlow(Z)\nFL = flowNumber(Z)\nfig, axs = plt.subplots(2,1,figsize=(8,6),sharex=True,\\\n gridspec_kw={\"height_ratios\":[3,1],\"hspace\":0})\nax = axs[0]\nli = ax.plot(X,C[0],lw=5)\nax.set(xlim=[0,R],ylim=[0,1.0E-5],ylabel=r\"$\\bf{|U|}$ [m/s]\")\n\nax = axs[1]\nli = ax.plot(X,np.log10(FL[0]),lw=3,c=\"gray\")\nax.set(xlabel=r\"$\\bf{X}$ [m]\",ylabel=r\"$\\bf{\\log(\\mathcal{F}_L)}$\")\nax.yaxis.set_tick_params(which=\"both\",labelright=True,right=True,labelleft=False,left=False)\n\nplt.show()\n```\n", "meta": {"hexsha": "c65f5f9dc726ee4a1775102ca784729200d50688", "size": 258811, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/Concepts/Potential flow.ipynb", "max_stars_repo_name": "edsaac/bioparticle", "max_stars_repo_head_hexsha": "67e191329ef191fc539b290069524b42fbaf7e21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/Concepts/Potential flow.ipynb", "max_issues_repo_name": "edsaac/bioparticle", "max_issues_repo_head_hexsha": "67e191329ef191fc539b290069524b42fbaf7e21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-25T23:31:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T23:31:21.000Z", "max_forks_repo_path": "notebooks/Concepts/Potential flow.ipynb", "max_forks_repo_name": "edsaac/VirusTransport_RxSandbox", "max_forks_repo_head_hexsha": "67e191329ef191fc539b290069524b42fbaf7e21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-30T05:00:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T05:00:58.000Z", "avg_line_length": 298.1693548387, "max_line_length": 128672, "alphanum_fraction": 0.9058347597, "converted": true, "num_tokens": 8452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9777138170582865, "lm_q2_score": 0.92522995296862, "lm_q1q2_score": 0.9046101089736084}}
{"text": "# Maximising the volume of a box\n\nLet us consider a sheet of metal of dimensions $l\\times L$\n\n\n\nWe can cut in to the sheet of metal a distance $x$ to create folds.\n\n\n\nThe volume of a box with these folds will be given by:\n\n$V(x) = (l - 2x)\\times (L-2x) \\times x$\n\nIn this notebook we will use calculus (the study of continuous change) and `sympy` to identify the size of the cut to give the biggest volume.\n\n## Defining a function\n\nTo help with writing our code, we will start by defining a python function for our volume.\n\n\n```python\nimport sympy as sym\nsym.init_printing()\nx, l, L = sym.symbols(\"x, l, L\")\n\ndef V(x=x, l=l, L=L):\n \"\"\"\n Return the volume of a box as described.\n \"\"\"\n return (l - 2 * x) * (L - 2 * x) * x\n```\n\n\n```python\nV()\n```\n\nWe can use this function to get our value as a function of $L$ and $l$:\n\n\n```python\nV(x=2)\n```\n\nOr we can pass values to all our variables and obtain a given volume:\n\n\n```python\nV(2, l=12, L=14)\n```\n\n### Exercises\n\n- Define the mathematical function $m x ^ 2 - w$\n\n## Plotting our function\n\nLet us start by looking at the volume as a function of $x$ for the following values of $l=20$ and $L=38$:\n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nsym.plot(V(x,l=20, L=38), (x, 0, 10)); # We only consider x < min(l, L) / 2\n```\n\nWe see that our function has one stationary points (where the graph is flat).\n\n### Exercises\n\n- Obtain a plot of $V(x)$ for $0\\leq x \\leq 20$\n- Obtain a plot of the function $f(x) = x ^ 2$\n- Obtain a plot of the function $f(x) = 1 / x$\n\n## Finding stationary points\n\nThese stationary points correspond to places where the derivative of the function is 0:\n\n$$\n\\frac{dV}{dx}=0\n$$\n\nLet us find the $\\frac{dV}{dx}$ using `sympy`:\n\n\n```python\nfirst_derivative = V().diff(x)\nfirst_derivative\n```\n\nLet us simplify our output:\n\n\n```python\nfirst_derivative = first_derivative.simplify()\nfirst_derivative\n```\n\nNow to find the solutions to the equation: \n\n$$\\frac{dV}{dx}=0$$\n\n\n```python\nstationary_points = sym.solveset(first_derivative, x)\nstationary_points\n```\n\n### Exercises\n\n- Find the stationary points of $f(x)=x^2$\n- Find the stationary points of $f(x)=mx^2-w$\n\n## Qualifying stationary points\n\nAs we can see in our graph, one of our stationary points is a maximum and the other a minumum. These can be quantified by looking at the second derivative:\n\n- If the second derivative at a stationary point is **positive** then the stationary point is a **local minima**;\n- If the second derivative at a stationary point is **negative** then the stationary point is a **local maxima**.\n\nLet us compute the second derivative using `sympy`:\n\n\n```python\nsecond_derivative = V().diff(x, 2)\nsecond_derivative\n```\n\n\n```python\nstationary_points\n```\n\n\n```python\nsecond_derivative_values = [(sol, second_derivative.subs({x: sol})) for sol in stationary_points]\nsecond_derivative_values\n```\n\nWe can see that the first solution gives a negative second derivative thus it's a **local** maximum (as we saw in our plot).\n\n\n```python\noptimal_x = second_derivative_values[0][0]\noptimal_x\n```\n\nWe can compute the actual value for the running example:\n\n\n```python\nparticular_values = {\"l\": 20, \"L\": 38}\nparticular_optimal_x = optimal_x.subs(particular_values)\nfloat(particular_optimal_x), float(V(particular_optimal_x, **particular_values))\n```\n\n### Exercises\n\n- Qualify the stationary points of $f(x)=x^2$\n- Qualify the stationary points of $f(x)=mx^2-w$\n", "meta": {"hexsha": "c5e37815db13c0a95cda42a4d0dea4fb481da5ac", "size": 48331, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "nbs/02-calculus-maximising-volume-of-a-box.ipynb", "max_stars_repo_name": "drvinceknight/mwp", "max_stars_repo_head_hexsha": "51bb5aa699788445f1dd710ee4c7535121f1d60d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nbs/02-calculus-maximising-volume-of-a-box.ipynb", "max_issues_repo_name": "drvinceknight/mwp", "max_issues_repo_head_hexsha": "51bb5aa699788445f1dd710ee4c7535121f1d60d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-02-17T16:36:11.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-19T15:01:53.000Z", "max_forks_repo_path": "nbs/02-calculus-maximising-volume-of-a-box.ipynb", "max_forks_repo_name": "drvinceknight/mwp", "max_forks_repo_head_hexsha": "51bb5aa699788445f1dd710ee4c7535121f1d60d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-02-19T13:48:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:42:08.000Z", "avg_line_length": 90.8477443609, "max_line_length": 16960, "alphanum_fraction": 0.8279365211, "converted": true, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9591542852576265, "lm_q2_score": 0.9425067195846918, "lm_q1q2_score": 0.9040093589737652}}
{"text": "# Local Minima for a function of Two Variables Using Optimality Conditions\n\nFind a local minimum point for the funtion:\n$$ f(x) = x_1 + \\frac{(4\\times 10^6)}{x_1 x_2} + 250x_2$$\n\nSee reference for details.\n\n## Solution\n\n\n```python\nimport sympy as sp\nimport numpy as np\nfrom scipy import linalg\nfrom symopt import DiffNotation\n```\n\n\n```python\nx1, x2 = sp.symbols(['x1', 'x2'])\n```\n\n\n```python\nfx = x1 + (4*10**6) / (x1*x2) + 250*x2\nfx\n```\n\n\n\n\n$\\displaystyle x_{1} + 250 x_{2} + \\frac{4000000}{x_{1} x_{2}}$\n\n\n\n\n```python\n# Necessary conditions\nd1 = DiffNotation(fx, x1, x2)\ngrad_f = d1.gradient()\ngrad_f\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 - \\frac{4000000}{x_{1}^{2} x_{2}}\\\\250 - \\frac{4000000}{x_{1} x_{2}^{2}}\\end{matrix}\\right]$\n\n\n\n\n```python\n# The solution of the system gives the stationary points of the function\nsp.nonlinsolve(grad_f, (x1, x2))\n```\n\n\n\n\n$\\displaystyle \\left\\{\\left( 1000, \\ 4\\right), \\left( -500 - 500 \\sqrt{3} i, \\ -2 - 2 \\sqrt{3} i\\right), \\left( -500 + 500 \\sqrt{3} i, \\ -2 + 2 \\sqrt{3} i\\right)\\right\\}$\n\n\n\n\n```python\n# The Hessian of fx is a suficient condition of minimum if it is defined positive\nhess_f = d1.hessian()\nhess_f\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{8000000}{x_{1}^{3} x_{2}} & \\frac{4000000}{x_{1}^{2} x_{2}^{2}}\\\\\\frac{4000000}{x_{1}^{2} x_{2}^{2}} & \\frac{8000000}{x_{1} x_{2}^{3}}\\end{matrix}\\right]$\n\n\n\n\n```python\n# we check the eigenvalues of the hessian at the stationary point (1000, 4)\nhess_f_values = np.array(\n hess_f.subs(x1, 1000).subs(x2, 4),\n dtype=float\n)\nlinalg.eig(hess_f_values)\n```\n\n\n\n\n (array([1.499994e-03+0.j, 1.250005e+02+0.j]),\n array([[-0.999998 , -0.00200002],\n [ 0.00200002, -0.999998 ]]))\n\n\n\nEigenvalues positive implies that (1000, 4) is a point of minimum\n\n## Contour plot\n\n\n```python\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib.mlab as mlab\n\n%matplotlib notebook\n```\n\n\n```python\n# Contornos\nx1_arr = np.linspace(500, 3000, 1000)\nx2_arr = np.linspace(2, 14, 1000)\nx1_mesh, x2_mesh = np.meshgrid(x1_arr, x2_arr)\nfx_mesh = [[x1_ + (4*10**6) / (x1_*x2_) + 250*x2_ \n for x1_ in x1_arr] \n for x2_ in x2_arr]\nfx_mesh = np.array(fx_mesh)\n```\n\n\n```python\nplt.figure()\nCS1 = plt.contour(x1_mesh, x2_mesh, fx_mesh, 10)\nplt.clabel(CS1, fontsize=9, inline=1)\norigin = (1000, 4)\nCS2 = plt.plot(*origin, 'ro',label='optimum')\n\nplt.xlabel('x1')\nplt.ylabel('x2')\nplt.legend()\nplt.grid()\nplt.show()\n#https://matplotlib.org/2.0.2/examples/pylab_examples/contour_demo.html\n#https://www.tutorialspoint.com/how-to-plot-vectors-in-python-using-matplotlib\n```\n\n\n <IPython.core.display.Javascript object>\n\n\n\n\n\n\n\n```python\n# The minimum is\nfx.subs(x1, 1000).subs(x2, 4)\n```\n\n\n\n\n$\\displaystyle 3000$\n\n\n\nReference\n========\n[1] ARORA, Jasbir S. Introduction to Optimum Design. Elservie. 2nd ed. Example 4.23 from page 115.\n", "meta": {"hexsha": "0647f6f88e17c52aed419039fb2d9bea1c1b2f9e", "size": 185395, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/notebooks/Local_Minima.ipynb", "max_stars_repo_name": "rafaelpsilva07/symopt", "max_stars_repo_head_hexsha": "0f3e4597c5f4e1956c792154a551af4f5339bd82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-03-13T23:28:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T18:14:13.000Z", "max_issues_repo_path": "docs/notebooks/Local_Minima.ipynb", "max_issues_repo_name": "rafaelpsilva07/symopt", "max_issues_repo_head_hexsha": "0f3e4597c5f4e1956c792154a551af4f5339bd82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/notebooks/Local_Minima.ipynb", "max_forks_repo_name": "rafaelpsilva07/symopt", "max_forks_repo_head_hexsha": "0f3e4597c5f4e1956c792154a551af4f5339bd82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 141.4149504195, "max_line_length": 132095, "alphanum_fraction": 0.8266727797, "converted": true, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9626731147976794, "lm_q2_score": 0.9390248135892423, "lm_q1q2_score": 0.903973942170266}}
{"text": "# Calculating the Mass of The Sun\n\nOne of the most important relationships in astronomy is Kepler's laws of planetary motion, because they allow us to use orbits to calculate the masses of astronomical objects. Of particular use is Kepler's third law, which relates the period, separation, and masses of two objects:\n\n\\begin{equation}\nP^2 = \\frac{4 \\pi^2}{G (m_1 + m_2)} a^3\n\\end{equation}\n\nHere $G$ is the gravitational constant, $m_1$ and $m_2$ are the masses of the two bodies orbiting eachother, $P$ is the period of their orbit, and $a$ is the distance between them. In the case of our Solar System, because the mass of the Sun is significantly greater than the mass of any of the planets (i.e. $m_1 + m_2 \\approx m_1$), this can be reduced to:\n\n\\begin{equation}\nP^2 = \\frac{4 \\pi^2}{G \\, M} a^3\n\\end{equation}\n\nBecause we know the periods and distances for all of the planets, we can use those values to calculate the mass of the body that they are orbiting, i.e the Sun.\n\nFirst, pick your favorite planet. Look up their orbital period and the distance from the Sun (i.e. their \"semi-major axis\"). You will also need to look up the value of the gravitational constant, $G$. Make sure to check your units! Define those as variables here:\n\n\n```python\n\n```\n\nNow, using the above equation, calculate the mass of the Sun:\n\n\n```python\n\n```\n\nUse what you know about string formatting to print out the mass you calculated with nice formatting, including units:\n\n\n```python\n\n```\n\nJust to make sure we did that correctly, pick your second favorite planet, and repeat. Do you get the same answer?\n\n\n```python\n\n```\n\nKepler's laws are universal, so they don't just work for the Sun, but can be used to measure the mass of anything, if there's something orbiting it. Let's try measuring the mass of Jupiter. Look up the separation and period of Jupiter's moon, Callisto, and use Kepler's third law to calculate the mass of Jupiter in the same way:\n\n\n```python\n\n```\n\nFinally, astronomers think there is a *supermassive black hole* at the center of our Milky Way galaxy. Why is that? Well, we've been able to watch stars orbit something at the center of our Galaxy:\n\n\n\nHow massive is the object that they are orbiting? Look-up the period and distance (i.e. semi-major axis) of the star \"S2\", and calculate the mass of that object (*Hint1: Wikipedia knows about this star. Hint 2: The units '\"', or arcseconds, that are listed there for the semi-major axis can be converted into a more useful number by multiplying by the distance to the source. What is a \"pc\"?*):\n\n\n```python\n\n```\n\nHow does the mass you measured compare with the mass of our Sun:\n\n\n```python\n\n```\n\nOften in astronomy we will list measured masses in terms of the mass of the Sun, because units of grams or kilograms are not easy to interpret when the numbers are so large. Use string formatting to display the mass of the object at the center of our Solar System in terms of the number of \"Solar masses\" that it is, with the proper units:\n\n\n```python\n\n```\n", "meta": {"hexsha": "eac4e14c3c08dd21ec712496c81bd8a70ec99e2f", "size": 5191, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "BonusProblems/Module1/BonusChallenge2.ipynb", "max_stars_repo_name": "psheehan/CIERA-HS-Program", "max_stars_repo_head_hexsha": "76f7f0ff994e74e646fa34bbb41c314bf7526e9b", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-06-25T02:36:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T21:44:41.000Z", "max_issues_repo_path": "BonusProblems/Module1/BonusChallenge2.ipynb", "max_issues_repo_name": "psheehan/CIERA-HS-Program", "max_issues_repo_head_hexsha": "76f7f0ff994e74e646fa34bbb41c314bf7526e9b", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BonusProblems/Module1/BonusChallenge2.ipynb", "max_forks_repo_name": "psheehan/CIERA-HS-Program", "max_forks_repo_head_hexsha": "76f7f0ff994e74e646fa34bbb41c314bf7526e9b", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-06-25T15:33:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T18:04:36.000Z", "avg_line_length": 31.8466257669, "max_line_length": 405, "alphanum_fraction": 0.6158736274, "converted": true, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9702399077750858, "lm_q2_score": 0.9304582521195071, "lm_q1q2_score": 0.9027677287249981}}
{"text": "# 2.2 矩阵乘法\n\n两个矩阵相乘得到第三个矩阵:\n\n$$\n\\bf C=AB\n$$\n\n为了使得定义合法,我们需要 $\\mathbf A$ 的形状为 $m\\times n$, $\\mathbf B$ 的形状为 $n\\times p$,得到的矩阵为 $\\mathbf C$ 的形状为 ${m\\times p}$。\n\n定义为\n\n$$\nC_{i,j} = \\sum_{k} A_{i,k}B_{k,j}\n$$\n\n注意矩阵乘法不是逐元素相乘,逐元素相乘又叫 `Hadamard` 乘积,记作 $\\bf A\\odot B$。\n\n向量可以看出是列为 $1$ 的矩阵,两个相同大小的向量 $\\bf x, y$ 的点乘(`dot product`)或者内积,可以使用矩阵乘法表示为 $\\bf x^\\top y$。\n\n我们也可以把矩阵乘法理解为: $C_{i,j}$ 表示 $\\bf A$ 的第 $i$ 行与 $\\bf B$ 的第 $j$ 列的点乘。\n\n### 矩阵乘法的性质\n\n矩阵乘法满足结合律(`associative`)和分配律(`distributive`):\n\n$$\n\\begin{align}\n\\bf A(B+C)&=\\bf AB+AC \\\\\n\\bf A(BC)&=\\bf (AB)C\n\\end{align}\n$$\n\n矩阵乘法通常是不可交换的:\n\n$$\n\\bf AB \\neq BA\n$$\n\n但是向量内积是可交换的:\n\n$$\n\\bf x^\\top y = y^\\top x\n$$\n\n矩阵乘法的转置形式如下:\n\n$$\n\\bf (AB)^\\top = B^\\top A^\\top\n$$\n\n利用这个式子和标量转置等于其本身,我们马上得到内积是可交换的结论:\n\n$$\n\\bf x^\\top y = (x^\\top y)^\\top = y^\\top x\n$$\n\n### 线性方程组\n\n线性方程组可以表示为矩阵和向量乘法的形式:\n\n$$\n\\bf Ax = b\n$$\n\n其中 $\\mathbf A\\in\\mathbb R^{m\\times n}, \\mathbf b\\in\\mathbb R^{m}$ 是已知的,$\\mathbf x\\in\\mathbb R^{n}$ 是我们要求的未知量。\n\n它是线性方程组的一种紧凑表示:\n\n$$\n\\begin{align}\n\\mathbf A_{1,:} \\mathbf x&=b_1 \\\\\n\\mathbf A_{2,:} \\mathbf x&=b_2 \\\\\n\\dots &\\\\\n\\mathbf A_{m,:} \\mathbf x&=b_m \\\\\n\\end{align}\n$$\n", "meta": {"hexsha": "686cced04a5d62bbe8c50ee126e3ae3b30c39af4", "size": 2685, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Deep-Learning/Part-I/Chap-02-Linear-Algebra/02-02-Multiplying-Matrices-and-Vectors.ipynb", "max_stars_repo_name": "binzhihao/py-ai-notebook", "max_stars_repo_head_hexsha": "31560c7cbd3d6d123e310cda4080d40e5e2b23ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-30T13:34:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-21T07:31:14.000Z", "max_issues_repo_path": "Deep-Learning/Part-I/Chap-02-Linear-Algebra/02-02-Multiplying-Matrices-and-Vectors.ipynb", "max_issues_repo_name": "binzhihao/py-ai-notebook", "max_issues_repo_head_hexsha": "31560c7cbd3d6d123e310cda4080d40e5e2b23ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Deep-Learning/Part-I/Chap-02-Linear-Algebra/02-02-Multiplying-Matrices-and-Vectors.ipynb", "max_forks_repo_name": "binzhihao/py-ai-notebook", "max_forks_repo_head_hexsha": "31560c7cbd3d6d123e310cda4080d40e5e2b23ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0373134328, "max_line_length": 128, "alphanum_fraction": 0.425698324, "converted": true, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799425745087, "lm_q2_score": 0.9362850070814366, "lm_q1q2_score": 0.9023727103583205}}
{"text": "## Exercise:\n\nThis example is sourced from the [Scipy website](https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/) where you can find more details. For more on these models and their variations, see [Compartmental models in epidimiology, Wikipedia](https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology).\n\nNumerically solve the SIR epidemic model:\n\n1. In pure Python using for loops to integrate in time.\n1. Using Scipy's odeint package. \n\nThe differential equations that describe the model are:\n\n\\begin{equation}\n\\frac{dS}{dt} = \\frac{-\\beta I S}{N}\n\\end{equation}\n\n\\begin{equation}\n\\frac{dI}{dt} = \\frac{\\beta I S}{N} - \\gamma I\n\\end{equation}\n\n\\begin{equation}\n\\frac{dR}{dt} = \\gamma I\n\\end{equation}\n\nWhere S are the susceptible numbers in the population, I is the number of infected, R is the number of recovered persons in the population. $\\beta$ is the *effective contact rate*, that is, an infected individual comes into contact with $\\beta N$ individuals. $\\gamma$ is the mean recovery rate: $1/\\gamma$ is the mean period of time that an individual can pass on the infection.\n\nA vitally important number to keep track of is the ratio: $R_0 = \\beta/\\gamma$; when $R_0 \\gt 1$, the disease spreads through the population, when $R_0 \\lt 1$, the disease quickly dies out.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\n\n```python\nN = 1000\nRec0 = 0\nInf0 = 1\nSus0 = N - Inf0\n```\n\n\n```python\nbeta = 0.2\ngamma = 0.1\nR0 = beta/gamma\n```\n\n\n```python\nR0\n```\n\n\n\n\n 2.0\n\n\n\n\n```python\nSus = [Sus0]\nRec = [Rec0]\nInf = [Inf0]\nfor t in range(150):\n delta_S = -beta * Inf[-1] * Sus[-1] / N\n Sus.append(Sus[-1]+delta_S)\n \n delta_I = beta * Inf[-1] * Sus[-1] / N - gamma * Inf[-1]\n Inf.append(Inf[-1] + delta_I)\n \n delta_R = gamma * Inf[-1]\n Rec.append(Rec[-1] + delta_R)\n #print(delta_S, delta_I, delta_R)\n```\n\n\n```python\nSus = np.array(Sus)\nRec = np.array(Rec)\nInf = np.array(Inf)\n```\n\n\n```python\nplt.plot(np.arange(151), Sus, label=\"Susceptible\")\nplt.plot(np.arange(151), Rec, label=\"Recovered\")\nplt.plot(np.arange(151), Inf, label=\"Infected\")\nplt.legend()\n```\n\n### Exercise 07: SIR model in scipy\n\nUse scipy.integrate.odeint to solve the SIR model. For more information, refer to the [documentation page](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html).\n\n\n```python\n# %load ./solutions/sol_scipy_SIR.py\n```\n", "meta": {"hexsha": "35c5fd73b1bf49625a466a96ad1d9a4fe549b7c3", "size": 27248, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "04_Numpy_SIR.ipynb", "max_stars_repo_name": "adityarn/MAV110_PythonModule", "max_stars_repo_head_hexsha": "c3ee6457ba0e4d2cae04f3f6a138d0b473bb4f8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-11-25T13:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T13:08:30.000Z", "max_issues_repo_path": "04_Numpy_SIR.ipynb", "max_issues_repo_name": "adityarn/MAV110_PythonModule", "max_issues_repo_head_hexsha": "c3ee6457ba0e4d2cae04f3f6a138d0b473bb4f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "04_Numpy_SIR.ipynb", "max_forks_repo_name": "adityarn/MAV110_PythonModule", "max_forks_repo_head_hexsha": "c3ee6457ba0e4d2cae04f3f6a138d0b473bb4f8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 132.2718446602, "max_line_length": 22108, "alphanum_fraction": 0.8823766882, "converted": true, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9539660976007596, "lm_q2_score": 0.9458012659756293, "lm_q1q2_score": 0.9022623428086292}}
{"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom numpy.linalg import inv\nfrom numpy import matmul as mm\n```\n\n- Dataset $\\mathcal{D}=\\{x_i,y_i\\}^N_{i=1}$ of N pairs of inputs $x_i$ and targets $y_i$. This data can be measurements in an experiment.\n- Goal: predict target $y_*$ associated to any arbitrary input $x_*$. This is known as a **regression** task in machine learning.\n\n### Generate Dataset\n$$y_i = (x_i+1)^3+\\epsilon_i$$\nwhere $\\epsilon_i \\sim \\mathcal{N}(0,1)$\n\n\n```python\nx = np.linspace(-4,2,20)\ny = (x+1)**3+10*np.random.normal(0,1,20)\n```\n\n\n```python\nplt.plot(x,y,'b.')\n```\n\n### Model of the data\nAssume that the dataset can be fit with a $M^{th}$ order polynomial (**polynomial regression**),\n\n$$f_w(x) = w_0+w_1x+w_2x^2+w_3x^3+...+w_Mx^M=\\sum^M_{j=1}w_j\\phi_j(x)$$\nThe $w_j$ are the weights of the polynomial, the parameters of the model, and $\\phi_j(x)$ is a basis function of our linear in the parameters model.\n\n### Fitting model parameters via the least squares approach\n- Measure the quality of the fit to the training data.\n- For each train point, measure the squared error $e^2_i = (y_i-f(x_i))^2$.\n- Find the parameters that minimize the sum of squared errors:\n\n$$E(\\mathbf{w})=\\sum^N_{i=1}e^2_i=\\|\\mathbf{e}\\|^2 = \\mathbf{e}^\\top\\mathbf{e}=(\\mathbf{y}-\\mathbf{f})^\\top(\\mathbf{y}-\\mathbf{f})$$\nwhere $\\mathbf{y} = [y_1,...y_N]^\\top$ is a vector that stacks the N training targets, $\\mathbf{f}=[f_\\mathbf{W}(x_1),...,f_\\mathbf{w}(x_N)]^\\top$ stacks the prediction evaluated at the N training inputs.\n\nTherefore, \n\n\\begin{align}\n\\mathbf{y}&=\\mathbf{f}+\\mathbf{e}=\\mathbf{\\Phi w}+\\mathbf{e} \\\\\n\\begin{pmatrix} y_1\\\\y_2\\\\\\vdots\\\\y_N\\end{pmatrix}&=\\begin{pmatrix}1&x_1&x_1^2&...&x_1^M\\\\1&x_2&x_2^2&...&x_2^M\\\\\\vdots&\\vdots&\\vdots&\\cdots&\\vdots\\\\1&x_N&x_N^2&...&x_N^M\\end{pmatrix}\\begin{pmatrix}w_0\\\\w_1\\\\\\vdots\\\\w_M\\end{pmatrix} + \\mathbf{e}\n\\end{align}\n\n\nThe sum of squared errors is a convex function of $\\mathbf{w}$: \n\n$$E(\\mathbf{w})=(\\mathbf{y}-\\mathbf{\\Phi w})^\\top(\\mathbf{y}-\\mathbf{\\Phi w})$$\nTo minimize the errors, find the weight vector $\\mathbf{\\hat{w}}$ that sets the gradient with respect to the weights to zero, \n\n$$\\frac{\\partial E(\\mathbf{w})}{\\partial \\mathbf{w}}=-2\\mathbf{\\Phi}^\\top(\\mathbf{y}-\\mathbf{\\Phi w})=2\\mathbf{\\Phi^\\top\\Phi w}-2\\mathbf{\\Phi}^\\top \\mathbf{y}=0$$\n\nThe weight vector is \n\n$$\\mathbf{\\hat{w}}=(\\mathbf{\\Phi^\\top\\Phi})^{-1}\\mathbf{\\Phi^\\top y}$$\n\n\n```python\ndef polynomialFit(x,y,order=3):\n for i in range(order+1):\n if i == 0:\n Phi = x**i\n else:\n Phi = np.vstack((Phi,x**i))\n Phi = Phi.T\n if order == 0:\n Phi = Phi.reshape(-1,1)\n w = mm(mm(inv(mm(Phi.T,Phi)),Phi.T),y)\n f = mm(Phi,w)\n dif = y-f\n err = mm(dif.T,dif)\n return f,err,w,Phi\n```\n\n\n```python\nf,err,w,Phi = polynomialFit(x,y)\n```\n\n\n```python\nplt.plot(x,y,'b.')\nplt.plot(x,f,'r-')\nprint(w) # ideal: 1,3,3,1\nprint(err)\n```\n\n### M-th order Polynomial\n\n\n```python\nerrlist = []\nplt.figure(figsize=(20,20))\nfor i in range(21):\n plt.subplot(7,3,i+1)\n f,err,w,Phi = polynomialFit(x,y,i)\n errlist.append(err)\n plt.plot(x,y,'b.')\n plt.plot(x,f,'r-')\n plt.title('Order '+str(i)+': '+str(err))\n```\n\n\n```python\nplt.plot(np.arange(16),errlist[:16])\n```\n\n#### The fitting becomes very unstable after the order of 15. This may be due to the inverse instability. This can be resolved via LU decomposition, Cholesky decomposition or QR decomposition.\n\n### LU decomposition\n\n\n```python\nimport scipy\nfrom scipy.linalg import lu_factor,lu_solve\n```\n\n\n```python\ndef polynomialFitLU(x,y,order=3):\n for i in range(order+1):\n if i == 0:\n Phi = x**i\n else:\n Phi = np.vstack((Phi,x**i))\n Phi = Phi.T\n if order == 0:\n Phi = Phi.reshape(-1,1)\n lu,piv = lu_factor(mm(Phi.T,Phi))\n tmp = lu_solve((lu,piv),Phi.T)\n w = mm(tmp,y)\n f = mm(Phi,w)\n dif = y-f\n err = mm(dif.T,dif)\n return f,err,w,Phi\n```\n\n\n```python\nerrlistLU = []\nplt.figure(figsize=(20,20))\nfor i in range(21):\n plt.subplot(7,3,i+1)\n f,err,w,Phi = polynomialFitLU(x,y,i)\n errlistLU.append(err)\n plt.plot(x,y,'b.')\n plt.plot(x,f,'r-')\n plt.title('Order '+str(i)+': '+str(err))\n```\n\n\n```python\nplt.plot(np.arange(21),errlistLU)\n```\n\n### Cholesky decomposition\n\n\n```python\nfrom scipy.linalg import cho_factor,cho_solve\n```\n\n\n```python\ndef polynomialFitChol(x,y,order=3):\n for i in range(order+1):\n if i == 0:\n Phi = x**i\n else:\n Phi = np.vstack((Phi,x**i))\n Phi = Phi.T\n if order == 0:\n Phi = Phi.reshape(-1,1)\n c,low = cho_factor(mm(Phi.T,Phi))\n tmp = cho_solve((c,low),Phi.T)\n w = mm(tmp,y)\n f = mm(Phi,w)\n dif = y-f\n err = mm(dif.T,dif)\n return f,err,w,Phi\n```\n\n\n```python\nerrlistChol = []\nplt.figure(figsize=(20,20))\nfor i in range(21):\n plt.subplot(7,3,i+1)\n f,err,w,Phi = polynomialFitLU(x,y,i)\n errlistChol.append(err)\n plt.plot(x,y,'b.')\n plt.plot(x,f,'r-')\n plt.title('Order '+str(i)+': '+str(err))\n```\n\n\n```python\nplt.plot(np.arange(21),errlistChol)\n```\n\n### Comparison between inverse, LU decomposition and Cholesky decomposition\n\n\n```python\nplt.plot(np.arange(21),errlist)\nplt.plot(np.arange(21),errlistLU)\nplt.plot(np.arange(21),errlistChol)\n```\n\n\n```python\nplt.plot(np.arange(21),errlistLU)\nplt.plot(np.arange(21),errlistChol)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "7ab295bd291dc9cf6f1fa2a3cc07e5cb0e8e3672", "size": 653231, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Probabilistic Machine Learning/Introduction to Probabilistic Machine Learning/.ipynb_checkpoints/Linear in the parameters regression-checkpoint.ipynb", "max_stars_repo_name": "zcemycl/ProbabilisticPerspectiveMachineLearning", "max_stars_repo_head_hexsha": "8291bc6cb935c5b5f9a88f7b436e6e42716c21ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-11-20T10:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T11:15:23.000Z", "max_issues_repo_path": "Probabilistic Machine Learning/Introduction to Probabilistic Machine Learning/.ipynb_checkpoints/Linear in the parameters regression-checkpoint.ipynb", "max_issues_repo_name": "zcemycl/ProbabilisticPerspectiveMachineLearning", "max_issues_repo_head_hexsha": "8291bc6cb935c5b5f9a88f7b436e6e42716c21ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Probabilistic Machine Learning/Introduction to Probabilistic Machine Learning/.ipynb_checkpoints/Linear in the parameters regression-checkpoint.ipynb", "max_forks_repo_name": "zcemycl/ProbabilisticPerspectiveMachineLearning", "max_forks_repo_head_hexsha": "8291bc6cb935c5b5f9a88f7b436e6e42716c21ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-27T03:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-02T13:15:42.000Z", "avg_line_length": 1140.0191972077, "max_line_length": 187812, "alphanum_fraction": 0.9543806096, "converted": true, "num_tokens": 1856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9658995733060719, "lm_q2_score": 0.9334308179739307, "lm_q1q2_score": 0.9016004287917573}}
{"text": "```python\nfrom sympy import *\ninit_printing(use_latex='mathjax')\nn = symbols('n', integer=True)\nx, y, z = symbols('x,y,z')\n```\n\n## Integrals\n\nIn the first section we learned symbolic differentiation with `diff`. Here we'll cover symbolic integration with `integrate`.\n\nHere is how we write the indefinite integral\n\n$$ \\int x^2 dx = \\frac{x^3}{3}$$\n\n\n```python\n# Indefinite integral\nintegrate(x**2, x)\n```\n\nAnd the definite integral\n\n$$ \\int_0^3 x^2 dx = \\left.\\frac{x^3}{3} \\right|_0^3 = \\frac{3^3}{3} - \\frac{0^3}{3} = 9 $$\n\n\n```python\n# Definite integral\nintegrate(x**2, (x, 0, 3))\n```\n\nAs always, because we're using symbolics, we could use a symbol wherever we previously used a number\n\n$$ \\int_y^z x^n dx $$\n\n\n```python\nintegrate(x**n, (x, y, z))\n```\n\n### Exercise\n\nCompute the following integrals:\n\n$$ \\int \\sin(x) dx $$\n$$ \\int_0^{\\pi} \\sin(x) dx $$\n$$ \\int_0^y x^5 + 12x^3 - 2x + 1 $$\n$$ \\int e^{\\frac{(x - \\mu)^2}{\\sigma^2}} $$\n\nFeel free to play with various parameters and settings and see how the results change.\n\n\n```python\n# Use `integrate` to solve the integrals above\n\n\n```\n\nAre there some integrals that SymPy can't do? Find some.\n\n\n```python\n# Use `integrate` on other equations. Symbolic integration has it limits, find them.\n```\n", "meta": {"hexsha": "e60fb298839c464949658ce0eb6aefa5fd8ecdc7", "size": 3219, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial_exercises/03-Integrals.ipynb", "max_stars_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_stars_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2016-06-21T21:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T07:51:03.000Z", "max_issues_repo_path": "tutorial_exercises/03-Integrals.ipynb", "max_issues_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_issues_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2016-07-02T20:24:06.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-11T11:31:44.000Z", "max_forks_repo_path": "tutorial_exercises/03-Integrals.ipynb", "max_forks_repo_name": "gvvynplaine/scipy-2016-tutorial", "max_forks_repo_head_hexsha": "aa417427a1de2dcab2a9640b631b809d525d7929", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2016-06-25T09:04:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T06:46:01.000Z", "avg_line_length": 20.5031847134, "max_line_length": 132, "alphanum_fraction": 0.5063684374, "converted": true, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964855153093913, "lm_q2_score": 0.9343951602572963, "lm_q1q2_score": 0.901555985400265}}
{"text": "# 2. Linear Algebra_2. Systems of Linear Equations\n\nLinear Algebra는 Linear Equations problem을 Vector를 이용해 해결하는 것에 관한 학문으로 이해할 수 있습니다.\n\n따라서, Linear Equation과 이의 조합인 Systems of Linear Equations(선형 연립방정식) 또한 Vector, Matrix로 표현이 가능합니다.\n\n\n예를 들어, 다음과 같은 선형 연립방정식을 행렬 $A$, 벡터 $x$, $b$ 를 이용해 간단히 표현할 수 있습니다.\n\n$$ x_{1} + x_{2} + x_{3} = 3 $$\n$$ x_{1} - x_{2} + 2x_{3} = 2 $$\n$$ x_{2} + x_{3} = 2 $$\n\n\n$$\n\\begin{align}\nA= \n\\begin{bmatrix}\n1&1&1\\\\\n1&-1&2\\\\\n0&1&1\n\\end{bmatrix}\n,\\;\\;\nx=\n\\begin{bmatrix}\nx1\\\\\nx2\\\\\nx3\n\\end{bmatrix}\n,\\;\\;\nb=\n\\begin{bmatrix}\n3\\\\\n2\\\\\n2\n\\end{bmatrix}\n\\end{align}\n$$\n\n$$Ax = b$$\n$$x = A^{-1}b$$\n\n\n\n그리고, 이러한 Systems of Linear equations의 solution ( 벡터 $x$ ) 을 쉽게 찾을 수 있다.\n이때, 역행렬을 구하기 위해 Numpy패키지의 np.linalg.inv() method를 활용한다\n\n**참고 : @ 기호는 dotproduct(내적)연산을 수행한다. 기본 행렬곱인 element-wise 연산을 수행하기 위해선, 아래와 같이 @를 통해 행렬과 벡터의 연산을 수행한다.**\n\n\n```python\nA = np.array([[1,1,1],[1,-1,2],[0,1,1]])\nb = np.array([[3],[2],[2]])\nx = np.linalg.inv(A)@b\nx\n```\n\n\n\n\n array([[1.],\n [1.],\n [1.]])\n\n\n\n이와 같은 선형연립방정식을 풀 때, 위와 같이 역행렬을 직접 구해 solution을 구해줄 수 있지만, Numpy의 'lstsq()' 명령을 활용해 구할 수도 있다.\n\n`lstsq()` 명령은 향후 자세히 보게 될 solution, RSS, rank, Singular vlaue 를 각각 반환한다. `lstsq()` 명령은 이후 보게될 'Ordinary Least Square Problem'을 풀기위한 연산 명령이다.\n\n위와 같이 미지수의 갯수 $=$ 방정식의 갯수 (A가 Square Matrix)인 경우, OLS와 Inverse Matrix의 solution이 같기 때문에*, `lstsq()` 명령을 사용해도 동일한 답을 얻을 수 있다.\n\n*미지수의 갯수 $=$ 방정식의 갯수인 경우, unique solution을 갖기 때문에\n\n\n```python\nx, resid, rank, s = np.linalg.lstsq(A, b)\nx\n```\n\n\n\n\n array([[1.],\n [1.],\n [1.]])\n\n\n", "meta": {"hexsha": "9166a5e282841b2376f36da3fb02e8f2777e9849", "size": 3536, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "1.Study/2. with computer/1.Math_code/5. Mathematics for Machine Learning/2. Linear Algebra_2. Systems of Linear Equations.ipynb", "max_stars_repo_name": "jskim0406/Study", "max_stars_repo_head_hexsha": "07b559b95f8f658303ee53114107ae35940a6080", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1.Study/2. with computer/1.Math_code/5. Mathematics for Machine Learning/2. Linear Algebra_2. Systems of Linear Equations.ipynb", "max_issues_repo_name": "jskim0406/Study", "max_issues_repo_head_hexsha": "07b559b95f8f658303ee53114107ae35940a6080", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.Study/2. with computer/1.Math_code/5. Mathematics for Machine Learning/2. Linear Algebra_2. Systems of Linear Equations.ipynb", "max_forks_repo_name": "jskim0406/Study", "max_forks_repo_head_hexsha": "07b559b95f8f658303ee53114107ae35940a6080", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6932515337, "max_line_length": 149, "alphanum_fraction": 0.4621040724, "converted": true, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9609517072737735, "lm_q2_score": 0.9381240082215467, "lm_q1q2_score": 0.9014918673350109}}
{"text": "```python\nimport numpy as np\nfrom scipy import linalg as la\nimport sympy as sp\n```\n\nStarting from L9\n\nVectors x1 and x2 are independent if c1x1+c2x2 <>0\n\nVectors v1,v2,...,vn are columns of A. They are independant if nullspace of A is only zero vector(r=n, no free variables). They are dependant if Ac=0 for some nonzero c(r<n, there are free variables).\n\nVectors v1,...,vl span a space means: the space consists of all combs of those vectors.\n\nBasis for a vector space is a sequence of vectors v1,v2,...,vd with 2 properties: 1. They are independant; 2. They span the space.\n\nI3 is a basis for R^3\n\n\n```python\nI3 = np.identity(3)\nI3\n```\n\n\n\n\n array([[ 1., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 1.]])\n\n\n\n\n```python\nZ = np.zeros(3)\nZ\n```\n\n\n\n\n array([ 0., 0., 0.])\n\n\n\nThe only vector that gives zeros:\n\n\n```python\nnp.dot(I3,Z)\n```\n\n\n\n\n array([ 0., 0., 0.])\n\n\n\nAnother basis:\n\n\n```python\nA = np.array([[1,1,4],\n [1,2,3],\n [2,7,11]])\nA\n```\n\n\n\n\n array([[ 1, 1, 4],\n [ 1, 2, 3],\n [ 2, 7, 11]])\n\n\n\nn x n matrix that is invertible.\n\n\n```python\nnp.linalg.inv(A)\n```\n\n\n\n\n array([[ 0.125, 2.125, -0.625],\n [-0.625, 0.375, 0.125],\n [ 0.375, -0.625, 0.125]])\n\n\n\n\n```python\nnp.linalg.det(A)\n```\n\n\n\n\n 8.0000000000000018\n\n\n\nEvery basis for the space has the same number of vectors and this number is the dimension of this space.\n\n\n```python\nnp.linalg.matrix_rank(A)\n```\n\n\n\n\n 3\n\n\n\nRank is a number of pivot columns and it is a dimension of the columnspace. C(A)\n\nThe dimension of a Null Space is the number of free variables, total - pivot variables.\n\n4 Fundamental subspaces:\n\n Columnspace C(A) in R^m\n nullspace N(A) in R^n\n rowspace C(A^T) in R^n\n nullspace of A^T = N(A^T) (Left NullSpace) in R^m\n \n \n\nJust a lyrical digression. One can do a PLU transformation using scipy.linalg.lu.\n\n\n```python\nP,L,U = la.lu(A)\n\nP,L,U\n```\n\n\n\n\n (array([[ 0., 1., 0.],\n [ 0., 0., 1.],\n [ 1., 0., 0.]]), array([[ 1. , 0. , 0. ],\n [ 0.5, 1. , 0. ],\n [ 0.5, 0.6, 1. ]]), array([[ 2. , 7. , 11. ],\n [ 0. , -2.5, -1.5],\n [ 0. , 0. , -1.6]]))\n\n\n\n\n```python\nA2 = np.array([[1,3,1,4],\n [2,7,3,9],\n [1,5,3,1],\n [1,2,0,8]])\n```\n\nUsing sympy it is possible to calculate Reduced Row Echelon Form of the Matrix and thus find the basis of the matrix. And understand which rows are linearly independant.\n\n\n```python\nsp.Matrix(A2).rref()\n```\n\n\n\n\n (Matrix([\n [1, 0, -2, 0],\n [0, 1, 1, 0],\n [0, 0, 0, 1],\n [0, 0, 0, 0]]), (0, 1, 3))\n\n\n\nIn a matrix A2 columns 1, 2 and 4 are linearly independant and form a basis. Thus the rank of this matrix is 3.\n\n\n```python\nnp.linalg.matrix_rank(A2)\n```\n\n\n\n\n 3\n\n\n\n\n```python\nsp.Matrix(A).rref()\n```\n\n\n\n\n (Matrix([\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]]), (0, 1, 2))\n\n\n\nAnd here all the columns are linearly independant and form the basis.\n\n\n```python\nsp.Matrix(np.transpose(A2)).rref()\n```\n\n\n\n\n (Matrix([\n [1, 0, 0, 0],\n [0, 1, 0, 1],\n [0, 0, 1, -1],\n [0, 0, 0, 0]]), (0, 1, 2))\n\n\n\n\n```python\nsp.Matrix(A2).nullspace()\n```\n\n\n\n\n [Matrix([\n [ 2],\n [-1],\n [ 1],\n [ 0]])]\n\n\n\n\n```python\nsp.Matrix(A2).rowspace()\n```\n\n\n\n\n [Matrix([[1, 3, 1, 4]]), Matrix([[0, 1, 1, 1]]), Matrix([[0, 0, 0, -5]])]\n\n\n\n\n```python\nsp.Matrix(A2).columnspace()\n```\n\n\n\n\n [Matrix([\n [1],\n [2],\n [1],\n [1]]), Matrix([\n [3],\n [7],\n [5],\n [2]]), Matrix([\n [4],\n [9],\n [1],\n [8]])]\n\n\n\nThe dim of both column space and row space are rank of matrix - r.\n\n\n```python\nA3 = np.array ([[1,2,3],\n [1,2,3],\n [2,5,8]])\n```\n\n\n```python\nnp.linalg.matrix_rank(A3)\n```\n\n\n\n\n 2\n\n\n\n\n```python\nR = np.array(sp.Matrix(A3).rref()[0])\nR\n```\n\n\n\n\n array([[1, 0, -1],\n [0, 1, 2],\n [0, 0, 0]], dtype=object)\n\n\n\n\n```python\nA4 = np.array([[1,2,3,1],\n [1,1,2,1],\n [1,2,3,1]])\n```\n\n\n```python\nR4 = np.array(sp.Matrix(A4).rref()[0])\nR4\n```\n\n\n\n\n array([[1, 0, 1, 1],\n [0, 1, 1, 0],\n [0, 0, 0, 0]], dtype=object)\n\n\n\n\n```python\nsp.Matrix(A4).rowspace()\n```\n\n\n\n\n [Matrix([[1, 2, 3, 1]]), Matrix([[0, -1, -1, 0]])]\n\n\n\n\n```python\nsp.Matrix(A4).columnspace()\n```\n\n\n\n\n [Matrix([\n [1],\n [1],\n [1]]), Matrix([\n [2],\n [1],\n [2]])]\n\n\n\n\n```python\nN41,N42 = np.array(sp.Matrix(A4).nullspace())\nnp.dot(A4,N41), np.dot(A4,N42)\n```\n\n\n\n\n (array([0, 0, 0], dtype=object), array([0, 0, 0], dtype=object))\n\n\n\n\n```python\nlN4 = np.array(sp.Matrix(np.transpose(A4)).nullspace())\nnp.dot(lN4,A4)\n```\n\n\n\n\n array([[0, 0, 0, 0]], dtype=object)\n\n\n\nE matrix, such as EA = R\n\n\n```python\npreE4 = np.rint(np.array(sp.Matrix(np.c_[A4,np.eye(3)]).rref()[0]).astype(np.double))\n```\n\n\n```python\npreE4\n```\n\n\n\n\n array([[ 1., 0., 1., 1., 0., 2., -1.],\n [ 0., 1., 1., 0., 0., -1., 1.],\n [ 0., 0., 0., 0., 1., 0., -1.]])\n\n\n\n\n```python\nA4\n```\n\n\n\n\n array([[1, 2, 3, 1],\n [1, 1, 2, 1],\n [1, 2, 3, 1]])\n\n\n\n\n```python\nE4 = preE4[:,4:7]\nE4\n```\n\n\n\n\n array([[ 0., 2., -1.],\n [ 0., -1., 1.],\n [ 1., 0., -1.]])\n\n\n\n\n```python\nnp.dot(E4,A4)\n```\n\n\n\n\n array([[ 1., 0., 1., 1.],\n [ 0., 1., 1., 0.],\n [ 0., 0., 0., 0.]])\n\n\n\nEnding Lecture 10 here.\n", "meta": {"hexsha": "936d59c04110b19579c3cd1683c1222331051cb4", "size": 15531, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "LinAl_003.ipynb", "max_stars_repo_name": "rtgshv/linal101", "max_stars_repo_head_hexsha": "f520987a6f1e468b3b466c14820e43dada565e43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LinAl_003.ipynb", "max_issues_repo_name": "rtgshv/linal101", "max_issues_repo_head_hexsha": "f520987a6f1e468b3b466c14820e43dada565e43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LinAl_003.ipynb", "max_forks_repo_name": "rtgshv/linal101", "max_forks_repo_head_hexsha": "f520987a6f1e468b3b466c14820e43dada565e43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0330882353, "max_line_length": 206, "alphanum_fraction": 0.4198699375, "converted": true, "num_tokens": 2094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.964321450147636, "lm_q2_score": 0.9343951625409307, "lm_q1q2_score": 0.9010572981524063}}
{"text": "## Barycentric Lagrange Interpolation\n\nThis rewriting of the Lagrange interpolation goes back at least seventy-five years but was popularized by [Berrut and Trefethen](https://epubs.siam.org/doi/pdf/10.1137/S0036144502417715) in the early 21st century. The idea here is basically to rewrite the Lagrange form to avoid the problems mentioned above.\n\nFirst define\n\n$$\\mathcal{l}(x)\\equiv \\prod_{i=0}^n (x-x_i).$$\n\nThen note that\n\n$$L_j^n(x) = \\frac{\\mathcal{l}(x)}{(x-x_j)} w_j,$$\n\nwhere the baricentric weight $w_j$ is \n\n$$ w_j \\equiv \\frac{1}{\\prod_{i=0,i\\neq j}^n (x_j-x_i)}.$$\n\nOur interpolating polynomial now becomes\n\n$$p_n(x) = \\sum_{i=0}^n L_i^n(x) f(x_i) = \\mathcal{l}(x)\\sum_{i=0}^n \\frac{w_i}{x-x_i} f(x_i).$$\n\nThis is called the *first form of barycentric interpolation*. Once we have computed the weights $w_j$, evaluation of $p_n(x)$ now requires $\\mathcal{O}(n)$ flops thus removing the first objection to the Lagrange form of the interpolating polynomial.\n\nIf we add a new node $x_{n+1}$, we can construct new weights $w_j$ by dividing the old weights by $(x_j-x_{n+1})$ to get the new $w_j$ (plus computing $w_{n+1}$ using the original formula). This effectively eliminates the second objection to the Lagrange form of the intepolating polynomial.\n\nThere is another similification we can use before constructing an algorithm for interpolation. Note that for the function $g(x)\\equiv 1$,\n\n$$\n\\begin{align}\ng(x) &= \\mathcal{l}(x)\\sum_{i=0}^n \\frac{w_i}{x-x_i} g(x_i),\\\\\n &= \\mathcal{l}(x)\\sum_{i=0}^n \\frac{w_i}{x-x_i}.\n\\end{align}\n$$\nAs we shall see when we discuss interpolation errors, this formula is actually exact. As a result,\n\n$$\n\\begin{align}\np_n(x) &= \\frac{p_n(x)}{1} = \\frac{p_n(x)}{g(x)},\\\\\n &=\\frac{\\mathcal{l}(x)\\sum_{i=0}^n \\frac{w_i}{x-x_i} f(x_i)}{\\mathcal{l}(x)\\sum_{i=0}^n \\frac{w_i}{x-x_i}},\n\\end{align}\n$$\n\nwhich simiplifies to the second, or *true form of barycentric interpolation*\n\n$$p_n(x)=\\frac{\\sum_{i=0}^n \\frac{w_i}{x-x_i} f(x_i)}{\\sum_{i=0}^n \\frac{w_i}{x-x_i}}.$$ \n\nIn this form, we avoid evaluating $\\mathcal{l}(x)$ entirely and the sum in the numerator and denominator can easily be constructed simultaneously.\n\nNote that there are two stages to implementation of barycentric Lagrange interpolation: i) computing the weights and ii) computing the interpolation at the desired points. The first should be done *only once* whereas the second needs to be done at each point where the interpolation is computed. A python code to do this is below \n\n\n```python\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef baryweight(x):\n # build the weights recursively by effectively adding new points one at a time\n w = [1.]*len(x)\n for i in range(0,len(x)):\n # in iteration i we compute w[i] from scratch while\n # including the contribution of x[i] to the other weights\n for j in range(0,i):\n w[j]=(x[j]-x[i])*w[j]\n w[i]=(x[i]-x[j])*w[i]\n # do the divisions at the end to minimize the total number of divisions\n return [1/x for x in w]\n\ndef baryinterp(w,x,y,xp):\n # Compute the barycentric interpolation at xp given the observed data in lists\n # x and y and the precomputed weights in a list w\n numer=0.\n denom=0.\n for i in range(0,len(x)):\n xdiff=xp-x[i]\n # We first check to ensure we are not actually evaluated at a given data point.\n # (This would lead to division by zero which would cause problems).\n if (xdiff == 0):\n return y[i]\n else:\n tmp=w[i]/xdiff\n numer += tmp*y[i]\n denom += tmp\n return numer/denom\n\n# Main program showing functions defined above used to interpolate data taken from\n# a simple sine function\n\n# This creates a list of x values for our observed data\ndx = 0.5\nx_data = np.arange(0, 6.5+dx, dx)\n\n# Compute the weights for the interpolating polynomial. \nweights=baryweight(x_data)\n\n# Create a list of y values for our observed data and plot\n# our observations\ny_data = np.sin(x_data)\nplt.plot(x_data, y_data, \"o\", label=\"data\")\n\n# Now we want to fill in between our observed data points using\n# a barycentric Lagrange interpolation and plot the result\ndx = 0.01\nx_all = np.arange(0,6.5+dx,dx)\ny_all = [0]*len(x_all)\nfor i in range(0,len(x_all)):\n y_all[i] = baryinterp(weights,x_data,y_data,x_all[i])\n \nplt.plot(x_all, y_all, label=\"barycentric interpolation\")\nplt.legend()\nplt.show()\n```\n\nThere are a few things to note here:\n\n- the weights depend only on the $x_i$ and not on $f(x_i)$. As such, the same weights could be used in the interpolation of any function whose values are known at the same set of $x_i$ (i.e. we can resuse the weights for other functions).\n- the order of the nodes does not matter. This means that if we want to add a new data point, it can just be appended to the end of the list, it does not need to be inserted in order.\n- if you want to add a new data point, you could easily write another function (say \"addpoint\") to update the weights. It would essentially consist of the \"extra\" iteration of the loop in the above `baryweight` function, accounting for the fact that we have already done the `1/x` operation. It should be clear that the update is $\\mathcal{O}(n)$ operation as only the inner loop is computed.\n- you may have noticed that the `baryinterp` function dealt with the case where $x=x_i$ as a special case to avoid division by zero. You might be concerned about overflow in the situation where $x$ is close to $x_i$ but not exactly the same. There are ways of dealing with this when it arises, but it turns out it is not a serious concern for most practical applications of interpolation.\n- as with any algorithm, one should ask if this is numerically stable. As we emphasized when we discussed errors in scientific computing, it is only reasonable to ask if the algorithm is stable when applied to a well-conditioned problem. As we will discuss shortly, polynomial interpolation for large numbers of points is only stable if these points are chosen appropriately. In this case, [Higham](https://www.maths.manchester.ac.uk/~higham/narep/narep440.pdf) has shown that barycentric Lagrange interpolation is unconditionally stable (the first form is slightly better than the \"true\" form in this regards, but the difference for practical purposes is not usually significant).\n- for some node spacings, it is possible to give an explicit formula for the barycentric weights $w_j$. As these weights appear in the true form of the barycentric interpolation in both the numerator and denominator, any common factor in all the weights can be cancelled without affecting the result. \n\nThere are also built in versions of [barycentric interpolation in SciPy](https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.barycentric_interpolate.html#scipy.interpolate.barycentric_interpolate). The SciPy version also has functions to add new nodes and new, or different, values of the function to be interpolated (making use of the previously computed weights in both cases).\n\n\n", "meta": {"hexsha": "e8b4e42a2ee269a87c9ef38ab4c34553c6ff0e18", "size": 28492, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "class/InterpFit/BarycentricInterp.ipynb", "max_stars_repo_name": "CDenniston/NumericalAnalysis", "max_stars_repo_head_hexsha": "8f4ccaa864461c36e269824a0e9038bc14ef10b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "class/InterpFit/BarycentricInterp.ipynb", "max_issues_repo_name": "CDenniston/NumericalAnalysis", "max_issues_repo_head_hexsha": "8f4ccaa864461c36e269824a0e9038bc14ef10b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "class/InterpFit/BarycentricInterp.ipynb", "max_forks_repo_name": "CDenniston/NumericalAnalysis", "max_forks_repo_head_hexsha": "8f4ccaa864461c36e269824a0e9038bc14ef10b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 154.847826087, "max_line_length": 19148, "alphanum_fraction": 0.8548013477, "converted": true, "num_tokens": 1912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9688561685659695, "lm_q2_score": 0.9294404111419479, "lm_q1q2_score": 0.900494075649367}}
{"text": "## Homework Problem: Alice Hunts Dragons\n\nWhen she is not calculating marginal distributions, Alice spends her time hunting dragons. For every dragon she encounters, Alice measures its fire power $X$ (measured on a scale from $1$ to $4$) and its roar volume $Y$ (measured on a scale from $1$ to $3$). She notices that the proportion of dragons with certain fire power and roar volume in the population behaves as the following function:\n\n$$\\begin{eqnarray}\nf(x,y) = \\begin{cases} x^2+y^2 &\\text{if } x \\in \\{1,2,4\\} \\text{ and } y \\in \\{1,3\\} \\\\\n0 &\\text{otherwise}. \\end{cases}\n\\end{eqnarray}$$\n\nIn other words, the joint probability table $p_{X,Y}$ is of the form\n\n$$p_{X,Y}(x,y) = c f(x, y) \\qquad \\text {for }x \\in \\{ 1, 2, 3, 4\\} , y \\in \\{ 1, 2, 3\\} ,$$\n \nfor some constant $c>0$ that you will determine.\n\n**Question:** Determine the constant $c$, which ensures that $p_{X,Y}$ is a valid probability distribution. (Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n\n```python\nΩ = {(i, j) for i in range(1, 5) for j in range(1, 4)}\nfrom fractions import Fraction\njoint_X_Y = {(i, j): (i**2 + j**2) for i in {1, 2, 4} for j in {1, 3}}\nc = 1/sum(joint_X_Y.values())\nprint(Fraction(c).limit_denominator())\n```\n\n 1/72\n\n\n**Question:** Determine $P(Y<X)$. (Note that $\\{Y<X\\}$ is an event. Think about what outcomes are in it.)\n\n(Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n\n```python\nY_lt_X = {x for x in joint_X_Y if x[1] < x[0]}\nprob_Y_lt_X = sum([joint_X_Y[x] for x in Y_lt_X]) * c\nprint(Fraction(prob_Y_lt_X).limit_denominator())\n```\n\n 47/72\n\n\n**Question:** Determine $P(X<Y)$. (Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n\n```python\nX_lt_Y = {x for x in joint_X_Y if x[1] > x[0]}\nprob_X_lt_Y = sum([joint_X_Y[x] for x in X_lt_Y]) * c\nprint(Fraction(prob_X_lt_Y).limit_denominator())\n```\n\n 23/72\n\n\n**Question:** Determine $P(Y=X)$. (Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n\n```python\nX_eq_Y = {x for x in joint_X_Y if x[1] == x[0]}\nprob_X_eq_Y = sum([joint_X_Y[x] for x in X_eq_Y]) * c\nprint(Fraction(prob_X_eq_Y).limit_denominator())\n```\n\n 1/36\n\n\n**Question:** Determine $P(Y=3)$. (Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n\n```python\nY_eq_3 = {x for x in joint_X_Y if x[1] == 3}\nprob_Y_eq_3 = sum([joint_X_Y[x] for x in Y_eq_3]) * c\nprint(Fraction(prob_Y_eq_3).limit_denominator())\n```\n\n 2/3\n\n\n**Question:** Find the probability tables for $p_X$ and $p_Y$. Express your answers as Python dictionaries. (Your answer should be the Python dictionary itself, and not the dictionary assigned to a variable, so please do not include, for instance, “prob_table =\" before specifying your answer. You can use fractions. If you use decimals instead, please be accurate and use at least 5 decimal places.)\n\n$p_X$ probability table (the dictionary keys should be the Python integers 1, 2, 3, 4): \n\n\n```python\nprob_X = {i: 0 for i in range(1, 5)} # initialize the dictionary with 0 \nfor key, values in joint_X_Y.items():\n if key[0] in prob_X:\n prob_X[key[0]] += values * c\n \nprob_X \n```\n\n\n\n\n {1: 0.16666666666666669, 2: 0.25, 3: 0, 4: 0.5833333333333333}\n\n\n\n$p_Y$ probability table (the dictionary keys should be the Python integers 1, 2, 3): \n\n\n```python\nprob_Y = {i: 0 for i in range(1, 4)} # initialize the dictionary with 0 \nfor key, values in joint_X_Y.items():\n if key[1] in prob_Y:\n prob_Y[key[1]] += values * c\n \nprob_Y\n```\n\n\n\n\n {1: 0.33333333333333337, 2: 0, 3: 0.6666666666666666}\n\n\n\n## Homework Problem: Alice's Coins\n\nAlice has five coins in a bag: two coins are normal, two are double-headed, and the last one is double-tailed. She reaches into the bag and randomly pulls out a coin. Without looking at the coin she drew, she tosses it.\n\n**Question:** What is the probability that once the coin lands, the side of the coin that is face-down is heads? (Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n**Answer:** Let $X$ is the random variable for selecting the coin. Let $X = \\{F, H, T\\}$ takes values $F$ for fair coin, $H$ for double-headed coin and $T$ for double-tailed coin. Also $Y = \\{h, t\\}$ is the random variable for getting $h$ for face down head and $t$ for face down tail. Then the joint probability distribution is given by \n\n| | Y=h | Y=t | X<sub>marginal</sub> |\n|----------------------|-----|-----|----------------------|\n| X=F | 1/5 | 1/5 | 2/5 |\n| X=H | 2/5 | 0 | 2/5 |\n| X=T | 0 | 1/5 | 1/5 |\n| Y<sub>marginal</sub> | 3/5 | 2/5 | |\n\nThe probability of getting face down head is given by marginal probibility $\\mathbb{P}(Y=h) = 3/5$.\n\n**Question:** The coin lands and shows heads face-up. What is the probability that the face-down side is heads? (Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n**Answer:** This question asking about conditional probability \n$$\\mathbb{P}(X=H|Y=h) = \\frac{\\mathbb{P}(X=H, Y=h)}{\\mathbb{P}(Y=h) } = \\frac{2/5}{3/5} = \\frac{2}{3} $$\n\nAlice discards the first coin (the one from part (b) that landed and showed heads face-up), reaches again into the bag and draws out a random coin. Again, without looking at it, she tosses it.\n\n**Question:** What is the probability that the coin shows heads face-up? (Please be precise with at least 3 decimal places, unless of course the answer doesn't need that many decimal places. You could also put a fraction.)\n\n**Answer:** Let $Z$ is the random varable for getting second coin face-up heads or tails. Also note that the first coin with face-up heads is discarded. There are two possibiliy of getting heads on face-up if $X=F$ or $X=H$. Let $W$ is the random variable for withdrawing second coin. \n\nThe joint probability distribution of $W$ and $Z$ given $X=F$, $i.e.$, $P(W,Z|X=F)$\n\n| | Z=h | Z=t | W<sub>marginal</sub> |\n|----------------------|-----|-----|:--------------------:|\n| W=F | 1/8 | 1/8 | 1/4 |\n| W=H | 1/2 | 0 | 1/2 |\n| W=T | 0 | 1/4 | 1/4 |\n| Z<sub>marginal</sub> | 5/8 | 3/8 | |\n\nThe joint probability distribution of $W$ and $Z$ given $X=H$, $i.e.$, $P(W,Z|X=H)$\n\n| | Z=h | Z=t | W<sub>marginal</sub> |\n|----------------------|-----|-----|:--------------------:|\n| W=F | 1/4 | 1/4 | 1/2 |\n| W=H | 1/4 | 0 | 1/4 |\n| W=T | 0 | 1/4 | 1/4 |\n| Z<sub>marginal</sub> | 1/2 | 1/2 | |\n\nHence the probability of getting heads in face-up is given by\n\n$$\n\\begin{align}\n\\mathbb{P}(Z=h|Y=h) \n&= \\mathbb{P}(Z=h|X=F) \\times \\mathbb{P}(X=F|Y=h) + \\mathbb{P}(Z=h|X=H) \\times \\mathbb{P}(X=H|Y=h) \\\\\n&= \\mathbb{P}(Z=h|X=F) \\times \\frac{\\mathbb{P}(X=F, Y=h)}{ \\mathbb{P}(Y=h)} + \\mathbb{P}(Z=h|X=H) \\times \\frac{\\mathbb{P}(X=H, Y=h)}{ \\mathbb{P}(Y=h)} \\\\\n&= \\frac{5}{8} \\times \\frac{1/5}{3/5} + \\frac{1}{2} \\times \\frac{2/5}{3/5}\\\\\n&= \\frac{13}{24}\n\\end{align}\n$$\n\n\n```python\n\n```\n", "meta": {"hexsha": "29ea1e7d58626e43c6f66eeece370ad4261982a6", "size": 12068, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "week02/06 Homework.ipynb", "max_stars_repo_name": "infimath/Computational-Probability-and-Inference", "max_stars_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-04T03:07:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-04T03:07:47.000Z", "max_issues_repo_path": "week02/06 Homework.ipynb", "max_issues_repo_name": "infimath/Computational-Probability-and-Inference", "max_issues_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week02/06 Homework.ipynb", "max_forks_repo_name": "infimath/Computational-Probability-and-Inference", "max_forks_repo_head_hexsha": "e48cd52c45ffd9458383ba0f77468d31f781dc77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-27T05:33:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T05:33:49.000Z", "avg_line_length": 33.7094972067, "max_line_length": 410, "alphanum_fraction": 0.5248591316, "converted": true, "num_tokens": 2424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.9489172605148684, "lm_q1q2_score": 0.9004439697019805}}
{"text": "Sympy variables are created using unique string identifiers.\n\n\n```python\nimport sympy as sp\nimport numpy as np\nx = sp.Symbol(\"x\")\ny = sp.Symbol(\"y\")\nz = sp.Symbol(\"z\")\n```\n\nOne can form expression from symbols.\nSympy expressions are made up of numbers, symbols, and sympy functions.\n\n\n```python\nexpression = x**2. + y**2. + z ** 2.\nexpression\n```\n\n\n\n\n x**2.0 + y**2.0 + z**2.0\n\n\n\nTwo expressions may be added together to form a new one.\n\n\n```python\nother_expression = x**2.\nexpression += other_expression\nexpression\n```\n\n\n\n\n 2*x**2.0 + y**2.0 + z**2.0\n\n\n\nOne can form sympy `Matrix` objects.\n\n\n```python\nsp.Matrix([[1,2],[3,4]])\n```\n\n\n\n\n Matrix([\n [1, 2],\n [3, 4]])\n\n\n\nAn important `Matrix` function is `eye(n)`, which forms a $n \\times n$ identity matrix.\n\n\n```python\nsp.eye(3)\n```\n\n\n\n\n Matrix([\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]])\n\n\n\nOne can stuff expressions into matrices, too.\n\n\n```python\n# One can stuff expressions into matrices\nf1 = x**2.+y**2-z**2.\nf2 = 2*x + y + z\nfunction_matrix = sp.Matrix([f1,f2])\nfunction_matrix\n```\n\n\n\n\n Matrix([\n [x**2.0 + y**2 - z**2.0],\n [ 2*x + y + z]])\n\n\n\nOne may compute the Jacobian of vector valued functions, too.\n\n\n```python\nfunction_matrix.jacobian([x,y,z]) # pass in a list of Sympy Symbols to take the Jacobian\n```\n\n\n\n\n Matrix([\n [2.0*x**1.0, 2*y, -2.0*z**1.0],\n [ 2, 1, 1]])\n\n\n\nSympy expressions can be evaluated by passing in a Python dictionary mapping Symbol `Symbol`s to specific values.\n\n\n```python\nx_val = 1.0\ny_val = 2.0\nz_val = 3.0\nvalues={\"x\":x_val,\"y\":y_val,\"z\":z_val}\nf1.subs(values)\n```\n\n\n\n\n -4.00000000000000\n\n\n\nOne can even valuate the Jacobian of functions.\n\n\n```python\nJ_mat = function_matrix.jacobian([x,y,z]).subs(values)\nJ_mat\n```\n\n\n\n\n Matrix([\n [2.0, 4.0, -6.0],\n [ 2, 1, 1]])\n\n\n\nTo convert a Sympy `Matrix` into a Numpy array, one may use the following:\n\n\n```python\nnp.array(J_mat)\n```\n\n\n\n\n array([[2.00000000000000, 4.00000000000000, -6.00000000000000],\n [2, 1, 1]], dtype=object)\n\n\n\nAfter evaluating an expression in Sympy, the return type is a `sympy.Float`.\nHowever, this is not readily usable by Numpy. Therefore, consider casting `sympy.Float` to a `numpy.float64`.\n\n\n```python\nJ=np.array(J_mat).astype(np.float64)\nJ\n```\n\n\n\n\n array([[ 2., 4., -6.],\n [ 2., 1., 1.]])\n\n\n\nAt this point, one cna do all the usual stuff one would in Numpy.\n\n\n```python\nJ.T@J\n```\n\n\n\n\n array([[ 8., 10., -10.],\n [ 10., 17., -23.],\n [-10., -23., 37.]])\n\n\n\nSymp's `Lambdify` can help increase the speed of Sympy's numerical computations.\n\n\n```python\nfunction_matrix.subs(values)\n```\n\n\n\n\n Matrix([\n [-4.0],\n [ 7.0]])\n\n\n\n\n```python\nfrom sympy.utilities.lambdify import lambdify\narray2mat = [{'ImmutableDenseMatrix': np.array}, 'numpy']\nlam_f_mat = lambdify((x,y,z), function_matrix, modules=array2mat)\nlam_f_mat(1,2,3)\n```\n\n\n\n\n array([[-4.],\n [ 7.]])\n\n\n\nOr if it is more convenient to have the function evaluation occur from a list of some sort, the Python `*` operator on lists can help.\n\n\n```python\nlam_f_mat(*[1,2,3])\n```\n\n\n\n\n array([[-4.],\n [ 7.]])\n\n\n", "meta": {"hexsha": "82c6580b4cede372156d7cbe83e275e4187ed594", "size": 10572, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "misc/An Introduction to Sympy.ipynb", "max_stars_repo_name": "JiaheXu/MATH", "max_stars_repo_head_hexsha": "9cb2b412ba019794702cacf213471742745d17a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/An Introduction to Sympy.ipynb", "max_issues_repo_name": "JiaheXu/MATH", "max_issues_repo_head_hexsha": "9cb2b412ba019794702cacf213471742745d17a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/An Introduction to Sympy.ipynb", "max_forks_repo_name": "JiaheXu/MATH", "max_forks_repo_head_hexsha": "9cb2b412ba019794702cacf213471742745d17a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3377483444, "max_line_length": 144, "alphanum_fraction": 0.3918842225, "converted": true, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9653811591688145, "lm_q2_score": 0.9324533060447605, "lm_q1q2_score": 0.9001728534602843}}
{"text": "## Homework-4\n### CSC-722: Machine Learning Fundamentals\n### Md Hafizur Rahman\n\n\n### 1) Write a code to find norm 0, norm 1, norm 2, and norm infinity of the vectore x\n\n### Theory:\nIn mathematics, a norm is a function from a vector space over the real or complex numbers to the nonnegative real numbers, that satisfies certain properties pertaining to scalability and additivity and takes the value zero only if the input vector is zero [1].\n\nOn $R^n$ and $p≥1$, where R is real number and n=0,1,2... the p-norm is defined as\n\\begin{align}\nl_p=(\\sum_{j=1}^n|x_j|^p)^{1/p}\n\\end{align}\n\nIn our case, we have to calculate $l_0$, $l_1$, $l_2$ and $l_\\inf$. X is a list of 10 random numbers between -10 and 10. So, j= 1,2,3...,10\n\n\n```python\n#importing the necessary libraries\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n```\n\n\n```python\n#generating 10 random numbers of a list between -10 and 10.\nx = np.random.randint(-10, 10, 10)\nprint(x)\n```\n\n [ 2 9 -9 -10 6 -5 -8 -9 5 -8]\n\n\n\n\n#### Norm-0:\n\nThe $l_0$ norm corresponds to the total number of nonzero elements in a given vector.\n\nWe have used count_nonzero method of numpy to find the norm-0.\n\n\n```python\nnorm_0=np.count_nonzero(x)\nprint(\"Norm-0 of the X is\", norm_0)\n```\n\n Norm-0 of the X is 10\n\n\n#### Norm-1:\nNorm-1 is also known as Manhattan Distance or Taxicab norm. L1 norm is the sum of the magnitudes of the vectors in a space. \n\nMathematically,\n\n\\begin{align}\nl_1=(\\sum_{j=1}^n|x_j|)\n\\end{align}\n\nWe used sum method of numpy to calculate the norm-1. abs() has to use for getting the absolute values of x. \n\n\n```python\nnorm_1=sum(abs(x))\nprint(\"Norm-1 of the X is\", norm_1)\n```\n\n Norm-1 of the X is 71\n\n\n#### Norm-2:\nNorm-2 is also known as the Euclidean norm. It is the shortest distance to go from one point to another. \n\nMathematically, we can write the $l_2$ norm as\n\n\\begin{align}\nl_2=(\\sum_{j=1}^n|x_j|^2)^{1/2}\n\\end{align}\n\nWe used sum method of numpy to calculate the norm-1. abs() has to use for getting the absolute values of x. \n\n\n```python\nnorm_2=(sum(x**2))**(1/2)\nprint(\"Norm-2 of the X is\",norm_2) \n```\n\n Norm-2 of the X is 23.68543856465402\n\n\n#### Norm-inf:\nNorm-inf gives the largest magnitude among each element of a vector. \n\nMathematically, we can write $l_\\inf$ norm as\n\n\\begin{align}\nl_\\inf=max|x_j|\n\\end{align}\n\nWe used max method of numpy to calculate the norm-inf. abs() has to use for getting the absolute values of x. \n\n\n```python\nnorm_inf=max(abs(x))\nprint(\"Norm-inf of the X is\",norm_inf)\n```\n\n Norm-inf of the X is 10\n\n\n### 2) Explain the following cells \n### 3) Explain what they do and why\n\nIf most of the elements in the matrix are zero then the matrix is called a sparse matrix. It is wasteful to store the zero elements in the matrix since they do not affect the results of our computation. This is why we implement these matrices in more efficient representations than the standard 2D Array. Using more efficient representations we can cut down space and time complexities of operations significantly without changing the main matrix[2]. We are disscusing the following example step by step.\n\nAt first, we generate a 3 $\\times$ 6 matrix and store in A. We are seeing that most of the elements of A are zero. We can create CSR matrix for A.\n\n\n```python\nA = np.array([[1, 0, 0, 1, 0, 0], [0, 0, 2, 0, 0, 1], [0, 0, 0, 2, 0, 0]])\nprint(A)\n```\n\n [[1 0 0 1 0 0]\n [0 0 2 0 0 1]\n [0 0 0 2 0 0]]\n\n\nTo create CSR matrix, we used csr_matrix function from numpy.\n\n\n```python\n# convert to sparse matrix (CSR method)\nS = csr_matrix(A)\nprint(S)\n```\n\n (0, 0)\t1\n (0, 3)\t1\n (1, 2)\t2\n (1, 5)\t1\n (2, 3)\t2\n\n\nFrom the result we can see that there are 5 items [consider in row] with value.\nThe row and position start from 0.\n\nThe 1. item is in row 0 position 0 and has the value 1.\n\nThe 2. item is in row 0 position 3 and has the value 1.\n\nThe 3. item is in row 1 position 2 and has the value 2.\n\nThe 4. item is in row 1 position 5 and has the value 1.\n\nThe 5. item is in row 2 position 3 and has the value 2.\n\nTherefore, this matrix S will take less space and reduce the time of computation.\n\nWe can reconstruct the orginal matrix A from S. For that we have used todense() function.\n\n\n```python\n# reconstruct dense matrix\nB = S.todense()\nprint(B)\n```\n\n [[1 0 0 1 0 0]\n [0 0 2 0 0 1]\n [0 0 0 2 0 0]]\n\n\n#### Refs:\n[1] Bourbaki, Nicolas (1987) [1981]. Topological Vector Spaces: Chapters 1–5 [Sur certains espaces vectoriels topologiques]. Annales de l'Institut Fourier. Elements of mathematics. 2. Translated by Eggleston, H.G.; Madan, S. Berlin New York: Springer-Verlag. ISBN 978-3-540-42338-6. \n\n[2] Pissanetzky, Sergio (1984). Sparse Matrix Technology. Academic Press.\n\nFor the code please click the following link:\n\nhttps://github.com/hafizurr/Machine_Learnig_course/blob/master/home_work/Homework_4.ipynb\n", "meta": {"hexsha": "38864fd980ff713f645a5b75e95a7c2affbddb60", "size": 8942, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "home_work/Homework_4.ipynb", "max_stars_repo_name": "hafizurr/Machine_Learnig_course", "max_stars_repo_head_hexsha": "2a1fd51fd69a3d62730be500f794f30165a7cf24", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "home_work/Homework_4.ipynb", "max_issues_repo_name": "hafizurr/Machine_Learnig_course", "max_issues_repo_head_hexsha": "2a1fd51fd69a3d62730be500f794f30165a7cf24", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "home_work/Homework_4.ipynb", "max_forks_repo_name": "hafizurr/Machine_Learnig_course", "max_forks_repo_head_hexsha": "2a1fd51fd69a3d62730be500f794f30165a7cf24", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1887323944, "max_line_length": 510, "alphanum_fraction": 0.536680832, "converted": true, "num_tokens": 1539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377249197138, "lm_q2_score": 0.9390248212680324, "lm_q1q2_score": 0.9000907158214007}}
|