Files
FYS-STK4155/doc/LectureNotes/_build/html/_sources/week45.ipynb
T
Morten Hjorth-Jensen beb104cebf update
2023-11-09 17:54:42 +01:00

1998 lines
76 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "967cdaca",
"metadata": {
"editable": true
},
"source": [
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
"doconce format html week45.do.txt --no_mako -->\n",
"<!-- dom:TITLE: Week 45, Recurrent Neural Networks -->"
]
},
{
"cell_type": "markdown",
"id": "7f44e4d0",
"metadata": {
"editable": true
},
"source": [
"# Week 45, Recurrent Neural Networks\n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
"Date: **November 6-10**"
]
},
{
"cell_type": "markdown",
"id": "3094316d",
"metadata": {
"editable": true
},
"source": [
"## Plan for week 45\n",
"\n",
"**Material for the active learning sessions on Tuesday and Wednesday.**\n",
"\n",
" * Discussion of project 2\n",
"\n",
" * [Video of lab session from week 43](https://youtu.be/Ia6wwDLxqtM)\n",
"\n",
" * [Video of lab session from week 44](https://youtu.be/EajWMW__k0I)\n",
"\n",
" * [Video of lab session from week 45](https://youtu.be/tgkj0KAEtZo)\n",
"\n",
" * [See also whiteboard notes from lab session week 44](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/Exercisesweek44.pdf)\n",
"\n",
" \n",
"\n",
"**Material for the lecture on Thursday November 9, 2023.**\n",
"\n",
" * Short repetition on Convolutional Neural Networks\n",
"\n",
" * Recurrent Neural Networks (RNNs)\n",
"\n",
" * Readings and Videos:\n",
"\n",
" * These lecture notes\n",
"\n",
" * [Video of lecture](https://youtu.be/z0x-vgyAZUk)\n",
"\n",
" * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesNov9.pdf)\n",
"\n",
" * For a more in depth discussion on neural networks we recommend Goodfellow et al chapter 10. See also chapter 11 and 12 on practicalities and applications \n",
"\n",
" * Reading suggestions for implementation of RNNs: [Aurelien Geron's chapter 14](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf).\n",
"\n",
" * [Video on Recurrent Neural Networks from MIT](https://www.youtube.com/watch?v=SEnXr6v2ifU&ab_channel=AlexanderAmini)\n",
"\n",
" * [Video on Deep Learning](https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi)"
]
},
{
"cell_type": "markdown",
"id": "46b1e9db",
"metadata": {
"editable": true
},
"source": [
"## Material for the lab sessions, additional ways to present classification results and other practicalities"
]
},
{
"cell_type": "markdown",
"id": "19315bd5",
"metadata": {
"editable": true
},
"source": [
"## Searching for Optimal Regularization Parameters $\\lambda$\n",
"\n",
"In project 1, when using Ridge and Lasso regression, we end up\n",
"searching for the optimal parameter $\\lambda$ which minimizes our\n",
"selected scores (MSE or $R2$ values for example). The brute force\n",
"approach, as discussed in the code here for Ridge regression, consists\n",
"in evaluating the MSE as function of different $\\lambda$ values.\n",
"Based on these calculations, one tries then to determine the value of the hyperparameter $\\lambda$\n",
"which results in optimal scores (for example the smallest MSE or an $R2=1$)."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "d03a6f44",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn import linear_model\n",
"\n",
"def MSE(y_data,y_model):\n",
" n = np.size(y_model)\n",
" return np.sum((y_data-y_model)**2)/n\n",
"# A seed just to ensure that the random numbers are the same for every run.\n",
"# Useful for eventual debugging.\n",
"np.random.seed(2021)\n",
"\n",
"n = 100\n",
"x = np.random.rand(n)\n",
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
"\n",
"Maxpolydegree = 5\n",
"X = np.zeros((n,Maxpolydegree-1))\n",
"\n",
"for degree in range(1,Maxpolydegree): #No intercept column\n",
" X[:,degree-1] = x**(degree)\n",
"\n",
"# We split the data in test and training data\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
"\n",
"# Decide which values of lambda to use\n",
"nlambdas = 500\n",
"MSERidgePredict = np.zeros(nlambdas)\n",
"lambdas = np.logspace(-4, 2, nlambdas)\n",
"for i in range(nlambdas):\n",
" lmb = lambdas[i]\n",
" RegRidge = linear_model.Ridge(lmb)\n",
" RegRidge.fit(X_train,y_train)\n",
" ypredictRidge = RegRidge.predict(X_test)\n",
" MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
"\n",
"# Now plot the results\n",
"plt.figure()\n",
"plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')\n",
"plt.xlabel('log10(lambda)')\n",
"plt.ylabel('MSE')\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "e6cbd4ca",
"metadata": {
"editable": true
},
"source": [
"Here we have performed a rather data greedy calculation as function of the regularization parameter $\\lambda$. There is no resampling here. The latter can easily be added by employing the function **RidgeCV** instead of just calling the **Ridge** function. For **RidgeCV** we need to pass the array of $\\lambda$ values.\n",
"By inspecting the figure we can in turn determine which is the optimal regularization parameter.\n",
"This becomes however less functional in the long run."
]
},
{
"cell_type": "markdown",
"id": "1ea723fc",
"metadata": {
"editable": true
},
"source": [
"## Grid Search\n",
"\n",
"An alternative is to use the so-called grid search functionality\n",
"included with the library **Scikit-Learn**, as demonstrated for the same\n",
"example here."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "0ebb62df",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.linear_model import Ridge\n",
"from sklearn.model_selection import GridSearchCV\n",
"\n",
"def R2(y_data, y_model):\n",
" return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
"\n",
"def MSE(y_data,y_model):\n",
" n = np.size(y_model)\n",
" return np.sum((y_data-y_model)**2)/n\n",
"\n",
"# A seed just to ensure that the random numbers are the same for every run.\n",
"# Useful for eventual debugging.\n",
"np.random.seed(2021)\n",
"\n",
"n = 100\n",
"x = np.random.rand(n)\n",
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
"\n",
"Maxpolydegree = 5\n",
"X = np.zeros((n,Maxpolydegree-1))\n",
"\n",
"for degree in range(1,Maxpolydegree): #No intercept column\n",
" X[:,degree-1] = x**(degree)\n",
"\n",
"# We split the data in test and training data\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
"\n",
"# Decide which values of lambda to use\n",
"nlambdas = 10\n",
"lambdas = np.logspace(-4, 2, nlambdas)\n",
"# create and fit a ridge regression model, testing each alpha\n",
"model = Ridge()\n",
"gridsearch = GridSearchCV(estimator=model, param_grid=dict(alpha=lambdas))\n",
"gridsearch.fit(X_train, y_train)\n",
"print(gridsearch)\n",
"ypredictRidge = gridsearch.predict(X_test)\n",
"# summarize the results of the grid search\n",
"print(f\"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}\")\n",
"print(f\"MSE score: {MSE(y_test,ypredictRidge)}\")\n",
"print(f\"R2 score: {R2(y_test,ypredictRidge)}\")"
]
},
{
"cell_type": "markdown",
"id": "0fb161e1",
"metadata": {
"editable": true
},
"source": [
"By default the grid search function includes cross validation with\n",
"five folds. The [Scikit-Learn\n",
"documentation](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV)\n",
"contains more information on how to set the different parameters.\n",
"\n",
"If we take out the random noise, running the above codes results in $\\lambda=0$ yielding the best fit."
]
},
{
"cell_type": "markdown",
"id": "8bdb137e",
"metadata": {
"editable": true
},
"source": [
"## Randomized Grid Search\n",
"\n",
"An alternative to the above manual grid set up, is to use a random\n",
"search where the parameters are tuned from a random distribution\n",
"(uniform below) for a fixed number of iterations. A model is\n",
"constructed and evaluated for each combination of chosen parameters.\n",
"We repeat the previous example but now with a random search. Note\n",
"that values of $\\lambda$ are now limited to be within $x\\in\n",
"[0,1]$. This domain may not be the most relevant one for the specific\n",
"case under study."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "af61779f",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.linear_model import Ridge\n",
"from sklearn.model_selection import GridSearchCV\n",
"from scipy.stats import uniform as randuniform\n",
"from sklearn.model_selection import RandomizedSearchCV\n",
"\n",
"\n",
"def R2(y_data, y_model):\n",
" return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
"\n",
"def MSE(y_data,y_model):\n",
" n = np.size(y_model)\n",
" return np.sum((y_data-y_model)**2)/n\n",
"\n",
"# A seed just to ensure that the random numbers are the same for every run.\n",
"# Useful for eventual debugging.\n",
"np.random.seed(2021)\n",
"\n",
"n = 100\n",
"x = np.random.rand(n)\n",
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n",
"\n",
"Maxpolydegree = 5\n",
"X = np.zeros((n,Maxpolydegree-1))\n",
"\n",
"for degree in range(1,Maxpolydegree): #No intercept column\n",
" X[:,degree-1] = x**(degree)\n",
"\n",
"# We split the data in test and training data\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
"\n",
"param_grid = {'alpha': randuniform()}\n",
"# create and fit a ridge regression model, testing each alpha\n",
"model = Ridge()\n",
"gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)\n",
"gridsearch.fit(X_train, y_train)\n",
"print(gridsearch)\n",
"ypredictRidge = gridsearch.predict(X_test)\n",
"# summarize the results of the grid search\n",
"print(f\"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}\")\n",
"print(f\"MSE score: {MSE(y_test,ypredictRidge)}\")\n",
"print(f\"R2 score: {R2(y_test,ypredictRidge)}\")"
]
},
{
"cell_type": "markdown",
"id": "89f07674",
"metadata": {
"editable": true
},
"source": [
"## Wisconsin Cancer Data\n",
"\n",
"We show here how we can use a simple regression case on the breast\n",
"cancer data using Logistic regression as our algorithm for\n",
"classification."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "37c8ca05",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.linear_model import LogisticRegression\n",
"\n",
"# Load the data\n",
"cancer = load_breast_cancer()\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
"print(X_train.shape)\n",
"print(X_test.shape)\n",
"# Logistic Regression\n",
"logreg = LogisticRegression(solver='lbfgs')\n",
"logreg.fit(X_train, y_train)\n",
"print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))"
]
},
{
"cell_type": "markdown",
"id": "509bf7a9",
"metadata": {
"editable": true
},
"source": [
"## Using the correlation matrix\n",
"\n",
"In addition to the above scores, we could also study the covariance (and the correlation matrix).\n",
"We use **Pandas** to compute the correlation matrix."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "e9d06a0c",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.linear_model import LogisticRegression\n",
"cancer = load_breast_cancer()\n",
"import pandas as pd\n",
"# Making a data frame\n",
"cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n",
"\n",
"fig, axes = plt.subplots(15,2,figsize=(10,20))\n",
"malignant = cancer.data[cancer.target == 0]\n",
"benign = cancer.data[cancer.target == 1]\n",
"ax = axes.ravel()\n",
"\n",
"for i in range(30):\n",
" _, bins = np.histogram(cancer.data[:,i], bins =50)\n",
" ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)\n",
" ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)\n",
" ax[i].set_title(cancer.feature_names[i])\n",
" ax[i].set_yticks(())\n",
"ax[0].set_xlabel(\"Feature magnitude\")\n",
"ax[0].set_ylabel(\"Frequency\")\n",
"ax[0].legend([\"Malignant\", \"Benign\"], loc =\"best\")\n",
"fig.tight_layout()\n",
"plt.show()\n",
"\n",
"import seaborn as sns\n",
"correlation_matrix = cancerpd.corr().round(1)\n",
"# use the heatmap function from seaborn to plot the correlation matrix\n",
"# annot = True to print the values inside the square\n",
"plt.figure(figsize=(15,8))\n",
"sns.heatmap(data=correlation_matrix, annot=True)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "ab1f9810",
"metadata": {
"editable": true
},
"source": [
"## Discussing the correlation data\n",
"\n",
"In the above example we note two things. In the first plot we display\n",
"the overlap of benign and malignant tumors as functions of the various\n",
"features in the Wisconsing breast cancer data set. We see that for\n",
"some of the features we can distinguish clearly the benign and\n",
"malignant cases while for other features we cannot. This can point to\n",
"us which features may be of greater interest when we wish to classify\n",
"a benign or not benign tumour.\n",
"\n",
"In the second figure we have computed the so-called correlation\n",
"matrix, which in our case with thirty features becomes a $30\\times 30$\n",
"matrix.\n",
"\n",
"We constructed this matrix using **pandas** via the statements"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "d8a5dabe",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)"
]
},
{
"cell_type": "markdown",
"id": "69fd6511",
"metadata": {
"editable": true
},
"source": [
"and then"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "b74de9e5",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"correlation_matrix = cancerpd.corr().round(1)"
]
},
{
"cell_type": "markdown",
"id": "24e267e4",
"metadata": {
"editable": true
},
"source": [
"Diagonalizing this matrix we can in turn say something about which\n",
"features are of relevance and which are not. This leads us to\n",
"the classical Principal Component Analysis (PCA) theorem with\n",
"applications. This will be discussed later this semester ([week 43](https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-bs.html))."
]
},
{
"cell_type": "markdown",
"id": "77a9c527",
"metadata": {
"editable": true
},
"source": [
"## Other ways of presenting a classification problem\n",
"\n",
"For a binary classifcation matrix, the so-called **confusion matrix**, is often used. It can also be extended to more catgeories/classes as well.\n",
"The following quantities are then used\n",
"1. positive condition number $P$, which represents the number of real positive cases in the data (output one/true etc)\n",
"\n",
"2. The condition negative number $N$ which is the number of negative cases (ouput zero/false etc)\n",
"\n",
"3. The true positive number $TP$ which represents whether a positive test result has been correctly classified (the application of our trained model on a test data set)\n",
"\n",
"4. The true negative $TN$ number which represents whether a negative test has been correctly classified\n",
"\n",
"5. The false positive $FP$ number, a so-called type I error which tells us about the fraction of positive test result which are wrongly classified\n",
"\n",
"6. A false negative $FN$ number, a so-called type II error which, should be pretty obvious, indicates if a negative test has been wrongly classified.\n",
"\n",
"It is is easy to think in terms of illness. You could think of the above as\n",
"1. True positive: Sick people correctly identified as sick\n",
"\n",
"2. False positive: Healthy people incorrectly identified as sick\n",
"\n",
"3. True negative: Healthy people correctly identified as healthy\n",
"\n",
"4. False negative: Sick people incorrectly identified as healthy"
]
},
{
"cell_type": "markdown",
"id": "5f6ea3f0",
"metadata": {
"editable": true
},
"source": [
"## Combinations of classification results\n",
"\n",
"It is common in the literature to define various combinations the above numbers. The most commonly used are\n",
"\n",
"**Sensitivity, recall, hit rate, or true positive rate $TPR$. It is the probability of a positive test result, conditioned on the individual truly being positive.**"
]
},
{
"cell_type": "markdown",
"id": "b0d324b8",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {TPR} ={\\frac {\\mathrm {TP} }{\\mathrm {P} }}={\\frac {\\mathrm {TP} }{\\mathrm {TP} +\\mathrm {FN} }}=1-\\mathrm {FNR} }\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "d5593af9",
"metadata": {
"editable": true
},
"source": [
"The $TPR$ defines how many correct positive results occur among all positive samples available during the test\n",
"\n",
"**Miss rate or false negative rate $FNR$.**"
]
},
{
"cell_type": "markdown",
"id": "e857f89e",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {FNR} ={\\frac {\\mathrm {FN} }{\\mathrm {P} }}={\\frac {\\mathrm {FN} }{\\mathrm {FN} +\\mathrm {TP} }} }\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "13dc6da3",
"metadata": {
"editable": true
},
"source": [
"**Specificity, selectivity or true negative rate $TNR$. It is the probability of a negative test result, conditioned on the individual truly being negative.**"
]
},
{
"cell_type": "markdown",
"id": "0f77aa9a",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {TNR} ={\\frac {\\mathrm {TN} }{\\mathrm {N} }}={\\frac {\\mathrm {TN} }{\\mathrm {TN} +\\mathrm {FP} }}=1-\\mathrm {FPR} }\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "3c560ddf",
"metadata": {
"editable": true
},
"source": [
"with the fall-out false positive rate"
]
},
{
"cell_type": "markdown",
"id": "b46686df",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {FPR} ={\\frac {\\mathrm {FP} }{\\mathrm {N} }}={\\frac {\\mathrm {FP} }{\\mathrm {FP} +\\mathrm {TN} }}=1-\\mathrm {TNR} }\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "24aec375",
"metadata": {
"editable": true
},
"source": [
"The $FPR$ defines how many incorrect positive results occur among\n",
"all negative samples available during the test."
]
},
{
"cell_type": "markdown",
"id": "8d288b9d",
"metadata": {
"editable": true
},
"source": [
"## Positive and negative prediction values\n",
"\n",
"The positive and negative predictive values \n",
"are the proportions of positive and negative results in statistics and\n",
"diagnostic tests that are true positive and true negative results,\n",
"respectively.[1] The PPV and NPV describe the performance of a\n",
"diagnostic test or other statistical measure. A high result can be\n",
"interpreted as indicating the accuracy of such a statistic.\n",
"\n",
"**Precision or positive predictive value $PPV$.**"
]
},
{
"cell_type": "markdown",
"id": "e1663205",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {PPV} ={\\frac {\\mathrm {TP} }{\\mathrm {TP} +\\mathrm {FP} }}=1-\\mathrm {FDR} }\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "b34d890c",
"metadata": {
"editable": true
},
"source": [
"**Negative predictive value $NPV$.**"
]
},
{
"cell_type": "markdown",
"id": "14e7f314",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {NPV} ={\\frac {\\mathrm {TN} }{\\mathrm {TN} +\\mathrm {FN} }}=1-\\mathrm {FOR} }\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "879bac6b",
"metadata": {
"editable": true
},
"source": [
"## Other quantities\n",
"\n",
"**False discovery rate $FDR$.**"
]
},
{
"cell_type": "markdown",
"id": "31d2b3b7",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {FDR} ={\\frac {\\mathrm {FP} }{\\mathrm {FP} +\\mathrm {TP} }}=1-\\mathrm {PPV} }\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "34fd7537",
"metadata": {
"editable": true
},
"source": [
"**False omission rate $FOR$.**"
]
},
{
"cell_type": "markdown",
"id": "4bebbe84",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {FOR} ={\\frac {\\mathrm {FN} }{\\mathrm {FN} +\\mathrm {TN} }}=1-\\mathrm {NPV} }\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "690c8d76",
"metadata": {
"editable": true
},
"source": [
"## $F_1$ score\n",
"\n",
"In statistical analysis of binary classification, the F-score or\n",
"F-measure is a measure of a test's accuracy. It is calculated from the\n",
"precision and recall of the test, where the precision is the number of\n",
"true positive results divided by the number of all positive results,\n",
"including those not identified correctly, and the recall is the number\n",
"of true positive results divided by the number of all samples that\n",
"should have been identified as positive. Precision is also known as\n",
"positive predictive value, and recall is also known as sensitivity in\n",
"diagnostic binary classification.\n",
"\n",
"The F1 score is the harmonic mean of the precision and recall. It thus\n",
"symmetrically represents both precision and recall in one metric. The\n",
"highest possible value of an F-score is 1.0, indicating perfect\n",
"precision and recall, and the lowest possible value is 0, if either\n",
"precision or recall are zero.\n",
"\n",
"It is defined as"
]
},
{
"cell_type": "markdown",
"id": "12d8a75e",
"metadata": {
"editable": true
},
"source": [
"$$\n",
"{\\displaystyle \\mathrm {F} _{1}=2\\times {\\frac {\\mathrm {PPV} \\times \\mathrm {TPR} }{\\mathrm {PPV} +\\mathrm {TPR} }}={\\frac {2\\mathrm {TP} }{2\\mathrm {TP} +\\mathrm {FP} +\\mathrm {FN} }}}\n",
"$$"
]
},
{
"cell_type": "markdown",
"id": "1df29154",
"metadata": {
"editable": true
},
"source": [
"## ROC curve\n",
"\n",
"A receiver operating characteristic curve, or ROC curve, is a\n",
"graphical plot that illustrates the performance of a binary classifier\n",
"model at varying threshold values.\n",
"\n",
"The ROC curve is the plot of the true positive rate (TPR) against the false positive rate (FPR) at each threshold setting.\n",
"\n",
"To draw a ROC curve, only the true positive rate (TPR) and false\n",
"positive rate (FPR) are needed (as functions of some classifier\n",
"parameter). The TPR defines how many correct positive results occur\n",
"among all positive samples available during the test. FPR, on the\n",
"other hand, defines how many incorrect positive results occur among\n",
"all negative samples available during the test.\n",
"\n",
"See <https://en.wikipedia.org/wiki/Receiver_operating_characteristic> for more discussions."
]
},
{
"cell_type": "markdown",
"id": "9083178e",
"metadata": {
"editable": true
},
"source": [
"## Cumulative gain curve\n",
"\n",
"The cumulative gain curve is a performance evaluation used typically for binary classification problems.\n",
"It plots the $TPR$ True Positive Rate or Sensitivity (which represents the \n",
"fraction of examples correctly classified\n",
"against Predictive Positive Rate, which represents \n",
"the fraction of positively predicted examples.\n",
"\n",
"The examples below show the confusion matrix, the ROC curve and the cumulative gain for the Wisconsin cancer data."
]
},
{
"cell_type": "markdown",
"id": "e7719466",
"metadata": {
"editable": true
},
"source": [
"## Other measures in classification studies: Cancer Data again"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "bcddf060",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.linear_model import LogisticRegression\n",
"\n",
"# Load the data\n",
"cancer = load_breast_cancer()\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
"print(X_train.shape)\n",
"print(X_test.shape)\n",
"# Logistic Regression\n",
"logreg = LogisticRegression(solver='lbfgs')\n",
"logreg.fit(X_train, y_train)\n",
"\n",
"from sklearn.preprocessing import LabelEncoder\n",
"from sklearn.model_selection import cross_validate\n",
"#Cross validation\n",
"accuracy = cross_validate(logreg,X_test,y_test,cv=10)['test_score']\n",
"print(accuracy)\n",
"print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
"\n",
"import scikitplot as skplt\n",
"y_pred = logreg.predict(X_test)\n",
"skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
"plt.show()\n",
"y_probas = logreg.predict_proba(X_test)\n",
"skplt.metrics.plot_roc(y_test, y_probas)\n",
"plt.show()\n",
"skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "6ec55e94",
"metadata": {
"editable": true
},
"source": [
"## Material for Lecture Thursday November 9"
]
},
{
"cell_type": "markdown",
"id": "690b1a08",
"metadata": {
"editable": true
},
"source": [
"## Recurrent neural networks (RNNs): Overarching view\n",
"\n",
"Till now our focus has been, including convolutional neural networks\n",
"as well, on feedforward neural networks. The output or the activations\n",
"flow only in one direction, from the input layer to the output layer.\n",
"\n",
"A recurrent neural network (RNN) looks very much like a feedforward\n",
"neural network, except that it also has connections pointing\n",
"backward. \n",
"\n",
"RNNs are used to analyze time series data such as stock prices, and\n",
"tell you when to buy or sell. In autonomous driving systems, they can\n",
"anticipate car trajectories and help avoid accidents. More generally,\n",
"they can work on sequences of arbitrary lengths, rather than on\n",
"fixed-sized inputs like all the nets we have discussed so far. For\n",
"example, they can take sentences, documents, or audio samples as\n",
"input, making them extremely useful for natural language processing\n",
"systems such as automatic translation and speech-to-text."
]
},
{
"cell_type": "markdown",
"id": "825bc136",
"metadata": {
"editable": true
},
"source": [
"## A simple example"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "ce956b33",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Start importing packages\n",
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import tensorflow as tf\n",
"from tensorflow.keras import datasets, layers, models\n",
"from tensorflow.keras.layers import Input\n",
"from tensorflow.keras.models import Model, Sequential \n",
"from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
"from tensorflow.keras import optimizers \n",
"from tensorflow.keras import regularizers \n",
"from tensorflow.keras.utils import to_categorical \n",
"\n",
"\n",
"\n",
"# convert into dataset matrix\n",
"def convertToMatrix(data, step):\n",
" X, Y =[], []\n",
" for i in range(len(data)-step):\n",
" d=i+step \n",
" X.append(data[i:d,])\n",
" Y.append(data[d,])\n",
" return np.array(X), np.array(Y)\n",
"\n",
"step = 4\n",
"N = 1000 \n",
"Tp = 800 \n",
"\n",
"t=np.arange(0,N)\n",
"x=np.sin(0.02*t)+2*np.random.rand(N)\n",
"df = pd.DataFrame(x)\n",
"df.head()\n",
"\n",
"values=df.values\n",
"train,test = values[0:Tp,:], values[Tp:N,:]\n",
"\n",
"# add step elements into train and test\n",
"test = np.append(test,np.repeat(test[-1,],step))\n",
"train = np.append(train,np.repeat(train[-1,],step))\n",
" \n",
"trainX,trainY =convertToMatrix(train,step)\n",
"testX,testY =convertToMatrix(test,step)\n",
"trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n",
"testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n",
"\n",
"model = Sequential()\n",
"model.add(SimpleRNN(units=32, input_shape=(1,step), activation=\"relu\"))\n",
"model.add(Dense(8, activation=\"relu\")) \n",
"model.add(Dense(1))\n",
"model.compile(loss='mean_squared_error', optimizer='rmsprop')\n",
"model.summary()\n",
"\n",
"model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)\n",
"trainPredict = model.predict(trainX)\n",
"testPredict= model.predict(testX)\n",
"predicted=np.concatenate((trainPredict,testPredict),axis=0)\n",
"\n",
"trainScore = model.evaluate(trainX, trainY, verbose=0)\n",
"print(trainScore)\n",
"plt.plot(df)\n",
"plt.plot(predicted)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "002c4d99",
"metadata": {
"editable": true
},
"source": [
"### RNNs\n",
"\n",
"RNNs are very powerful, because they\n",
"combine two properties:\n",
"1. Distributed hidden state that allows them to store a lot of information about the past efficiently.\n",
"\n",
"2. Non-linear dynamics that allows them to update their hidden state in complicated ways.\n",
"\n",
"With enough neurons and time, RNNs\n",
"can compute anything that can be\n",
"computed by your computer!"
]
},
{
"cell_type": "markdown",
"id": "6572c07f",
"metadata": {
"editable": true
},
"source": [
"## Basic layout\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN1.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN1.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->"
]
},
{
"cell_type": "markdown",
"id": "fbd8e269",
"metadata": {
"editable": true
},
"source": [
"### We need to specify the initial activity state of all the hidden and output units\n",
"\n",
"1. We could just fix these initial states to have some default value like 0.5.\n",
"\n",
"2. But it is better to treat the initial states as learned parameters.\n",
"\n",
"3. We learn them in the same way as we learn the weights.\n",
"\n",
"* Start off with an initial random guess for the initial states.\n",
"\n",
"a. At the end of each training sequence, backpropagate through time all the way to the initial states to get the gradient of the error function with respect to each initial state.\n",
"\n",
"b. Adjust the initial states by following the negative gradient."
]
},
{
"cell_type": "markdown",
"id": "919bb09e",
"metadata": {
"editable": true
},
"source": [
"### We can specify inputs in several ways\n",
"\n",
"1. Specify the initial states of all the units.\n",
"\n",
"2. Specify the initial states of a subset of the units.\n",
"\n",
"3. Specify the states of the same subset of the units at every time step.\n",
"\n",
"This is the natural way to model most sequential data."
]
},
{
"cell_type": "markdown",
"id": "6e3360db",
"metadata": {
"editable": true
},
"source": [
"### We can specify targets in several ways\n",
"\n",
"1. Specify desired final activities of all the units\n",
"\n",
"2. Specify desired activities of all units for the last few steps\n",
"\n",
"* Good for learning attractors\n",
"\n",
"* It is easy to add in extra error derivatives as we backpropagate.\n",
"\n",
" * Specify the desired activity of a subset of the units.\n",
"\n",
"* The other units are input or hidden units. \n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN2.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN2.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN3.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN3.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN4.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN4.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN5.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN5.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->"
]
},
{
"cell_type": "markdown",
"id": "0f284cbd",
"metadata": {
"editable": true
},
"source": [
"### Backpropagation through time\n",
"\n",
"We can think of the recurrent net as a layered, feed-forward\n",
"net with shared weights and then train the feed-forward net\n",
"with weight constraints.\n",
"\n",
"We can also think of this training algorithm in the time domain:\n",
"1. The forward pass builds up a stack of the activities of all the units at each time step.\n",
"\n",
"2. The backward pass peels activities off the stack to compute the error derivatives at each time step.\n",
"\n",
"3. After the backward pass we add together the derivatives at all the different times for each weight."
]
},
{
"cell_type": "markdown",
"id": "b5e9785e",
"metadata": {
"editable": true
},
"source": [
"### The backward pass is linear\n",
"\n",
"1. There is a big difference between the forward and backward passes.\n",
"\n",
"2. In the forward pass we use squashing functions (like the logistic) to prevent the activity vectors from exploding.\n",
"\n",
"3. The backward pass, is completely linear. If you double the error derivatives at the final layer, all the error derivatives will double.\n",
"\n",
"The forward pass determines the slope of the linear function used for\n",
"backpropagating through each neuron\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN6.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN6.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN7.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN7.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN8.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN8.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN9.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN9.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN10.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN10.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN11.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN11.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN12.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN12.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->"
]
},
{
"cell_type": "markdown",
"id": "50a43c30",
"metadata": {
"editable": true
},
"source": [
"## The problem of exploding or vanishing gradients\n",
"* What happens to the magnitude of the gradients as we backpropagate through many layers?\n",
"\n",
"a. If the weights are small, the gradients shrink exponentially.\n",
"\n",
"b. If the weights are big the gradients grow exponentially.\n",
"\n",
"* Typical feed-forward neural nets can cope with these exponential effects because they only have a few hidden layers.\n",
"\n",
"* In an RNN trained on long sequences (e.g. 100 time steps) the gradients can easily explode or vanish.\n",
"\n",
"a. We can avoid this by initializing the weights very carefully.\n",
"\n",
"* Even with good initial weights, its very hard to detect that the current target output depends on an input from many time-steps ago.\n",
"\n",
"RNNs have difficulty dealing with long-range dependencies."
]
},
{
"cell_type": "markdown",
"id": "f3e0d31b",
"metadata": {
"editable": true
},
"source": [
"## Four effective ways to learn an RNN\n",
"1. Long Short Term Memory Make the RNN out of little modules that are designed to remember values for a long time.\n",
"\n",
"2. Hessian Free Optimization: Deal with the vanishing gradients problem by using a fancy optimizer that can detect directions with a tiny gradient but even smaller curvature.\n",
"\n",
"3. Echo State Networks: Initialize the input a hidden and hidden-hidden and output-hidden connections very carefully so that the hidden state has a huge reservoir of weakly coupled oscillators which can be selectively driven by the input.\n",
"\n",
" * ESNs only need to learn the hidden-output connections.\n",
"\n",
"4. Good initialization with momentum Initialize like in Echo State Networks, but then learn all of the connections using momentum"
]
},
{
"cell_type": "markdown",
"id": "b1571231",
"metadata": {
"editable": true
},
"source": [
"### Long Short Term Memory (LSTM)\n",
"\n",
"LSTM uses a memory cell for \n",
" modeling long-range dependencies and avoid vanishing gradient\n",
" problems.\n",
"\n",
"1. Introduced by Hochreiter and Schmidhuber (1997) who solved the problem of getting an RNN to remember things for a long time (like hundreds of time steps).\n",
"\n",
"2. They designed a memory cell using logistic and linear units with multiplicative interactions.\n",
"\n",
"3. Information gets into the cell whenever its “write” gate is on.\n",
"\n",
"4. The information stays in the cell so long as its **keep** gate is on.\n",
"\n",
"5. Information can be read from the cell by turning on its **read** gate."
]
},
{
"cell_type": "markdown",
"id": "e7886dd3",
"metadata": {
"editable": true
},
"source": [
"### Implementing a memory cell in a neural network\n",
"\n",
"To preserve information for a long time in\n",
"the activities of an RNN, we use a circuit\n",
"that implements an analog memory cell.\n",
"\n",
"1. A linear unit that has a self-link with a weight of 1 will maintain its state.\n",
"\n",
"2. Information is stored in the cell by activating its write gate.\n",
"\n",
"3. Information is retrieved by activating the read gate.\n",
"\n",
"4. We can backpropagate through this circuit because logistics are have nice derivatives. \n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN13.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN13.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN14.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN14.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN15.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN15.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN16.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN16.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN17.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN17.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN18.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN18.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN19.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN19.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN20.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN20.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN21.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN21.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->\n",
"\n",
"<!-- dom:FIGURE: [figslides/RNN22.png, width=700 frac=0.9] -->\n",
"<!-- begin figure -->\n",
"\n",
"<img src=\"figslides/RNN22.png\" width=\"700\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
"<!-- end figure -->"
]
},
{
"cell_type": "markdown",
"id": "f878b195",
"metadata": {
"editable": true
},
"source": [
"## An extrapolation example\n",
"\n",
"The following code provides an example of how recurrent neural\n",
"networks can be used to extrapolate to unknown values of physics data\n",
"sets. Specifically, the data sets used in this program come from\n",
"a quantum mechanical many-body calculation of energies as functions of the number of particles."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "1889da48",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"\n",
"# For matrices and calculations\n",
"import numpy as np\n",
"# For machine learning (backend for keras)\n",
"import tensorflow as tf\n",
"# User-friendly machine learning library\n",
"# Front end for TensorFlow\n",
"import tensorflow.keras\n",
"# Different methods from Keras needed to create an RNN\n",
"# This is not necessary but it shortened function calls \n",
"# that need to be used in the code.\n",
"from tensorflow.keras import datasets, layers, models\n",
"from tensorflow.keras.layers import Input\n",
"from tensorflow.keras import regularizers\n",
"from tensorflow.keras.models import Model, Sequential\n",
"from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
"# For timing the code\n",
"from timeit import default_timer as timer\n",
"# For plotting\n",
"import matplotlib.pyplot as plt\n",
"\n",
"\n",
"# The data set\n",
"datatype='VaryDimension'\n",
"X_tot = np.arange(2, 42, 2)\n",
"y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,\n",
"\t-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, \n",
"\t-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])"
]
},
{
"cell_type": "markdown",
"id": "5bf3bea4",
"metadata": {
"editable": true
},
"source": [
"## Formatting the Data\n",
"\n",
"The way the recurrent neural networks are trained in this program\n",
"differs from how machine learning algorithms are usually trained.\n",
"Typically a machine learning algorithm is trained by learning the\n",
"relationship between the x data and the y data. In this program, the\n",
"recurrent neural network will be trained to recognize the relationship\n",
"in a sequence of y values. This is type of data formatting is\n",
"typically used time series forcasting, but it can also be used in any\n",
"extrapolation (time series forecasting is just a specific type of\n",
"extrapolation along the time axis). This method of data formatting\n",
"does not use the x data and assumes that the y data are evenly spaced.\n",
"\n",
"For a standard machine learning algorithm, the training data has the\n",
"form of (x,y) so the machine learning algorithm learns to assiciate a\n",
"y value with a given x value. This is useful when the test data has x\n",
"values within the same range as the training data. However, for this\n",
"application, the x values of the test data are outside of the x values\n",
"of the training data and the traditional method of training a machine\n",
"learning algorithm does not work as well. For this reason, the\n",
"recurrent neural network is trained on sequences of y values of the\n",
"form ((y1, y2), y3), so that the network is concerned with learning\n",
"the pattern of the y data and not the relation between the x and y\n",
"data. As long as the pattern of y data outside of the training region\n",
"stays relatively stable compared to what was inside the training\n",
"region, this method of training can produce accurate extrapolations to\n",
"y values far removed from the training data set.\n",
"\n",
"<!-- -->\n",
"<!-- The idea behind formatting the data in this way comes from [this resource](https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/) and [this one](https://fairyonice.github.io/Understand-Keras%27s-RNN-behind-the-scenes-with-a-sin-wave-example.html). -->\n",
"<!-- -->\n",
"<!-- The following method takes in a y data set and formats it so the \"x data\" are of the form (y1, y2) and the \"y data\" are of the form y3, with extra brackets added in to make the resulting arrays compatable with both Keras and Tensorflow. -->\n",
"<!-- -->\n",
"<!-- Note: Using a sequence length of two is not required for time series forecasting so any lenght of sequence could be used (for example instead of ((y1, y2) y3) you could change the length of sequence to be 4 and the resulting data points would have the form ((y1, y2, y3, y4), y5)). While the following method can be used to create a data set of any sequence length, the remainder of the code expects the length of sequence to be 2. This is because the data sets are very small and the higher the lenght of the sequence the less resulting data points. -->"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "6fc9b3dd",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# FORMAT_DATA\n",
"def format_data(data, length_of_sequence = 2): \n",
" \"\"\"\n",
" Inputs:\n",
" data(a numpy array): the data that will be the inputs to the recurrent neural\n",
" network\n",
" length_of_sequence (an int): the number of elements in one iteration of the\n",
" sequence patter. For a function approximator use length_of_sequence = 2.\n",
" Returns:\n",
" rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its\n",
" dimensions are length of data - length of sequence, length of sequence, \n",
" dimnsion of data\n",
" rnn_output (a numpy array): the training data for the neural network\n",
" Formats data to be used in a recurrent neural network.\n",
" \"\"\"\n",
"\n",
" X, Y = [], []\n",
" for i in range(len(data)-length_of_sequence):\n",
" # Get the next length_of_sequence elements\n",
" a = data[i:i+length_of_sequence]\n",
" # Get the element that immediately follows that\n",
" b = data[i+length_of_sequence]\n",
" # Reshape so that each data point is contained in its own array\n",
" a = np.reshape (a, (len(a), 1))\n",
" X.append(a)\n",
" Y.append(b)\n",
" rnn_input = np.array(X)\n",
" rnn_output = np.array(Y)\n",
"\n",
" return rnn_input, rnn_output\n",
"\n",
"\n",
"# ## Defining the Recurrent Neural Network Using Keras\n",
"# \n",
"# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.\n",
"\n",
"def rnn(length_of_sequences, batch_size = None, stateful = False):\n",
" \"\"\"\n",
" Inputs:\n",
" length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
" when the data is formatted\n",
" batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
" stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
" Returns:\n",
" model (a Keras model): The recurrent neural network that is built and compiled by this\n",
" method\n",
" Builds and compiles a recurrent neural network with one hidden layer and returns the model.\n",
" \"\"\"\n",
" # Number of neurons in the input and output layers\n",
" in_out_neurons = 1\n",
" # Number of neurons in the hidden layer\n",
" hidden_neurons = 200\n",
" # Define the input layer\n",
" inp = Input(batch_shape=(batch_size, \n",
" length_of_sequences, \n",
" in_out_neurons)) \n",
" # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to \n",
" # the network immediately after the input layer\n",
" rnn = SimpleRNN(hidden_neurons, \n",
" return_sequences=False,\n",
" stateful = stateful,\n",
" name=\"RNN\")(inp)\n",
" # Define the output layer as a dense neural network layer (standard neural network layer)\n",
" #and add it to the network immediately after the hidden layer.\n",
" dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
" # Create the machine learning model starting with the input layer and ending with the \n",
" # output layer\n",
" model = Model(inputs=[inp],outputs=[dens])\n",
" # Compile the machine learning model using the mean squared error function as the loss \n",
" # function and an Adams optimizer.\n",
" model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
" return model"
]
},
{
"cell_type": "markdown",
"id": "6b02bff4",
"metadata": {
"editable": true
},
"source": [
"## Predicting New Points With A Trained Recurrent Neural Network"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "7030f585",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def test_rnn (x1, y_test, plot_min, plot_max):\n",
" \"\"\"\n",
" Inputs:\n",
" x1 (a list or numpy array): The complete x component of the data set\n",
" y_test (a list or numpy array): The complete y component of the data set\n",
" plot_min (an int or float): the smallest x value used in the training data\n",
" plot_max (an int or float): the largest x valye used in the training data\n",
" Returns:\n",
" None.\n",
" Uses a trained recurrent neural network model to predict future points in the \n",
" series. Computes the MSE of the predicted data set from the true data set, saves\n",
" the predicted data set to a csv file, and plots the predicted and true data sets w\n",
" while also displaying the data range used for training.\n",
" \"\"\"\n",
" # Add the training data as the first dim points in the predicted data array as these\n",
" # are known values.\n",
" y_pred = y_test[:dim].tolist()\n",
" # Generate the first input to the trained recurrent neural network using the last two \n",
" # points of the training data. Based on how the network was trained this means that it\n",
" # will predict the first point in the data set after the training data. All of the \n",
" # brackets are necessary for Tensorflow.\n",
" next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])\n",
" # Save the very last point in the training data set. This will be used later.\n",
" last = [y_test[dim-1]]\n",
"\n",
" # Iterate until the complete data set is created.\n",
" for i in range (dim, len(y_test)):\n",
" # Predict the next point in the data set using the previous two points.\n",
" next = model.predict(next_input)\n",
" # Append just the number of the predicted data set\n",
" y_pred.append(next[0][0])\n",
" # Create the input that will be used to predict the next data point in the data set.\n",
" next_input = np.array([[last, next[0]]], dtype=np.float64)\n",
" last = next\n",
"\n",
" # Print the mean squared error between the known data set and the predicted data set.\n",
" print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())\n",
" # Save the predicted data set as a csv file for later use\n",
" name = datatype + 'Predicted'+str(dim)+'.csv'\n",
" np.savetxt(name, y_pred, delimiter=',')\n",
" # Plot the known data set and the predicted data set. The red box represents the region that was used\n",
" # for the training data.\n",
" fig, ax = plt.subplots()\n",
" ax.plot(x1, y_test, label=\"true\", linewidth=3)\n",
" ax.plot(x1, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
" ax.legend()\n",
" # Created a red region to represent the points used in the training data.\n",
" ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')\n",
" plt.show()\n",
"\n",
"# Check to make sure the data set is complete\n",
"assert len(X_tot) == len(y_tot)\n",
"\n",
"# This is the number of points that will be used in as the training data\n",
"dim=12\n",
"\n",
"# Separate the training data from the whole data set\n",
"X_train = X_tot[:dim]\n",
"y_train = y_tot[:dim]\n",
"\n",
"\n",
"# Generate the training data for the RNN, using a sequence of 2\n",
"rnn_input, rnn_training = format_data(y_train, 2)\n",
"\n",
"\n",
"# Create a recurrent neural network in Keras and produce a summary of the \n",
"# machine learning model\n",
"model = rnn(length_of_sequences = rnn_input.shape[1])\n",
"model.summary()\n",
"\n",
"# Start the timer. Want to time training+testing\n",
"start = timer()\n",
"# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
"# validation split. Setting verbose to True prints information about each training iteration.\n",
"hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
" verbose=True,validation_split=0.05)\n",
"\n",
"for label in [\"loss\",\"val_loss\"]:\n",
" plt.plot(hist.history[label],label=label)\n",
"\n",
"plt.ylabel(\"loss\")\n",
"plt.xlabel(\"epoch\")\n",
"plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
"plt.legend()\n",
"plt.show()\n",
"\n",
"# Use the trained neural network to predict more points of the data set\n",
"test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
"# Stop the timer and calculate the total time needed.\n",
"end = timer()\n",
"print('Time: ', end-start)"
]
},
{
"cell_type": "markdown",
"id": "53dc1510",
"metadata": {
"editable": true
},
"source": [
"## Other Things to Try\n",
"\n",
"Changing the size of the recurrent neural network and its parameters\n",
"can drastically change the results you get from the model. The below\n",
"code takes the simple recurrent neural network from above and adds a\n",
"second hidden layer, changes the number of neurons in the hidden\n",
"layer, and explicitly declares the activation function of the hidden\n",
"layers to be a sigmoid function. The loss function and optimizer can\n",
"also be changed but are kept the same as the above network. These\n",
"parameters can be tuned to provide the optimal result from the\n",
"network. For some ideas on how to improve the performance of a\n",
"[recurrent neural network](https://danijar.com/tips-for-training-recurrent-neural-networks)."
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "62aa2c1c",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
" \"\"\"\n",
" Inputs:\n",
" length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
" when the data is formatted\n",
" batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
" stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
" Returns:\n",
" model (a Keras model): The recurrent neural network that is built and compiled by this\n",
" method\n",
" Builds and compiles a recurrent neural network with two hidden layers and returns the model.\n",
" \"\"\"\n",
" # Number of neurons in the input and output layers\n",
" in_out_neurons = 1\n",
" # Number of neurons in the hidden layer, increased from the first network\n",
" hidden_neurons = 500\n",
" # Define the input layer\n",
" inp = Input(batch_shape=(batch_size, \n",
" length_of_sequences, \n",
" in_out_neurons)) \n",
" # Create two hidden layers instead of one hidden layer. Explicitly set the activation\n",
" # function to be the sigmoid function (the default value is hyperbolic tangent)\n",
" rnn1 = SimpleRNN(hidden_neurons, \n",
" return_sequences=True, # This needs to be True if another hidden layer is to follow\n",
" stateful = stateful, activation = 'sigmoid',\n",
" name=\"RNN1\")(inp)\n",
" rnn2 = SimpleRNN(hidden_neurons, \n",
" return_sequences=False, activation = 'sigmoid',\n",
" stateful = stateful,\n",
" name=\"RNN2\")(rnn1)\n",
" # Define the output layer as a dense neural network layer (standard neural network layer)\n",
" #and add it to the network immediately after the hidden layer.\n",
" dens = Dense(in_out_neurons,name=\"dense\")(rnn2)\n",
" # Create the machine learning model starting with the input layer and ending with the \n",
" # output layer\n",
" model = Model(inputs=[inp],outputs=[dens])\n",
" # Compile the machine learning model using the mean squared error function as the loss \n",
" # function and an Adams optimizer.\n",
" model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
" return model\n",
"\n",
"# Check to make sure the data set is complete\n",
"assert len(X_tot) == len(y_tot)\n",
"\n",
"# This is the number of points that will be used in as the training data\n",
"dim=12\n",
"\n",
"# Separate the training data from the whole data set\n",
"X_train = X_tot[:dim]\n",
"y_train = y_tot[:dim]\n",
"\n",
"\n",
"# Generate the training data for the RNN, using a sequence of 2\n",
"rnn_input, rnn_training = format_data(y_train, 2)\n",
"\n",
"\n",
"# Create a recurrent neural network in Keras and produce a summary of the \n",
"# machine learning model\n",
"model = rnn_2layers(length_of_sequences = 2)\n",
"model.summary()\n",
"\n",
"# Start the timer. Want to time training+testing\n",
"start = timer()\n",
"# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
"# validation split. Setting verbose to True prints information about each training iteration.\n",
"hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
" verbose=True,validation_split=0.05)\n",
"\n",
"\n",
"# This section plots the training loss and the validation loss as a function of training iteration.\n",
"# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
"# being overtrained.\n",
"for label in [\"loss\",\"val_loss\"]:\n",
" plt.plot(hist.history[label],label=label)\n",
"\n",
"plt.ylabel(\"loss\")\n",
"plt.xlabel(\"epoch\")\n",
"plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
"plt.legend()\n",
"plt.show()\n",
"\n",
"# Use the trained neural network to predict more points of the data set\n",
"test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
"# Stop the timer and calculate the total time needed.\n",
"end = timer()\n",
"print('Time: ', end-start)"
]
},
{
"cell_type": "markdown",
"id": "56fb2d92",
"metadata": {
"editable": true
},
"source": [
"## Other Types of Recurrent Neural Networks\n",
"\n",
"Besides a simple recurrent neural network layer, there are two other\n",
"commonly used types of recurrent neural network layers: Long Short\n",
"Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short\n",
"introduction to these layers see <https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b>\n",
"and <https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b>.\n",
"\n",
"The first network created below is similar to the previous network,\n",
"but it replaces the SimpleRNN layers with LSTM layers. The second\n",
"network below has two hidden layers made up of GRUs, which are\n",
"preceeded by two dense (feeddorward) neural network layers. These\n",
"dense layers \"preprocess\" the data before it reaches the recurrent\n",
"layers. This architecture has been shown to improve the performance\n",
"of recurrent neural networks (see the link above and also\n",
"<https://arxiv.org/pdf/1807.02857.pdf>."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "145ed525",
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
" \"\"\"\n",
" Inputs:\n",
" length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
" when the data is formatted\n",
" batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
" stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
" Returns:\n",
" model (a Keras model): The recurrent neural network that is built and compiled by this\n",
" method\n",
" Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.\n",
" \"\"\"\n",
" # Number of neurons on the input/output layer and the number of neurons in the hidden layer\n",
" in_out_neurons = 1\n",
" hidden_neurons = 250\n",
" # Input Layer\n",
" inp = Input(batch_shape=(batch_size, \n",
" length_of_sequences, \n",
" in_out_neurons)) \n",
" # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)\n",
" rnn= LSTM(hidden_neurons, \n",
" return_sequences=True,\n",
" stateful = stateful,\n",
" name=\"RNN\", use_bias=True, activation='tanh')(inp)\n",
" rnn1 = LSTM(hidden_neurons, \n",
" return_sequences=False,\n",
" stateful = stateful,\n",
" name=\"RNN1\", use_bias=True, activation='tanh')(rnn)\n",
" # Output layer\n",
" dens = Dense(in_out_neurons,name=\"dense\")(rnn1)\n",
" # Define the midel\n",
" model = Model(inputs=[inp],outputs=[dens])\n",
" # Compile the model\n",
" model.compile(loss='mean_squared_error', optimizer='adam') \n",
" # Return the model\n",
" return model\n",
"\n",
"def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):\n",
" \"\"\"\n",
" Inputs:\n",
" length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
" when the data is formatted\n",
" batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
" stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
" Returns:\n",
" model (a Keras model): The recurrent neural network that is built and compiled by this\n",
" method\n",
" Builds and compiles a recurrent neural network with four hidden layers (two dense followed by\n",
" two GRU layers) and returns the model.\n",
" \"\"\" \n",
" # Number of neurons on the input/output layers and hidden layers\n",
" in_out_neurons = 1\n",
" hidden_neurons = 250\n",
" # Input layer\n",
" inp = Input(batch_shape=(batch_size, \n",
" length_of_sequences, \n",
" in_out_neurons)) \n",
" # Hidden Dense (feedforward) layers\n",
" dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)\n",
" dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)\n",
" # Hidden GRU layers\n",
" rnn1 = GRU(hidden_neurons, \n",
" return_sequences=True,\n",
" stateful = stateful,\n",
" name=\"RNN1\", use_bias=True)(dnn1)\n",
" rnn = GRU(hidden_neurons, \n",
" return_sequences=False,\n",
" stateful = stateful,\n",
" name=\"RNN\", use_bias=True)(rnn1)\n",
" # Output layer\n",
" dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
" # Define the model\n",
" model = Model(inputs=[inp],outputs=[dens])\n",
" # Compile the mdoel\n",
" model.compile(loss='mean_squared_error', optimizer='adam') \n",
" # Return the model\n",
" return model\n",
"\n",
"# Check to make sure the data set is complete\n",
"assert len(X_tot) == len(y_tot)\n",
"\n",
"# This is the number of points that will be used in as the training data\n",
"dim=12\n",
"\n",
"# Separate the training data from the whole data set\n",
"X_train = X_tot[:dim]\n",
"y_train = y_tot[:dim]\n",
"\n",
"\n",
"# Generate the training data for the RNN, using a sequence of 2\n",
"rnn_input, rnn_training = format_data(y_train, 2)\n",
"\n",
"\n",
"# Create a recurrent neural network in Keras and produce a summary of the \n",
"# machine learning model\n",
"# Change the method name to reflect which network you want to use\n",
"model = dnn2_gru2(length_of_sequences = 2)\n",
"model.summary()\n",
"\n",
"# Start the timer. Want to time training+testing\n",
"start = timer()\n",
"# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
"# validation split. Setting verbose to True prints information about each training iteration.\n",
"hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
" verbose=True,validation_split=0.05)\n",
"\n",
"\n",
"# This section plots the training loss and the validation loss as a function of training iteration.\n",
"# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
"# being overtrained.\n",
"for label in [\"loss\",\"val_loss\"]:\n",
" plt.plot(hist.history[label],label=label)\n",
"\n",
"plt.ylabel(\"loss\")\n",
"plt.xlabel(\"epoch\")\n",
"plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
"plt.legend()\n",
"plt.show()\n",
"\n",
"# Use the trained neural network to predict more points of the data set\n",
"test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
"# Stop the timer and calculate the total time needed.\n",
"end = timer()\n",
"print('Time: ', end-start)\n",
"\n",
"\n",
"# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)\n",
"# \n",
"# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.\n",
"\n",
"# Check to make sure the data set is complete\n",
"assert len(X_tot) == len(y_tot)\n",
"\n",
"# This is the number of points that will be used in as the training data\n",
"dim=12\n",
"\n",
"# Separate the training data from the whole data set\n",
"X_train = X_tot[:dim]\n",
"y_train = y_tot[:dim]\n",
"\n",
"# Reshape the data for Keras specifications\n",
"X_train = X_train.reshape((dim, 1))\n",
"y_train = y_train.reshape((dim, 1))\n",
"\n",
"\n",
"# Create a recurrent neural network in Keras and produce a summary of the \n",
"# machine learning model\n",
"# Set the sequence length to 1 for regular data formatting \n",
"model = rnn(length_of_sequences = 1)\n",
"model.summary()\n",
"\n",
"# Start the timer. Want to time training+testing\n",
"start = timer()\n",
"# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
"# validation split. Setting verbose to True prints information about each training iteration.\n",
"hist = model.fit(X_train, y_train, batch_size=None, epochs=150, \n",
" verbose=True,validation_split=0.05)\n",
"\n",
"\n",
"# This section plots the training loss and the validation loss as a function of training iteration.\n",
"# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
"# being overtrained.\n",
"for label in [\"loss\",\"val_loss\"]:\n",
" plt.plot(hist.history[label],label=label)\n",
"\n",
"plt.ylabel(\"loss\")\n",
"plt.xlabel(\"epoch\")\n",
"plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
"plt.legend()\n",
"plt.show()\n",
"\n",
"# Use the trained neural network to predict the remaining data points\n",
"X_pred = X_tot[dim:]\n",
"X_pred = X_pred.reshape((len(X_pred), 1))\n",
"y_model = model.predict(X_pred)\n",
"y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))\n",
"\n",
"# Plot the known data set and the predicted data set. The red box represents the region that was used\n",
"# for the training data.\n",
"fig, ax = plt.subplots()\n",
"ax.plot(X_tot, y_tot, label=\"true\", linewidth=3)\n",
"ax.plot(X_tot, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
"ax.legend()\n",
"# Created a red region to represent the points used in the training data.\n",
"ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')\n",
"plt.show()\n",
"\n",
"# Stop the timer and calculate the total time needed.\n",
"end = timer()\n",
"print('Time: ', end-start)"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}