removed files

This commit is contained in:
Morten Hjorth-Jensen
2025-08-05 16:44:10 +02:00
parent 09a6275bc8
commit 9fe2835fb6
3 changed files with 0 additions and 1837 deletions
-932
View File
@@ -1,932 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "34471c23",
"metadata": {
"editable": true
},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html Project1.do.txt -->\n",
"<!-- dom:TITLE: Project 1 on Machine Learning, deadline October 7 (midnight), 2024 -->"
]
},
{
"cell_type": "markdown",
"id": "947e566c",
"metadata": {
"editable": true
},
"source": [
"# Project 1 on Machine Learning, deadline October 7 (midnight), 2024\n",
"**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, University of Oslo, Norway\n",
"\n",
"Date: **September 2**"
]
},
{
"cell_type": "markdown",
"id": "91b68c62",
"metadata": {
"editable": true
},
"source": [
"## Preamble: Note on writing reports, using reference material, AI and other tools\n",
"\n",
"We want you to answer the three different projects by handing in\n",
"reports written like a standard scientific/technical report. The link\n",
"at\n",
"<https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ProjectWriting/projectwriting.ipynb>\n",
"gives some guidance. See also the grading suggestion at\n",
"<https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md>.\n",
"\n",
"Furthermore, at\n",
"<https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/ReportExample/>\n",
"you can find examples of previous reports. How to write reports will\n",
"also be discussed during the various lab sessions. Please do ask us if you are in doubt.\n",
"\n",
"When using codes and material from other sources, you should refer to these in the bibliography of your report, indicating wherefrom you for example\n",
"got the code, whether this is from the lecture notes, softwares like\n",
"Scikit-Learn, TensorFlow, PyTorch or other sources. These should\n",
"always be cited correctly. How to cite some of the libraries is often\n",
"indicated from their corresponding GitHub sites or websites, see for example how to cite Scikit-Learn at <https://scikit-learn.org/dev/about.html>. \n",
"\n",
"We enocurage you to use tools like\n",
"[ChatGPT](https://openai.com/chatgpt/) or similar in writing the report. If you use for example ChatGPT,\n",
"please do cite it properly and include (if possible) your questions and answers as an addition to the report. This can\n",
"be uploaded to for example your website, GitHub/GitLab or similar as supplemental material."
]
},
{
"cell_type": "markdown",
"id": "6161e2ec",
"metadata": {
"editable": true
},
"source": [
"## Regression analysis and resampling methods\n",
"\n",
"The main aim of this project is to study in more detail various\n",
"regression methods, including the Ordinary Least Squares (OLS) method.\n",
"In addition to the scientific part, in this course we want also to\n",
"give you an experience in writing scientific reports.\n",
"\n",
"**A small recommendation when developing the codes here**. Instead of\n",
"jumping on to the two-dimensional function described below, we\n",
"recommend to do the code development and testing with a simpler\n",
"one-dimensional function, similar to those discussed in the exercises\n",
"of weeks 35 and 36. A simple test, as discussed during the lectures the first\n",
"three weeks is to set the design matrix equal to the identity\n",
"matrix. Then your model should give a mean square error which is exactly equal to zero.\n",
"When you are sure that your codes function well, you can then replace\n",
"the one-dimensional test function with the two-dimensional **Franke** function\n",
"discussed here.\n",
"\n",
"The Franke function serves as a stepping stone towards the analysis of\n",
"real topographic data. The latter is the last part of this project."
]
},
{
"cell_type": "markdown",
"id": "d598eabc",
"metadata": {
"editable": true
},
"source": [
"### Description of two-dimensional function\n",
"\n",
"We will first study how to fit polynomials to a specific\n",
"two-dimensional function called [Franke's\n",
"function](http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf). This\n",
"is a function which has been widely used when testing various\n",
"interpolation and fitting algorithms. Furthermore, after having\n",
"established the model and the method, we will employ resamling\n",
"techniques such as cross-validation and/or bootstrap in order to perform a\n",
"proper assessment of our models. We will also study in detail the\n",
"so-called Bias-Variance trade off.\n",
"\n",
"The Franke function, which is a weighted sum of four exponentials reads as follows"
]
},
{
"cell_type": "markdown",
"id": "6f94bf24",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\begin{align*}\n",
"f(x,y) &= \\frac{3}{4}\\exp{\\left(-\\frac{(9x-2)^2}{4} - \\frac{(9y-2)^2}{4}\\right)}+\\frac{3}{4}\\exp{\\left(-\\frac{(9x+1)^2}{49}- \\frac{(9y+1)}{10}\\right)} \\\\\n",
"&+\\frac{1}{2}\\exp{\\left(-\\frac{(9x-7)^2}{4} - \\frac{(9y-3)^2}{4}\\right)} -\\frac{1}{5}\\exp{\\left(-(9x-4)^2 - (9y-7)^2\\right) }.\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "2d87bd3d",
"metadata": {
"editable": true
},
"source": [
"The function will be defined for $x,y\\in [0,1]$. In a sense, our data are thus scaled to a particular domain for the input values.\n",
"\n",
"Our first step will\n",
"be to perform an OLS regression analysis of this function, trying out\n",
"a polynomial fit with an $x$ and a $y$ dependence of the form $[x, y,\n",
"x^2, y^2, xy, \\dots]$. We will also include bootstrap first as a\n",
"resampling technique. After that we will include the cross-validation\n",
"technique.\n",
"\n",
"We can\n",
"use a uniform distribution to set up the arrays of values for $x$ and\n",
"$y$, or as in the example below just a set of fixed values for $x$ and\n",
"$y$ with a given step size. We will fit a function (for example a\n",
"polynomial) of $x$ and $y$. Thereafter we will repeat much of the\n",
"same procedure using the Ridge and Lasso regression methods,\n",
"introducing thus a dependence on the bias (penalty) $\\lambda$.\n",
"\n",
"Finally we are going to use (real) digital terrain data and try to\n",
"reproduce these data using the same methods. We will also try to go\n",
"beyond the second-order polynomials metioned above and explore \n",
"which polynomial fits the data best.\n",
"\n",
"The Python code for the Franke function is included here (it performs also a three-dimensional plot of it)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "3ea47a48",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"from mpl_toolkits.mplot3d import Axes3D\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib import cm\n",
"from matplotlib.ticker import LinearLocator, FormatStrFormatter\n",
"import numpy as np\n",
"from random import random, seed\n",
"\n",
"fig = plt.figure()\n",
"ax = fig.add_subplot(projection = '3d')\n",
"# Make data.\n",
"x = np.arange(0, 1, 0.05)\n",
"y = np.arange(0, 1, 0.05)\n",
"x, y = np.meshgrid(x,y)\n",
"\n",
"\n",
"def FrankeFunction(x,y):\n",
" term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
" term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
" term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
" term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
" return term1 + term2 + term3 + term4\n",
"\n",
"\n",
"z = FrankeFunction(x, y)\n",
"\n",
"# Plot the surface.\n",
"surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,\n",
" linewidth=0, antialiased=False)\n",
"\n",
"# Customize the z axis.\n",
"ax.set_zlim(-0.10, 1.40)\n",
"ax.zaxis.set_major_locator(LinearLocator(10))\n",
"ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n",
"\n",
"# Add a color bar which maps values to colors.\n",
"fig.colorbar(surf, shrink=0.5, aspect=5)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "681ae810",
"metadata": {
"editable": true
},
"source": [
"If you wish to compare your results with other on the Franke function or other popular functions tested with linear regression, see the list in Figure 1 of the article by Cook et al at <https://arxiv.org/abs/2401.11694>."
]
},
{
"cell_type": "markdown",
"id": "0bf63b42",
"metadata": {
"editable": true
},
"source": [
"### Part a) : Ordinary Least Square (OLS) on the Franke function\n",
"\n",
"We will generate our own dataset for a function\n",
"$\\mathrm{FrankeFunction}(x,y)$ with $x,y \\in [0,1]$. The function\n",
"$f(x,y)$ is the Franke function. You should explore also the addition\n",
"of an added stochastic noise to this function using the normal\n",
"distribution $N(0,1)$.\n",
"\n",
"*Write your own code* (using either a matrix inversion or a singular\n",
"value decomposition from e.g., **numpy** ) and perform a standard **ordinary least square regression**\n",
"analysis using polynomials in $x$ and $y$ up to fifth order.\n",
"\n",
"Evaluate the mean Squared error (MSE)"
]
},
{
"cell_type": "markdown",
"id": "bda22453",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"MSE(\\boldsymbol{y},\\tilde{\\boldsymbol{y}}) = \\frac{1}{n}\n",
"\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "7cc65393",
"metadata": {
"editable": true
},
"source": [
"and the $R^2$ score function. If $\\tilde{\\boldsymbol{y}}_i$ is the predicted\n",
"value of the $i-th$ sample and $y_i$ is the corresponding true value,\n",
"then the score $R^2$ is defined as"
]
},
{
"cell_type": "markdown",
"id": "0e5859cb",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "5969702e",
"metadata": {
"editable": true
},
"source": [
"where we have defined the mean value of $\\boldsymbol{y}$ as"
]
},
{
"cell_type": "markdown",
"id": "6fc7cf78",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "fad83915",
"metadata": {
"editable": true
},
"source": [
"Plot the resulting scores (MSE and R$^2$) as functions of the polynomial degree (here up to polymial degree five).\n",
"Plot also the parameters $\\beta$ as you increase the order of the polynomial. Comment your results.\n",
"\n",
"Your code has to include a scaling/centering of the data (for example by\n",
"subtracting the mean value), and\n",
"a split of the data in training and test data. For this exercise you can\n",
"either write your own code or use for example the function for\n",
"splitting training data provided by the library **Scikit-Learn** (make\n",
"sure you have installed it). This function is called\n",
"$train\\_test\\_split$. **You should present a critical discussion of why and how you have scaled or not scaled the data**.\n",
"\n",
"It is normal in essentially all Machine Learning studies to split the\n",
"data in a training set and a test set (eventually also an additional\n",
"validation set). There\n",
"is no explicit recipe for how much data should be included as training\n",
"data and say test data. An accepted rule of thumb is to use\n",
"approximately $2/3$ to $4/5$ of the data as training data.\n",
"\n",
"You can easily reuse the solutions to your exercises from week 35 and week 36.\n",
"See also the lecture slides from week 35 and week 36.\n",
"\n",
"On scaling, we recommend reading the following section from the scikit-learn software description, see <https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html#plot-all-scaling-standard-scaler-section>."
]
},
{
"cell_type": "markdown",
"id": "5ca41535",
"metadata": {
"editable": true
},
"source": [
"### Part b): Adding Ridge regression for the Franke function\n",
"\n",
"Write your own code for the Ridge method, either using matrix\n",
"inversion or the singular value decomposition as done in the previous\n",
"exercise. The lecture notes from week 35 and 36 contain more information. Furthermore, the numerical exercise from week 36 is something you can reuse here.\n",
"\n",
"Perform the same analysis as you did in the previous exercise but now for different values of $\\lambda$. Compare and\n",
"analyze your results with those obtained in part a) with the ordinary least squares method. Study the\n",
"dependence on $\\lambda$."
]
},
{
"cell_type": "markdown",
"id": "eafba188",
"metadata": {
"editable": true
},
"source": [
"### Part c): Adding Lasso for the Franke function\n",
"\n",
"This exercise is essentially a repeat of the previous two ones, but now\n",
"with Lasso regression. Write either your own code (difficult and optional) or, in this case,\n",
"you can also use the functionalities of **Scikit-Learn** (recommended). Keep in mind that the library **Scikit-Learn** excludes the intercept by default. \n",
"Give a\n",
"critical discussion of the three methods and a judgement of which\n",
"model fits the data best."
]
},
{
"cell_type": "markdown",
"id": "ca22f9c3",
"metadata": {
"editable": true
},
"source": [
"### Part d): Paper and pencil part\n",
"\n",
"This exercise deals with various mean values and variances in linear regression method (here it may be useful to look up chapter 3, equation (3.8) of [Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer](https://www.springer.com/gp/book/9780387848570)). The exercise is also part of the weekly exercises for week 37.\n",
"\n",
"The assumption we have made is \n",
"that there exists a continuous function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim N(0, \\sigma^2)$\n",
"which describes our data"
]
},
{
"cell_type": "markdown",
"id": "62e8987d",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "3a837289",
"metadata": {
"editable": true
},
"source": [
"We then approximate this function $f(\\boldsymbol{x})$ with our model $\\boldsymbol{\\tilde{y}}$ from the solution of the linear regression equations (ordinary least squares OLS), that is our\n",
"function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we minimized $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, with"
]
},
{
"cell_type": "markdown",
"id": "c4103004",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "8802447b",
"metadata": {
"editable": true
},
"source": [
"The matrix $\\boldsymbol{X}$ is the so-called design or feature matrix. \n",
"\n",
"Show that the expectation value of $\\boldsymbol{y}$ for a given element $i$"
]
},
{
"cell_type": "markdown",
"id": "b129e460",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\mathbb{E}(y_i) =\\sum_{j}x_{ij} \\beta_j=\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta},\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "91bb15a6",
"metadata": {
"editable": true
},
"source": [
"and that\n",
"its variance is"
]
},
{
"cell_type": "markdown",
"id": "d6ac051f",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\mbox{Var}(y_i) = \\sigma^2.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "6d2b1477",
"metadata": {
"editable": true
},
"source": [
"Hence, $y_i \\sim N( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n",
"mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$.\n",
"\n",
"With the OLS expressions for the optimal parameters $\\boldsymbol{\\hat{\\beta}}$ show that"
]
},
{
"cell_type": "markdown",
"id": "ffb13255",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\mathbb{E}(\\boldsymbol{\\hat{\\beta}}) = \\boldsymbol{\\beta}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "031020e1",
"metadata": {
"editable": true
},
"source": [
"Show finally that the variance of $\\boldsymbol{\\beta}$ is"
]
},
{
"cell_type": "markdown",
"id": "ba8af75f",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\mbox{Var}(\\boldsymbol{\\hat{\\beta}}) = \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "c5c4d7e6",
"metadata": {
"editable": true
},
"source": [
"We can use the last expression when we define a so-called confidence interval for the parameters $\\beta$. \n",
"A given parameter $\\beta_j$ is given by the diagonal matrix element of the above matrix."
]
},
{
"cell_type": "markdown",
"id": "62633d34",
"metadata": {
"editable": true
},
"source": [
"### Part e): Bias-variance trade-off and resampling techniques\n",
"\n",
"Our aim here is to study the bias-variance trade-off by implementing the **bootstrap** resampling technique.\n",
"**We will only use the simpler ordinary least squares here**.\n",
"\n",
"With a code which does OLS and includes resampling techniques, \n",
"we will now discuss the bias-variance trade-off in the context of\n",
"continuous predictions such as regression. However, many of the\n",
"intuitions and ideas discussed here also carry over to classification\n",
"tasks and basically all Machine Learning algorithms. \n",
"\n",
"Before you perform an analysis of the bias-variance trade-off on your test data, make\n",
"first a figure similar to Fig. 2.11 of Hastie, Tibshirani, and\n",
"Friedman. Figure 2.11 of this reference displays only the test and training MSEs. The test MSE can be used to \n",
"indicate possible regions of low/high bias and variance. You will most likely not get an\n",
"equally smooth curve!\n",
"\n",
"With this result we move on to the bias-variance trade-off analysis.\n",
"\n",
"Consider a\n",
"dataset $\\mathcal{L}$ consisting of the data\n",
"$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$.\n",
"\n",
"As in part d), we assume that the true data is generated from a noisy model"
]
},
{
"cell_type": "markdown",
"id": "18f1b5b0",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "76dc98a9",
"metadata": {
"editable": true
},
"source": [
"Here $\\epsilon$ is normally distributed with mean zero and standard\n",
"deviation $\\sigma^2$.\n",
"\n",
"In our derivation of the ordinary least squares method we defined then\n",
"an approximation to the function $f$ in terms of the parameters\n",
"$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
"that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$.\n",
"\n",
"The parameters $\\boldsymbol{\\beta}$ are in turn found by optimizing the mean\n",
"squared error via the so-called cost function"
]
},
{
"cell_type": "markdown",
"id": "ea4f7a95",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "21225b69",
"metadata": {
"editable": true
},
"source": [
"Here the expected value $\\mathbb{E}$ is the sample value. \n",
"\n",
"Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a\n",
"term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.\n",
"That is, show that"
]
},
{
"cell_type": "markdown",
"id": "c259efb1",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathrm{Bias}[\\tilde{y}]+\\mathrm{var}[\\tilde{y}]+\\sigma^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "2bf21344",
"metadata": {
"editable": true
},
"source": [
"with"
]
},
{
"cell_type": "markdown",
"id": "2b5dd2b9",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\mathrm{Bias}[\\tilde{y}]=\\mathbb{E}\\left[\\left(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]\\right)^2\\right],\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "90c065aa",
"metadata": {
"editable": true
},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"id": "c29e34b2",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\mathrm{var}[\\tilde{y}]=\\mathbb{E}\\left[\\left(\\tilde{\\boldsymbol{y}}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]\\right)^2\\right]=\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "f928062b",
"metadata": {
"editable": true
},
"source": [
"The answer to this exercise should be included in the theory part of the report. This exercise is also part of the weekly exercises of week 38.\n",
"Explain what the terms mean and discuss their interpretations.\n",
"\n",
"Perform then a bias-variance analysis of the Franke function by\n",
"studying the MSE value as function of the complexity of your model.\n",
"\n",
"Discuss the bias and variance trade-off as function\n",
"of your model complexity (the degree of the polynomial) and the number\n",
"of data points, and possibly also your training and test data using the **bootstrap** resampling method.\n",
"You can follow the code example in the jupyter-book at <https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#the-bias-variance-tradeoff>."
]
},
{
"cell_type": "markdown",
"id": "ba0fe639",
"metadata": {
"editable": true
},
"source": [
"### Part f): Cross-validation as resampling techniques, adding more complexity\n",
"\n",
"The aim here is to implement another widely popular\n",
"resampling technique, the so-called cross-validation method. \n",
"\n",
"Implement the $k$-fold cross-validation algorithm (write your own\n",
"code or use the functionality of **Scikit-Learn**) and evaluate again the MSE function resulting\n",
"from the test folds. \n",
"\n",
"Compare the MSE you get from your cross-validation code with the one\n",
"you got from your **bootstrap** code. Comment your results. Try $5-10$\n",
"folds. \n",
"\n",
"In addition to using the ordinary least squares method, you should include both Ridge and Lasso regression."
]
},
{
"cell_type": "markdown",
"id": "82f076b3",
"metadata": {
"editable": true
},
"source": [
"### Part g): Analysis of real data\n",
"\n",
"With our codes functioning and having been tested properly on a\n",
"simpler function we are now ready to look at real data. We will\n",
"essentially repeat in this exercise what was done in exercises a-f. However, we\n",
"need first to download the data and prepare properly the inputs to our\n",
"codes. We are going to download digital terrain data from the website\n",
"<https://earthexplorer.usgs.gov/>,\n",
"\n",
"Or, if you prefer, we have placed selected datafiles at <https://github.com/CompPhysics/MachineLearning/tree/master/doc/Projects/2023/Project1/DataFiles>\n",
"\n",
"In order to obtain data for a specific region, you need to register as\n",
"a user (free) at this website and then decide upon which area you want\n",
"to fetch the digital terrain data from. In order to be able to read\n",
"the data properly, you need to specify that the format should be **SRTM\n",
"Arc-Second Global** and download the data as a **GeoTIF** file. The\n",
"files are then stored in *tif* format which can be imported into a\n",
"Python program using"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "b5f7adac",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"scipy.misc.imread"
]
},
{
"cell_type": "markdown",
"id": "5e55285e",
"metadata": {
"editable": true
},
"source": [
"Here is a simple part of a Python code which reads and plots the data\n",
"from such files"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "a66f3a48",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"from imageio import imread\n",
"import matplotlib.pyplot as plt\n",
"from mpl_toolkits.mplot3d import Axes3D\n",
"from matplotlib import cm\n",
"\n",
"# Load the terrain\n",
"terrain1 = imread('SRTM_data_Norway_1.tif')\n",
"# Show the terrain\n",
"plt.figure()\n",
"plt.title('Terrain over Norway 1')\n",
"plt.imshow(terrain1, cmap='gray')\n",
"plt.xlabel('X')\n",
"plt.ylabel('Y')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "1015d4e5",
"metadata": {
"editable": true
},
"source": [
"If you should have problems in downloading the digital terrain data,\n",
"we provide two examples under the data folder of project 1. One is\n",
"from a region close to Stavanger in Norway and the other Møsvatn\n",
"Austfjell, again in Norway.\n",
"Feel free to produce your own terrain data.\n",
"\n",
"Alternatively, if you would like to use another data set, feel free to do so. This could be data close to your reseach area or simply a data set you found interesting. See for example [kaggle.com](https://www.kaggle.com/datasets) for examples.\n",
"\n",
"Our final part deals with the parameterization of your digital terrain\n",
"data (or your own data). We will apply all three methods for linear regression, the same type (or higher order) of polynomial\n",
"approximation and cross-validation as resampling technique to evaluate which\n",
"model fits the data best.\n",
"\n",
"At the end, you should present a critical evaluation of your results\n",
"and discuss the applicability of these regression methods to the type\n",
"of data presented here (either the terrain data we propose or other data sets)."
]
},
{
"cell_type": "markdown",
"id": "23b093c7",
"metadata": {
"editable": true
},
"source": [
"## Background literature\n",
"\n",
"1. For a discussion and derivation of the variances and mean squared errors using linear regression, see the [Lecture notes on ridge regression by Wessel N. van Wieringen](https://arxiv.org/abs/1509.09169)\n",
"\n",
"2. The textbook of [Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer](https://www.springer.com/gp/book/9780387848570), chapters 3 and 7 are the most relevant ones for the analysis here."
]
},
{
"cell_type": "markdown",
"id": "fe5834fa",
"metadata": {
"editable": true
},
"source": [
"## Introduction to numerical projects\n",
"\n",
"Here follows a brief recipe and recommendation on how to answer the various questions when preparing your answers. \n",
"\n",
" * Give a short description of the nature of the problem and the eventual numerical methods you have used.\n",
"\n",
" * Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.\n",
"\n",
" * Include the source code of your program. Comment your program properly. You should have the code at your GitHub/GitLab link. You can also place the code in an appendix of your report.\n",
"\n",
" * If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.\n",
"\n",
" * Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.\n",
"\n",
" * Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.\n",
"\n",
" * Try to give an interpretation of you results in your answers to the problems.\n",
"\n",
" * Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.\n",
"\n",
" * Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning."
]
},
{
"cell_type": "markdown",
"id": "a238d8fe",
"metadata": {
"editable": true
},
"source": [
"## Format for electronic delivery of report and programs\n",
"\n",
"The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008, Julia or Python. The following prescription should be followed when preparing the report:\n",
"\n",
" * Use Canvas to hand in your projects, log in at <https://www.uio.no/english/services/it/education/canvas/> with your normal UiO username and password.\n",
"\n",
" * Upload **only** the report file or the link to your GitHub/GitLab or similar typo of repos! For the source code file(s) you have developed please provide us with your link to your GitHub/GitLab or similar domain. The report file should include all of your discussions and a list of the codes you have developed. Do not include library files which are available at the course homepage, unless you have made specific changes to them.\n",
"\n",
" * In your GitHub/GitLab or similar repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.\n",
"\n",
"Finally, \n",
"we encourage you to collaborate. Optimal working groups consist of \n",
"2-3 students. You can then hand in a common report."
]
},
{
"cell_type": "markdown",
"id": "e2cae8ee",
"metadata": {
"editable": true
},
"source": [
"## Software and needed installations\n",
"\n",
"If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, \n",
"we recommend that you install the following Python packages via **pip** as\n",
"1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow\n",
"\n",
"For Python3, replace **pip** with **pip3**.\n",
"\n",
"See below for a discussion of **tensorflow** and **scikit-learn**. \n",
"\n",
"For OSX users we recommend also, after having installed Xcode, to install **brew**. Brew allows \n",
"for a seamless installation of additional software via for example\n",
"1. brew install python3\n",
"\n",
"For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution\n",
"you can use **pip** as well and simply install Python as \n",
"1. sudo apt-get install python3 (or python for python2.7)\n",
"\n",
"etc etc. \n",
"\n",
"If you don't want to install various Python packages with their dependencies separately, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely\n",
"1. [Anaconda](https://docs.anaconda.com/) Anaconda is an open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment. Package versions are managed by the package management system **conda**\n",
"\n",
"2. [Enthought canopy](https://www.enthought.com/product/canopy/) is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.\n",
"\n",
"Popular software packages written in Python for ML are\n",
"\n",
"* [Scikit-learn](http://scikit-learn.org/stable/), \n",
"\n",
"* [Tensorflow](https://www.tensorflow.org/),\n",
"\n",
"* [PyTorch](http://pytorch.org/) and \n",
"\n",
"* [Keras](https://keras.io/).\n",
"\n",
"These are all freely available at their respective GitHub sites. They \n",
"encompass communities of developers in the thousands or more. And the number\n",
"of code developers and contributors keeps increasing."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
-341
View File
@@ -1,341 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "5b2f9dda",
"metadata": {},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html Project2.do.txt -->\n",
"<!-- dom:TITLE: Project 2 on Machine Learning, deadline November 4 (Midnight) -->"
]
},
{
"cell_type": "markdown",
"id": "cacbd604",
"metadata": {},
"source": [
"# Project 2 on Machine Learning, deadline November 4 (Midnight)\n",
"**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n",
"\n",
"Date: **Oct 8, 2024**\n",
"\n",
"Copyright 1999-2024, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license"
]
},
{
"cell_type": "markdown",
"id": "acb32119",
"metadata": {},
"source": [
"## Classification and Regression, from linear and logistic regression to neural networks\n",
"\n",
"The main aim of this project is to study both classification and\n",
"regression problems by developing our own feed-forward neural network\n",
"(FFNN) code. We can reuse the regression algorithms studied in project\n",
"1. We will also include logistic regression for classification\n",
"problems and write our own FFNN code for studying both regression and\n",
"classification problems. The codes developed in project 1, including\n",
"bootstrap **and/or** cross-validation as well as the computation of the\n",
"mean-squared error and/or the $R2$ or the accuracy score\n",
"(classification problems) functions can also be utilized in the\n",
"present analysis.\n",
"\n",
"The data sets that we propose here are (the default sets)\n",
"\n",
"* Regression (fitting a continuous function). In this part you will need to bring back your results from project 1 and compare these with what you get from your Neural Network code to be developed here. The data sets could be\n",
"\n",
"a. A simple one-dimensional function or the Franke function or the terrain data from project 1, or data sets your propose. It could be a simpler function than the Franke function. We recommend testing a simpler function (see below). But if you wish to try more complex function, feel free to do so.\n",
"\n",
"* Classification. Here you will also need to develop a Logistic regression code that you will use to compare with the Neural Network code. The data set we propose are the so-called [Wisconsin Breat Cancer Data](https://www.kaggle.com/uciml/breast-cancer-wisconsin-data) data set of images representing various features of tumors. A longer explanation with links to the scientific literature can be found at the [Machine Learning repository of the University of California at Irvine](https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+%28Diagnostic%29). Feel free to consult this site and the pertinent literature.\n",
"\n",
"You can find more information about this at the [Scikit-Learn site](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html) or at the [University of California at Irvine](https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)). \n",
"\n",
"However, if you would like to study other data sets, feel free to\n",
"propose other sets. What we list here are mere suggestions from our\n",
"side. If you opt for another data set, consider using a set which has\n",
"been studied in the scientific literature. This makes it easier for\n",
"you to compare and analyze your results. Comparing with existing\n",
"results from the scientific literature is also an essential element of\n",
"the scientific discussion. The University of California at Irvine\n",
"with its Machine Learning repository at\n",
"<https://archive.ics.uci.edu/ml/index.php> is an excellent site to\n",
"look up for examples and\n",
"inspiration. [Kaggle.com](https://www.kaggle.com/) is an equally\n",
"interesting site. Feel free to explore these sites.\n",
"\n",
"We will start with a regression problem and we will reuse our codes from project 1 starting with writing our own Stochastic Gradient Descent (SGD) code."
]
},
{
"cell_type": "markdown",
"id": "027202f0",
"metadata": {},
"source": [
"### Part a): Write your own Stochastic Gradient Descent code, first step\n",
"\n",
"In order to get started, we will now replace in our standard ordinary\n",
"least squares (OLS) and Ridge regression codes (from project 1) the\n",
"matrix inversion algorithm with our own gradient descent (GD) and SGD\n",
"codes. You can use the Franke function or the terrain data from\n",
"project 1. **However, we recommend using a simpler function like**\n",
"$f(x)=a_0+a_1x+a_2x^2$ or higher-order one-dimensional polynomials.\n",
"You can obviously test your final codes against for example the Franke\n",
"function.\n",
"\n",
"The exercise set for week 41 should help in solving this part of the project.\n",
"\n",
"You should include in your analysis of the GD and SGD codes the following elements\n",
"1. A plain gradient descent with a fixed learning rate (you will need to tune it) using the analytical expression for the gradient.\n",
"\n",
"2. Add momentum to the plain GD code and compare convergence with a fixed learning rate (you may need to tune the learning rate). Keep using the analytical expression for the gradient.\n",
"\n",
"3. Repeat these steps for stochastic gradient descent with mini batches and a given number of epochs. Use a tunable learning rate as discussed in the lectures from weeks 39 and 40. Discuss the results as functions of the various parameters (size of batches, number of epochs etc). Use the analytical gradient.\n",
"\n",
"4. Implement the Adagrad method in order to tune the learning rate. Do this with and without momentum for plain gradient descent and SGD.\n",
"\n",
"5. Add RMSprop and Adam to your library of methods for tuning the learning rate.\n",
"\n",
"The lecture notes from [weeks 39 and 40 contain more\n",
"details](https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html) and code examples. Feel free to use these examples.\n",
"1. Replace thereafter your analytical gradient with either **Autograd** or **JAX**\n",
"\n",
"**Feel free to use codes on these methods from the lecture notes from week 39 and week 40**.\n",
"\n",
"In summary, you should \n",
"perform an analysis of the results for OLS and Ridge regression as\n",
"function of the chosen learning rates, the number of mini-batches and\n",
"epochs as well as algorithm for scaling the learning rate. You can\n",
"also compare your own results with those that can be obtained using\n",
"for example **Scikit-Learn**'s various SGD options. Discuss your\n",
"results. For Ridge regression you need now to study the results as functions of the hyper-parameter $\\lambda$ and \n",
"the learning rate $\\eta$. Discuss your results.\n",
"\n",
"You will need your SGD code for the setup of the Neural Network and\n",
"Logistic Regression codes. You will find the Python [Seaborn\n",
"package](https://seaborn.pydata.org/generated/seaborn.heatmap.html)\n",
"useful when plotting the results as function of the learning rate\n",
"$\\eta$ and the hyper-parameter $\\lambda$ when you use Ridge\n",
"regression. Since you will use different gradient descent methods, you can also add Lasse regression. This is however optional. How to code Lasso regression is discussed in the lecture notes from week 40.\n",
"\n",
"We recommend reading chapter 8 on optimization from the textbook of Goodfellow, Bengio and Courville at <https://www.deeplearningbook.org/>. This chapter contains many useful insights and discussions on the optimization part of machine learning."
]
},
{
"cell_type": "markdown",
"id": "9388fa74",
"metadata": {},
"source": [
"### Part b): Writing your own Neural Network code\n",
"\n",
"Your aim now, and this is the central part of this project, is to\n",
"write your own Feed Forward Neural Network code implementing the back\n",
"propagation algorithm discussed in the lecture slides from [week 41](https://compphysics.github.io/MachineLearning/doc/pub/week41/ipynb/week41.ipynb) and\n",
"[week 42](https://compphysics.github.io/MachineLearning/doc/pub/week42/ipynb/week42.ipynb).\n",
"\n",
"We will focus on a regression problem first and study either the simple second-order polynomial from part a) or the \n",
"Franke function or terrain data (or both or other data sets) from\n",
"project 1.\n",
"\n",
"Discuss again your choice of cost function.\n",
"\n",
"Write an FFNN code for regression with a flexible number of hidden\n",
"layers and nodes using the Sigmoid function as activation function for\n",
"the hidden layers. Initialize the weights using a normal\n",
"distribution. How would you initialize the biases? And which\n",
"activation function would you select for the final output layer?\n",
"\n",
"Train your network and compare the results with those from your OLS and Ridge Regression codes from project 1 if you use the Franke function or the terrain data.\n",
"You should test your results against a similar code using **Scikit-Learn** (see the examples in the above lecture notes from weeks 41 and 42) or **tensorflow/keras** or **Pytorch** (for Pytorch, see Raschka et al.'s text chapters 12 and 13). \n",
"\n",
"Comment your results and give a critical discussion of the results\n",
"obtained with the Linear Regression code and your own Neural Network\n",
"code. \n",
"Make an analysis of the regularization parameters and the learning rates employed to find the optimal MSE and $R2$ scores.\n",
"\n",
"A useful reference on the back progagation algorithm is Nielsen's book at <http://neuralnetworksanddeeplearning.com/>. It is an excellent\n",
"read."
]
},
{
"cell_type": "markdown",
"id": "49666354",
"metadata": {},
"source": [
"### Part c): Testing different activation functions\n",
"\n",
"You should now also test different activation functions for the hidden layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and discuss your results. You may also study the way you initialize your weights and biases."
]
},
{
"cell_type": "markdown",
"id": "79aacf29",
"metadata": {},
"source": [
"### Part d): Classification analysis using neural networks\n",
"\n",
"With a well-written code it should now be easy to change the\n",
"activation function for the output layer.\n",
"\n",
"Here we will change the cost function for our neural network code\n",
"developed in parts b) and c) in order to perform a classification analysis. \n",
"\n",
"We will here study the Wisconsin Breast Cancer data set. This is a typical binary classification problem with just one single output, either True or Fale, $0$ or $1$ etc.\n",
"You find more information about this at the [Scikit-Learn\n",
"site](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html) or at the [University of California\n",
"at Irvine](https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)). \n",
"\n",
"To measure the performance of our classification problem we use the\n",
"so-called *accuracy* score. The accuracy is as you would expect just\n",
"the number of correctly guessed targets $t_i$ divided by the total\n",
"number of targets, that is"
]
},
{
"cell_type": "markdown",
"id": "42e22900",
"metadata": {},
"source": [
"$$\n",
"\\text{Accuracy} = \\frac{\\sum_{i=1}^n I(t_i = y_i)}{n} ,\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "82ae763d",
"metadata": {},
"source": [
"where $I$ is the indicator function, $1$ if $t_i = y_i$ and $0$\n",
"otherwise if we have a binary classification problem. Here $t_i$\n",
"represents the target and $y_i$ the outputs of your FFNN code and $n$ is simply the number of targets $t_i$.\n",
"\n",
"Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter $\\lambda$ (as you did in Ridge Regression), various activation functions, number of hidden layers and nodes and activation functions. \n",
"\n",
"As stated in the introduction, it can also be useful to study other\n",
"datasets. \n",
"\n",
"Again, we strongly recommend that you compare your own neural Network\n",
"code for classification and pertinent results against a similar code using **Scikit-Learn** or **tensorflow/keras** or **pytorch**."
]
},
{
"cell_type": "markdown",
"id": "1d6b84d1",
"metadata": {},
"source": [
"### Part e): Write your Logistic Regression code, final step\n",
"\n",
"Finally, we want to compare the FFNN code we have developed with\n",
"Logistic regression, that is we wish to compare our neural network\n",
"classification results with the results we can obtain with another\n",
"method.\n",
"\n",
"Define your cost function and the design matrix before you start writing your code.\n",
"Write thereafter a Logistic regression code using your SGD algorithm. You can also use standard gradient descent in this case, with a learning rate as hyper-parameter.\n",
"Study the results as functions of the chosen learning rates.\n",
"Add also an $l_2$ regularization parameter $\\lambda$. Compare your results with those from your FFNN code as well as those obtained using **Scikit-Learn**'s logistic regression functionality.\n",
"\n",
"The weblink here <https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3>compares logistic regression and FFNN using the so-called MNIST data set. You may find several useful hints and ideas from this article."
]
},
{
"cell_type": "markdown",
"id": "0bce8832",
"metadata": {},
"source": [
"### Part f) Critical evaluation of the various algorithms\n",
"\n",
"After all these glorious calculations, you should now summarize the\n",
"various algorithms and come with a critical evaluation of their pros\n",
"and cons. Which algorithm works best for the regression case and which\n",
"is best for the classification case. These codes can also be part of\n",
"your final project 3, but now applied to other data sets."
]
},
{
"cell_type": "markdown",
"id": "51b1b29b",
"metadata": {},
"source": [
"## Background literature\n",
"\n",
"1. The text of Michael Nielsen is highly recommended, see Nielsen's book at <http://neuralnetworksanddeeplearning.com/>. It is an excellent read.\n",
"\n",
"2. Goodfellow, Bengio and Courville, Deep Learning at <https://www.deeplearningbook.org/>. Here we recommend chapters 6, 7 and 8\n",
"\n",
"3. Raschka et al. at <https://sebastianraschka.com/blog/2022/ml-pytorch-book.html>. Here we recommend chapters 11, 12 and 13."
]
},
{
"cell_type": "markdown",
"id": "7e4ffbbd",
"metadata": {},
"source": [
"## Introduction to numerical projects\n",
"\n",
"Here follows a brief recipe and recommendation on how to write a report for each\n",
"project.\n",
"\n",
" * Give a short description of the nature of the problem and the eventual numerical methods you have used.\n",
"\n",
" * Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.\n",
"\n",
" * Include the source code of your program. Comment your program properly.\n",
"\n",
" * If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.\n",
"\n",
" * Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.\n",
"\n",
" * Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.\n",
"\n",
" * Try to give an interpretation of you results in your answers to the problems.\n",
"\n",
" * Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.\n",
"\n",
" * Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning."
]
},
{
"cell_type": "markdown",
"id": "56112b03",
"metadata": {},
"source": [
"## Format for electronic delivery of report and programs\n",
"\n",
"The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008 or Python. The following prescription should be followed when preparing the report:\n",
"\n",
" * Use Canvas to hand in your projects, log in at <https://www.uio.no/english/services/it/education/canvas/> with your normal UiO username and password.\n",
"\n",
" * Upload **only** the report file or the link to your GitHub/GitLab or similar typo of repos! For the source code file(s) you have developed please provide us with your link to your GitHub/GitLab or similar domain. The report file should include all of your discussions and a list of the codes you have developed. Do not include library files which are available at the course homepage, unless you have made specific changes to them.\n",
"\n",
" * In your GitHub/GitLab or similar repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.\n",
"\n",
"Finally, \n",
"we encourage you to collaborate. Optimal working groups consist of \n",
"2-3 students. You can then hand in a common report."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.18"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
-564
View File
@@ -1,564 +0,0 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "515b56d5",
"metadata": {
"editable": true
},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html Project3.do.txt -->\n",
"<!-- dom:TITLE: Project 3 on Machine Learning, deadline December 9 (midnight), 2024 -->"
]
},
{
"cell_type": "markdown",
"id": "d08608f0",
"metadata": {
"editable": true
},
"source": [
"# Project 3 on Machine Learning, deadline December 9 (midnight), 2024\n",
"**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n",
"\n",
"Date: **Nov 4, 2024**\n",
"\n",
"Copyright 1999-2024, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license"
]
},
{
"cell_type": "markdown",
"id": "43262ea8",
"metadata": {
"editable": true
},
"source": [
"# Paths for project 3"
]
},
{
"cell_type": "markdown",
"id": "43359271",
"metadata": {
"editable": true
},
"source": [
"## Defining the data sets to analyze yourself\n",
"\n",
"For project 3, you can propose own data sets that relate to your research interests or just use existing data sets from say\n",
"1. [Kaggle](https://www.kaggle.com/datasets) \n",
"\n",
"2. The [University of California at Irvine (UCI) with its machine learning repository](https://archive.ics.uci.edu/ml/index.php).\n",
"\n",
"3. Or other sources.\n",
"\n",
"4. Or you can propose own problems (but please do write to us before you start)\n",
"\n",
"The approach to the analysis of these new data sets should follow to a large extent what you did in projects 1 and 2. That is:\n",
"1. Whether you end up with a regression or a classification problem, you should employ at least two of the methods we have discussed among **linear regression (including Ridge and Lasso)**, **Logistic Regression**, **Neural Networks**, **Convolution Neural Networks**, **Recurrent Neural Networks**, and **Decision Trees, Random Forests, Bagging and Boosting**.\n",
"\n",
"Feel also free to use support vector machines, $k$-means and principal components analysis, although the latter have not been covered during the lectures. This material can be found in the lecture notes.\n",
"\n",
"You could for example explore all of the approaches from decision trees, via bagging and voting classifiers, to random forests, boosting and finally XGboost. If you wish to venture into **convolutional neural networks** or **recurrent neural networks**, or extensions of neural networkds, feel free to do so. You can also study unsupervised methods, although we in this course have mainly paid attention to supervised learning. \n",
"\n",
"For Boosting, feel also free to write your own codes.\n",
"\n",
"1. For project 3, you should feel free to use your own codes from projects 1 and 2, eventually write your own for Decision trees/random forests/bagging/boosting' or use the available functionality of **Scikit-Learn**, **Tensorflow**, PyTorch etc. \n",
"\n",
"2. The estimates you used and tested in projects 1 and 2 should also be included, that is the $R2$-score, **MSE**, confusion matrix, accuracy score, information gain, ROC and Cumulative gains curves and other, cross-validation and/or bootstrap if these are relevant.\n",
"\n",
"3. Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches.\n",
"\n",
"4. If possible, you should link the data sets with exisiting research and analyses thereof. Scientific articles which have used Machine Learning algorithms to analyze the data are highly welcome. Perhaps you can improve previous analyses and even publish a new article? \n",
"\n",
"5. A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include.\n",
"\n",
"All in all, the report should follow the same pattern as the two previous ones, with abstract, introduction, methods, code, results, conclusions etc..\n",
"\n",
"We propose also an alternative to the above. This is a project on\n",
"using machine learning methods (neural networks mainly) to the\n",
"solution of ordinary differential equations and partial differential\n",
"equations, with a final twist on how to diagonalize a symmetric matrix\n",
"with neural networks.\n",
"\n",
"This is a field with large scientific interest, spanning from studies\n",
"of turbulence in fluid mechanics and meteorology to the solution of\n",
"quantum mechanical systems. As reading background you can use the\n",
"slides [from week\n",
"43](https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week42.html)\n",
"and/or the textbook by [Yadav et\n",
"al](https://www.springer.com/gp/book/9789401798150)."
]
},
{
"cell_type": "markdown",
"id": "233aeb80",
"metadata": {
"editable": true
},
"source": [
"## The basic structure of your project\n",
"\n",
"Here follows a set up on how to structure your report and analyze the data you have opted for."
]
},
{
"cell_type": "markdown",
"id": "5e9e9325",
"metadata": {
"editable": true
},
"source": [
"### Part a)\n",
"\n",
"The first part deals with structuring and reading the data, much along the same lines as done in projects 1 and 2. Explain how the data are produced and place them in a proper context."
]
},
{
"cell_type": "markdown",
"id": "180fe836",
"metadata": {
"editable": true
},
"source": [
"### Part b)\n",
"\n",
"You need to include at least two central algorithms, or as an alternative explore methods from decisions tree to bagging, random forests and boosting. Explain the basics of the methods you have chosen to work with. This would be your theory part."
]
},
{
"cell_type": "markdown",
"id": "79044fd5",
"metadata": {
"editable": true
},
"source": [
"### Part c)\n",
"\n",
"Then describe your algorithm and its implementation and tests you have performed."
]
},
{
"cell_type": "markdown",
"id": "1d20adf9",
"metadata": {
"editable": true
},
"source": [
"### Part d)\n",
"\n",
"Then presents your results and findings, link with existing literature and more."
]
},
{
"cell_type": "markdown",
"id": "da0685a9",
"metadata": {
"editable": true
},
"source": [
"### Part e)\n",
"\n",
"Finally, here you should present a critical assessment of the methods you have studied and link your results with the existing literature."
]
},
{
"cell_type": "markdown",
"id": "84f0c1ee",
"metadata": {
"editable": true
},
"source": [
"## Solving partial differential equations with neural networks\n",
"\n",
"This variant of project 3 is tailored to those of you who are\n",
"interested in studying differential equations and may have followed\n",
"popular courses on these methods, see below.\n",
"\n",
"For this variant of project 3, we will assume that you have some\n",
"background in the solution of partial differential equations using\n",
"finite difference schemes. We will study the solution of the diffusion\n",
"equation in one dimension using a standard explicit scheme and neural\n",
"networks to solve the same equations.\n",
"\n",
"For the explicit scheme, you can study for example chapter 10 of the lecture notes in [Computational Physics, FYS3150/4150](https://github.com/CompPhysics/ComputationalPhysics/blob/master/doc/Lectures/lectures2015.pdf) or alternative sources from courses like [MAT-MEK4270](https://www.uio.no/studier/emner/matnat/math/MAT-MEK4270/index.html). For the solution of ordinary and partial differential equations using neural networks, the lectures by of week 43 at for example <https://compphysics.github.io/MachineLearning/doc/pub/week42/html/week43.html> at this course are highly recommended.\n",
"\n",
"For the machine learning part you can use your own code from project 2\n",
"or the functionality of for example **Tensorflow/Keras**, **PyTorch** or\n",
"other libraries such as [Physics informed machine learning](https://maziarraissi.github.io/PINNs/)."
]
},
{
"cell_type": "markdown",
"id": "dff04e8f",
"metadata": {
"editable": true
},
"source": [
"### Alternative differential equations\n",
"\n",
"Note that you can replace the one-dimensional diffusion equation discussed below with other sets of either ordinary differential equations or partial differential equations.\n",
"Please discuss such a change with us at the lab."
]
},
{
"cell_type": "markdown",
"id": "51f14d9f",
"metadata": {
"editable": true
},
"source": [
"### Part a), setting up the problem\n",
"\n",
"The physical problem can be that of the temperature gradient in a rod of length $L=1$ at $x=0$ and $x=1$.\n",
"We are looking at a one-dimensional\n",
"problem"
]
},
{
"cell_type": "markdown",
"id": "6abd2255",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"\\frac{\\partial^2 u(x,t)}{\\partial x^2} =\\frac{\\partial u(x,t)}{\\partial t}, t> 0, x\\in [0,L]\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "4f4a3f3b",
"metadata": {
"editable": true
},
"source": [
"or"
]
},
{
"cell_type": "markdown",
"id": "0cc61e0f",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"u_{xx} = u_t,\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "2bc5108c",
"metadata": {
"editable": true
},
"source": [
"with initial conditions, i.e., the conditions at $t=0$,"
]
},
{
"cell_type": "markdown",
"id": "8c206f31",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"u(x,0)= \\sin{(\\pi x)} \\hspace{0.5cm} 0 < x < L,\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "1dd3f41d",
"metadata": {
"editable": true
},
"source": [
"with $L=1$ the length of the $x$-region of interest. The \n",
"boundary conditions are"
]
},
{
"cell_type": "markdown",
"id": "69aab333",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"u(0,t)= 0 \\hspace{0.5cm} t \\ge 0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "33b3f598",
"metadata": {
"editable": true
},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"id": "ac7742e7",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"u(L,t)= 0 \\hspace{0.5cm} t \\ge 0.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "895cfb4f",
"metadata": {
"editable": true
},
"source": [
"The function $u(x,t)$ can be the temperature gradient of a rod.\n",
"As time increases, the velocity approaches a linear variation with $x$. \n",
"\n",
"We will limit ourselves to the so-called explicit forward Euler algorithm with discretized versions of time given by a forward formula and a centered difference in space resulting in"
]
},
{
"cell_type": "markdown",
"id": "c6622f0d",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"u_t\\approx \\frac{u(x,t+\\Delta t)-u(x,t)}{\\Delta t}=\\frac{u(x_i,t_j+\\Delta t)-u(x_i,t_j)}{\\Delta t}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "3ca63c88",
"metadata": {
"editable": true
},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"id": "29c0ac61",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"u_{xx}\\approx \\frac{u(x+\\Delta x,t)-2u(x,t)+u(x-\\Delta x,t)}{\\Delta x^2},\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "14bb1c45",
"metadata": {
"editable": true
},
"source": [
"or"
]
},
{
"cell_type": "markdown",
"id": "a8107ecb",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"u_{xx}\\approx \\frac{u(x_i+\\Delta x,t_j)-2u(x_i,t_j)+u(x_i-\\Delta x,t_j)}{\\Delta x^2}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "63bd4075",
"metadata": {
"editable": true
},
"source": [
"Write down the algorithm and the equations you need to implement.\n",
"Find also the analytical solution to the problem."
]
},
{
"cell_type": "markdown",
"id": "5c43dc30",
"metadata": {
"editable": true
},
"source": [
"### Part b)\n",
"\n",
"Implement the explicit scheme algorithm and perform tests of the solution \n",
"for $\\Delta x=1/10$, $\\Delta x=1/100$ using $\\Delta t$ as dictated by the stability limit of the explicit scheme. The stability criterion for the explicit scheme requires that $\\Delta t/\\Delta x^2 \\leq 1/2$. \n",
"\n",
"Study the solutions at two time points $t_1$ and $t_2$ where $u(x,t_1)$ is smooth but still significantly curved\n",
"and $u(x,t_2)$ is almost linear, close to the stationary state."
]
},
{
"cell_type": "markdown",
"id": "b0053091",
"metadata": {
"editable": true
},
"source": [
"### Part c) Neural networks\n",
"\n",
"Study now the lecture notes on solving ODEs and PDEs with neural\n",
"network and use either your own code from project 2 or the\n",
"functionality of tensorflow/keras to solve the same equation as in\n",
"part b). Discuss your results and compare them with the standard\n",
"explicit scheme. Include also the analytical solution and compare with\n",
"that."
]
},
{
"cell_type": "markdown",
"id": "2288b721",
"metadata": {
"editable": true
},
"source": [
"### Part d) Neural network complexity\n",
"\n",
"Here we study the stability of the results of the results as functions of the number of hidden nodes, layers and activation functions for the hidden layers.\n",
"Increase the number of hidden nodes and layers in order to see if this improves your results. Try also different activation functions for the hidden layers, such as the **tanh**, **ReLU**, and other activation functions. \n",
"Discuss your results."
]
},
{
"cell_type": "markdown",
"id": "dc9e08fd",
"metadata": {
"editable": true
},
"source": [
"### Part e)\n",
"\n",
"Finally, present a critical assessment of the methods you have studied\n",
"and discuss the potential for the solving differential equations with machine learning methods."
]
},
{
"cell_type": "markdown",
"id": "8c3d752a",
"metadata": {
"editable": true
},
"source": [
"## Introduction to numerical projects\n",
"\n",
"Here follows a brief recipe and recommendation on how to write a report for each\n",
"project.\n",
"\n",
" * Give a short description of the nature of the problem and the eventual numerical methods you have used.\n",
"\n",
" * Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.\n",
"\n",
" * Include the source code of your program. Comment your program properly.\n",
"\n",
" * If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.\n",
"\n",
" * Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.\n",
"\n",
" * Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.\n",
"\n",
" * Try to give an interpretation of you results in your answers to the problems.\n",
"\n",
" * Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.\n",
"\n",
" * Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning."
]
},
{
"cell_type": "markdown",
"id": "a81f1b16",
"metadata": {
"editable": true
},
"source": [
"## Format for electronic delivery of report and programs\n",
"\n",
"The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008 or Python. The following prescription should be followed when preparing the report:\n",
"\n",
" * Use Canvas to hand in your projects, log in at <https://www.uio.no/english/services/it/education/canvas/> with your normal UiO username and password.\n",
"\n",
" * Upload **only** the report file or the link to your GitHub/GitLab or similar typo of repos! For the source code file(s) you have developed please provide us with your link to your GitHub/GitLab or similar domain. The report file should include all of your discussions and a list of the codes you have developed. Do not include library files which are available at the course homepage, unless you have made specific changes to them.\n",
"\n",
" * In your GitHub/GitLab or similar repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.\n",
"\n",
"Finally, \n",
"we encourage you to collaborate. Optimal working groups consist of \n",
"2-3 students. You can then hand in a common report."
]
},
{
"cell_type": "markdown",
"id": "0d14d009",
"metadata": {
"editable": true
},
"source": [
"## Software and needed installations\n",
"\n",
"If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, \n",
"we recommend that you install the following Python packages via **pip** as\n",
"1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow\n",
"\n",
"For Python3, replace **pip** with **pip3**.\n",
"\n",
"See below for a discussion of **tensorflow** and **scikit-learn**. \n",
"\n",
"For OSX users we recommend also, after having installed Xcode, to install **brew**. Brew allows \n",
"for a seamless installation of additional software via for example\n",
"1. brew install python3\n",
"\n",
"For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution\n",
"you can use **pip** as well and simply install Python as \n",
"1. sudo apt-get install python3 (or python for python2.7)\n",
"\n",
"etc etc. \n",
"\n",
"If you don't want to install various Python packages with their dependencies separately, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely\n",
"1. [Anaconda](https://docs.anaconda.com/) Anaconda is an open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment. Package versions are managed by the package management system **conda**\n",
"\n",
"2. [Enthought canopy](https://www.enthought.com/product/canopy/) is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.\n",
"\n",
"Popular software packages written in Python for ML are\n",
"\n",
"* [Scikit-learn](http://scikit-learn.org/stable/), \n",
"\n",
"* [Tensorflow](https://www.tensorflow.org/),\n",
"\n",
"* [PyTorch](http://pytorch.org/) and \n",
"\n",
"* [Keras](https://keras.io/).\n",
"\n",
"These are all freely available at their respective GitHub sites. They \n",
"encompass communities of developers in the thousands or more. And the number\n",
"of code developers and contributors keeps increasing."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}