3655 lines
144 KiB
Plaintext
3655 lines
144 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "bb8912ae",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
|
||
"doconce format html week43.do.txt --no_mako -->\n",
|
||
"<!-- dom:TITLE: Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ceeae681",
|
||
"metadata": {},
|
||
"source": [
|
||
"# Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis\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: **Nov 2, 2021**\n",
|
||
"\n",
|
||
"Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0a4121b3",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Plans for week 43\n",
|
||
"\n",
|
||
"* Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks\n",
|
||
"\n",
|
||
" * [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober28.mp4?vrtx=view-as-webpage)\n",
|
||
"\n",
|
||
"* Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis\n",
|
||
"\n",
|
||
" * [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober29.mp4?vrtx=view-as-webpage)\n",
|
||
"\n",
|
||
"**Excellent lectures on CNNs and RNNs.**\n",
|
||
"\n",
|
||
"* [Video on Convolutional Neural Networks from MIT](https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini)\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)\n",
|
||
"\n",
|
||
"**More resources.**\n",
|
||
"\n",
|
||
"* [IN5400 at UiO Lecture](https://www.uio.no/studier/emner/matnat/ifi/IN5400/v20/material/week10/in5400_2020_week10_recurrent_neural_network.pdf)\n",
|
||
"\n",
|
||
"* [CS231 at Stanford Lecture](https://www.youtube.com/watch?v=6niqTuYFZLQ&list=PLzUTmXVwsnXod6WNdg57Yc3zFx_f-RYsq&index=10&ab_channel=StanfordUniversitySchoolofEngineering)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f9660a14",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Reading Recommendations\n",
|
||
"\n",
|
||
"* Goodfellow et al, chapter 10 on Recurrent NNs, chapters 11 and 12 on various practicalities around deep learning are also recommended.\n",
|
||
"\n",
|
||
"* Aurelien Geron, chapter 14 on RNNs."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "842f5497",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Summary on Deep Learning Methods\n",
|
||
"\n",
|
||
"We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).\n",
|
||
"\n",
|
||
"The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c30579aa",
|
||
"metadata": {},
|
||
"source": [
|
||
"## CNNs in brief\n",
|
||
"\n",
|
||
"In summary:\n",
|
||
"\n",
|
||
"* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n",
|
||
"\n",
|
||
"* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n",
|
||
"\n",
|
||
"* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n",
|
||
"\n",
|
||
"* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)\n",
|
||
"\n",
|
||
"* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n",
|
||
"\n",
|
||
"For more material on convolutional networks, we strongly recommend\n",
|
||
"the course\n",
|
||
"[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
|
||
"and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n",
|
||
"\n",
|
||
"However, both standard feed forwards networks and CNNs perform well on data with unknown length.\n",
|
||
"\n",
|
||
"This is where recurrent nueral networks (RNNs) come to our rescue."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cd85c599",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Recurrent neural networks: 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": "44578951",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Set up of an RNN\n",
|
||
"\n",
|
||
"More to text to be added"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "dcef62c4",
|
||
"metadata": {},
|
||
"source": [
|
||
"## A simple example"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 1,
|
||
"id": "d1e1f8b0",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"%matplotlib inline\n",
|
||
"\n",
|
||
"# 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",
|
||
"plt.plot(df)\n",
|
||
"plt.show()\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",
|
||
"\n",
|
||
"index = df.index.values\n",
|
||
"plt.plot(index,df)\n",
|
||
"plt.plot(index,predicted)\n",
|
||
"plt.axvline(df.index[Tp], c=\"r\")\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7a672f93",
|
||
"metadata": {},
|
||
"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": 2,
|
||
"id": "fec7cd79",
|
||
"metadata": {},
|
||
"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": "3c152c36",
|
||
"metadata": {},
|
||
"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": 3,
|
||
"id": "b2900154",
|
||
"metadata": {},
|
||
"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": "eecb1945",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Predicting New Points With A Trained Recurrent Neural Network"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"id": "32b674b8",
|
||
"metadata": {},
|
||
"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": "7fd7f5d6",
|
||
"metadata": {},
|
||
"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": 5,
|
||
"id": "6b4b438e",
|
||
"metadata": {},
|
||
"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": "05df6234",
|
||
"metadata": {},
|
||
"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": 6,
|
||
"id": "e0262cbb",
|
||
"metadata": {},
|
||
"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)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e006cdfd",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Generative Models\n",
|
||
"\n",
|
||
"**Generative models** describe a class of statistical models that are a contrast\n",
|
||
"to **discriminative models**. Informally we say that generative models can\n",
|
||
"generate new data instances while discriminative models discriminate between\n",
|
||
"different kinds of data instances. A generative model could generate new photos\n",
|
||
"of animals that look like 'real' animals while a discriminative model could tell\n",
|
||
"a dog from a cat. More formally, given a data set $x$ and a set of labels /\n",
|
||
"targets $y$. Generative models capture the joint probability $p(x, y)$, or\n",
|
||
"just $p(x)$ if there are no labels, while discriminative models capture the\n",
|
||
"conditional probability $p(y | x)$. Discriminative models generally try to draw\n",
|
||
"boundaries in the data space (often high dimensional), while generative models\n",
|
||
"try to model how data is placed throughout the space.\n",
|
||
"\n",
|
||
"**Note**: this material is thanks to Linus Ekstrøm."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "276dd606",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Generative Adversarial Networks\n",
|
||
"\n",
|
||
"**Generative Adversarial Networks** are a type of unsupervised machine learning\n",
|
||
"algorithm proposed by [Goodfellow et. al](https://arxiv.org/pdf/1406.2661.pdf)\n",
|
||
"in 2014 (short and good article).\n",
|
||
"\n",
|
||
"The simplest formulation of\n",
|
||
"the model is based on a game theoretic approach, *zero sum game*, where we pit\n",
|
||
"two neural networks against one another. We define two rival networks, one\n",
|
||
"generator $g$, and one discriminator $d$. The generator directly produces\n",
|
||
"samples"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ae501166",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"_auto1\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\n",
|
||
" x = g(z; \\theta^{(g)})\n",
|
||
"\\label{_auto1} \\tag{1}\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "409bdfef",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Discriminator\n",
|
||
"The discriminator attempts to distinguish between samples drawn from the\n",
|
||
"training data and samples drawn from the generator. In other words, it tries to\n",
|
||
"tell the difference between the fake data produced by $g$ and the actual data\n",
|
||
"samples we want to do prediction on. The discriminator outputs a probability\n",
|
||
"value given by"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "fb082c5d",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"_auto2\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\n",
|
||
" d(x; \\theta^{(d)})\n",
|
||
"\\label{_auto2} \\tag{2}\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1525ddb5",
|
||
"metadata": {},
|
||
"source": [
|
||
"indicating the probability that $x$ is a real training example rather than a\n",
|
||
"fake sample the generator has generated. The simplest way to formulate the\n",
|
||
"learning process in a generative adversarial network is a zero-sum game, in\n",
|
||
"which a function"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "6aa70c91",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"_auto3\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\n",
|
||
" v(\\theta^{(g)}, \\theta^{(d)})\n",
|
||
"\\label{_auto3} \\tag{3}\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "777e450d",
|
||
"metadata": {},
|
||
"source": [
|
||
"determines the reward for the discriminator, while the generator gets the\n",
|
||
"conjugate reward"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cf5297d4",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"_auto4\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\n",
|
||
" -v(\\theta^{(g)}, \\theta^{(d)})\n",
|
||
"\\label{_auto4} \\tag{4}\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "dbfbe4f0",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Learning Process\n",
|
||
"\n",
|
||
"During learning both of the networks maximize their own reward function, so that\n",
|
||
"the generator gets better and better at tricking the discriminator, while the\n",
|
||
"discriminator gets better and better at telling the difference between the fake\n",
|
||
"and real data. The generator and discriminator alternate on which one trains at\n",
|
||
"one time (i.e. for one epoch). In other words, we keep the generator constant\n",
|
||
"and train the discriminator, then we keep the discriminator constant to train\n",
|
||
"the generator and repeat. It is this back and forth dynamic which lets GANs\n",
|
||
"tackle otherwise intractable generative problems. As the generator improves with\n",
|
||
" training, the discriminator's performance gets worse because it cannot easily\n",
|
||
" tell the difference between real and fake. If the generator ends up succeeding\n",
|
||
" perfectly, the the discriminator will do no better than random guessing i.e.\n",
|
||
" 50\\%. This progression in the training poses a problem for the convergence\n",
|
||
" criteria for GANs. The discriminator feedback gets less meaningful over time,\n",
|
||
" if we continue training after this point then the generator is effectively\n",
|
||
" training on junk data which can undo the learning up to that point. Therefore,\n",
|
||
" we stop training when the discriminator starts outputting $1/2$ everywhere."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "6aa3b96a",
|
||
"metadata": {},
|
||
"source": [
|
||
"## More about the Learning Process\n",
|
||
"\n",
|
||
"At convergence we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a787801c",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"_auto5\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\n",
|
||
" g^* = \\underset{g}{\\mathrm{argmin}}\\hspace{2pt}\n",
|
||
" \\underset{d}{\\mathrm{max}}v(\\theta^{(g)}, \\theta^{(d)})\n",
|
||
"\\label{_auto5} \\tag{5}\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8c433b7e",
|
||
"metadata": {},
|
||
"source": [
|
||
"The default choice for $v$ is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "117a59ec",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"_auto6\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\n",
|
||
" v(\\theta^{(g)}, \\theta^{(d)}) = \\mathbb{E}_{x\\sim p_\\mathrm{data}}\\log d(x)\n",
|
||
" + \\mathbb{E}_{x\\sim p_\\mathrm{model}}\n",
|
||
" \\log (1 - d(x))\n",
|
||
"\\label{_auto6} \\tag{6}\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "036ab1a1",
|
||
"metadata": {},
|
||
"source": [
|
||
"The main motivation for the design of GANs is that the learning process requires\n",
|
||
"neither approximate inference (variational autoencoders for example) nor\n",
|
||
"approximation of a partition function. In the case where"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0e3d13b4",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"_auto7\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\n",
|
||
" \\underset{d}{\\mathrm{max}}v(\\theta^{(g)}, \\theta^{(d)})\n",
|
||
"\\label{_auto7} \\tag{7}\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7a743892",
|
||
"metadata": {},
|
||
"source": [
|
||
"is convex in $\\theta^{(g)} then the procedure is guaranteed to converge and is\n",
|
||
"asymptotically consistent\n",
|
||
"( [Seth Lloyd on QuGANs](https://arxiv.org/pdf/1804.09139.pdf) )."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d4384dbb",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Additional References\n",
|
||
"This is in\n",
|
||
"general not the case and it is possible to get situations where the training\n",
|
||
"process never converges because the generator and discriminator chase one\n",
|
||
"another around in the parameter space indefinitely. A much deeper discussion on\n",
|
||
"the currently open research problem of GAN convergence is available\n",
|
||
"[here](https://www.deeplearningbook.org/contents/generative_models.html). To\n",
|
||
"anyone interested in learning more about GANs it is a highly recommended read.\n",
|
||
"Direct quote: \"In this best-performing formulation, the generator aims to\n",
|
||
"increase the log probability that the discriminator makes a mistake, rather than\n",
|
||
"aiming to decrease the log probability that the discriminator makes the correct\n",
|
||
"prediction.\" [Another interesting read](https://arxiv.org/abs/1701.00160)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b6f72b0f",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Writing Our First Generative Adversarial Network\n",
|
||
"Let us now move on to actually implementing a GAN in tensorflow. We will study\n",
|
||
"the performance of our GAN on the MNIST dataset. This code is based on and\n",
|
||
"adapted from the\n",
|
||
"[google tutorial](https://www.tensorflow.org/tutorials/generative/dcgan)\n",
|
||
"\n",
|
||
"First we import our libraries"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"id": "f62f2392",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import os\n",
|
||
"import time\n",
|
||
"import numpy as np\n",
|
||
"import tensorflow as tf\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from tensorflow.keras import layers\n",
|
||
"from tensorflow.keras.utils import plot_model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "bf56bc45",
|
||
"metadata": {},
|
||
"source": [
|
||
"Next we define our hyperparameters and import our data the usual way"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 8,
|
||
"id": "77f775a5",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"BUFFER_SIZE = 60000\n",
|
||
"BATCH_SIZE = 256\n",
|
||
"EPOCHS = 30\n",
|
||
"\n",
|
||
"data = tf.keras.datasets.mnist.load_data()\n",
|
||
"(train_images, train_labels), (test_images, test_labels) = data\n",
|
||
"train_images = np.reshape(train_images, (train_images.shape[0],\n",
|
||
" 28,\n",
|
||
" 28,\n",
|
||
" 1)).astype('float32')\n",
|
||
"\n",
|
||
"# we normalize between -1 and 1\n",
|
||
"train_images = (train_images - 127.5) / 127.5\n",
|
||
"training_dataset = tf.data.Dataset.from_tensor_slices(\n",
|
||
" train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b850456f",
|
||
"metadata": {},
|
||
"source": [
|
||
"## MNIST and GANs\n",
|
||
"\n",
|
||
"Let's have a quick look"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"id": "18c95981",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"plt.imshow(train_images[0], cmap='Greys')\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "552a9eb3",
|
||
"metadata": {},
|
||
"source": [
|
||
"Now we define our two models. This is where the 'magic' happens. There are a\n",
|
||
"huge amount of possible formulations for both models. A lot of engineering and\n",
|
||
"trial and error can be done here to try to produce better performing models. For\n",
|
||
"more advanced GANs this is by far the step where you can 'make or break' a\n",
|
||
"model.\n",
|
||
"\n",
|
||
"We start with the generator. As stated in the introductory text the generator\n",
|
||
"$g$ upsamples from a random sample to the shape of what we want to predict. In\n",
|
||
"our case we are trying to predict MNIST images ($28\\times 28$ pixels)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"id": "66828365",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def generator_model():\n",
|
||
" \"\"\"\n",
|
||
" The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to\n",
|
||
" produce an image from a random seed. We start with a Dense layer taking this\n",
|
||
" random sample as an input and subsequently upsample through multiple\n",
|
||
" convolutional layers.\n",
|
||
" \"\"\"\n",
|
||
"\n",
|
||
" # we define our model\n",
|
||
" model = tf.keras.Sequential()\n",
|
||
"\n",
|
||
"\n",
|
||
" # adding our input layer. Dense means that every neuron is connected and\n",
|
||
" # the input shape is the shape of our random noise. The units need to match\n",
|
||
" # in some sense the upsampling strides to reach our desired output shape.\n",
|
||
" # we are using 100 random numbers as our seed\n",
|
||
" model.add(layers.Dense(units=7*7*BATCH_SIZE,\n",
|
||
" use_bias=False,\n",
|
||
" input_shape=(100, )))\n",
|
||
" # we normalize the output form the Dense layer\n",
|
||
" model.add(layers.BatchNormalization())\n",
|
||
" # and add an activation function to our 'layer'. LeakyReLU avoids vanishing\n",
|
||
" # gradient problem\n",
|
||
" model.add(layers.LeakyReLU())\n",
|
||
" model.add(layers.Reshape((7, 7, BATCH_SIZE)))\n",
|
||
" assert model.output_shape == (None, 7, 7, BATCH_SIZE)\n",
|
||
" # even though we just added four keras layers we think of everything above\n",
|
||
" # as 'one' layer\n",
|
||
"\n",
|
||
" # next we add our upscaling convolutional layers\n",
|
||
" model.add(layers.Conv2DTranspose(filters=128,\n",
|
||
" kernel_size=(5, 5),\n",
|
||
" strides=(1, 1),\n",
|
||
" padding='same',\n",
|
||
" use_bias=False))\n",
|
||
" model.add(layers.BatchNormalization())\n",
|
||
" model.add(layers.LeakyReLU())\n",
|
||
" assert model.output_shape == (None, 7, 7, 128)\n",
|
||
"\n",
|
||
" model.add(layers.Conv2DTranspose(filters=64,\n",
|
||
" kernel_size=(5, 5),\n",
|
||
" strides=(2, 2),\n",
|
||
" padding='same',\n",
|
||
" use_bias=False))\n",
|
||
" model.add(layers.BatchNormalization())\n",
|
||
" model.add(layers.LeakyReLU())\n",
|
||
" assert model.output_shape == (None, 14, 14, 64)\n",
|
||
"\n",
|
||
" model.add(layers.Conv2DTranspose(filters=1,\n",
|
||
" kernel_size=(5, 5),\n",
|
||
" strides=(2, 2),\n",
|
||
" padding='same',\n",
|
||
" use_bias=False,\n",
|
||
" activation='tanh'))\n",
|
||
" assert model.output_shape == (None, 28, 28, 1)\n",
|
||
"\n",
|
||
" return model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "af3c3094",
|
||
"metadata": {},
|
||
"source": [
|
||
"And there we have our 'simple' generator model. Now we move on to defining our\n",
|
||
"discriminator model $d$, which is a convolutional neural network based image\n",
|
||
"classifier."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 11,
|
||
"id": "6483f1ba",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def discriminator_model():\n",
|
||
" \"\"\"\n",
|
||
" The discriminator is a convolutional neural network based image classifier\n",
|
||
" \"\"\"\n",
|
||
"\n",
|
||
" # we define our model\n",
|
||
" model = tf.keras.Sequential()\n",
|
||
" model.add(layers.Conv2D(filters=64,\n",
|
||
" kernel_size=(5, 5),\n",
|
||
" strides=(2, 2),\n",
|
||
" padding='same',\n",
|
||
" input_shape=[28, 28, 1]))\n",
|
||
" model.add(layers.LeakyReLU())\n",
|
||
" # adding a dropout layer as you do in conv-nets\n",
|
||
" model.add(layers.Dropout(0.3))\n",
|
||
"\n",
|
||
"\n",
|
||
" model.add(layers.Conv2D(filters=128,\n",
|
||
" kernel_size=(5, 5),\n",
|
||
" strides=(2, 2),\n",
|
||
" padding='same'))\n",
|
||
" model.add(layers.LeakyReLU())\n",
|
||
" # adding a dropout layer as you do in conv-nets\n",
|
||
" model.add(layers.Dropout(0.3))\n",
|
||
"\n",
|
||
" model.add(layers.Flatten())\n",
|
||
" model.add(layers.Dense(1))\n",
|
||
"\n",
|
||
" return model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7d330ae6",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Other Models\n",
|
||
"Let us take a look at our models. **Note**: double click images for bigger view."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 12,
|
||
"id": "3e5f5e35",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"generator = generator_model()\n",
|
||
"plot_model(generator, show_shapes=True, rankdir='LR')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 13,
|
||
"id": "b1bac2c7",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"discriminator = discriminator_model()\n",
|
||
"plot_model(discriminator, show_shapes=True, rankdir='LR')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "faa440ef",
|
||
"metadata": {},
|
||
"source": [
|
||
"Next we need a few helper objects we will use in training"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 14,
|
||
"id": "07992584",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n",
|
||
"generator_optimizer = tf.keras.optimizers.Adam(1e-4)\n",
|
||
"discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e7750195",
|
||
"metadata": {},
|
||
"source": [
|
||
"The first object, *cross_entropy* is our loss function and the two others are\n",
|
||
"our optimizers. Notice we use the same learning rate for both $g$ and $d$. This\n",
|
||
"is because they need to improve their accuracy at approximately equal speeds to\n",
|
||
"get convergence (not necessarily exactly equal). Now we define our loss\n",
|
||
"functions"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 15,
|
||
"id": "6764500d",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def generator_loss(fake_output):\n",
|
||
" loss = cross_entropy(tf.ones_like(fake_output), fake_output)\n",
|
||
"\n",
|
||
" return loss"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 16,
|
||
"id": "451117b8",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def discriminator_loss(real_output, fake_output):\n",
|
||
" real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n",
|
||
" fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)\n",
|
||
" total_loss = real_loss + fake_loss\n",
|
||
"\n",
|
||
" return total_loss"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a1a2558f",
|
||
"metadata": {},
|
||
"source": [
|
||
"Next we define a kind of seed to help us compare the learning process over\n",
|
||
"multiple training epochs."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 17,
|
||
"id": "fd419bf0",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"noise_dimension = 100\n",
|
||
"n_examples_to_generate = 16\n",
|
||
"seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "21d5ab6b",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Training Step\n",
|
||
"\n",
|
||
"Now we have everything we need to define our training step, which we will apply\n",
|
||
"for every step in our training loop. Notice the @tf.function flag signifying\n",
|
||
"that the function is tensorflow 'compiled'. Removing this flag doubles the\n",
|
||
"computation time."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 18,
|
||
"id": "5e3d108e",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"@tf.function\n",
|
||
"def train_step(images):\n",
|
||
" noise = tf.random.normal([BATCH_SIZE, noise_dimension])\n",
|
||
"\n",
|
||
" with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n",
|
||
" generated_images = generator(noise, training=True)\n",
|
||
"\n",
|
||
" real_output = discriminator(images, training=True)\n",
|
||
" fake_output = discriminator(generated_images, training=True)\n",
|
||
"\n",
|
||
" gen_loss = generator_loss(fake_output)\n",
|
||
" disc_loss = discriminator_loss(real_output, fake_output)\n",
|
||
"\n",
|
||
" gradients_of_generator = gen_tape.gradient(gen_loss,\n",
|
||
" generator.trainable_variables)\n",
|
||
" gradients_of_discriminator = disc_tape.gradient(disc_loss,\n",
|
||
" discriminator.trainable_variables)\n",
|
||
" generator_optimizer.apply_gradients(zip(gradients_of_generator,\n",
|
||
" generator.trainable_variables))\n",
|
||
" discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,\n",
|
||
" discriminator.trainable_variables))\n",
|
||
"\n",
|
||
" return gen_loss, disc_loss"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2a3a8802",
|
||
"metadata": {},
|
||
"source": [
|
||
"Next we define a helper function to produce an output over our training epochs\n",
|
||
"to see the predictive progression of our generator model. **Note**: I am including\n",
|
||
"this code here, but comment it out in the training loop."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 19,
|
||
"id": "bca416b1",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def generate_and_save_images(model, epoch, test_input):\n",
|
||
" # we're making inferences here\n",
|
||
" predictions = model(test_input, training=False)\n",
|
||
"\n",
|
||
" fig = plt.figure(figsize=(4, 4))\n",
|
||
"\n",
|
||
" for i in range(predictions.shape[0]):\n",
|
||
" plt.subplot(4, 4, i+1)\n",
|
||
" plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')\n",
|
||
" plt.axis('off')\n",
|
||
"\n",
|
||
" plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')\n",
|
||
" plt.close()\n",
|
||
" #plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "651e1db3",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Checkpoints\n",
|
||
"Setting up checkpoints to periodically save our model during training so that\n",
|
||
"everything is not lost even if the program were to somehow terminate while\n",
|
||
"training."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 20,
|
||
"id": "d8cedbc7",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Setting up checkpoints to save model during training\n",
|
||
"checkpoint_dir = './training_checkpoints'\n",
|
||
"checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')\n",
|
||
"checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n",
|
||
" discriminator_optimizer=discriminator_optimizer,\n",
|
||
" generator=generator,\n",
|
||
" discriminator=discriminator)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a53622bb",
|
||
"metadata": {},
|
||
"source": [
|
||
"Now we define our training loop"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 21,
|
||
"id": "9f4c3228",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def train(dataset, epochs):\n",
|
||
" generator_loss_list = []\n",
|
||
" discriminator_loss_list = []\n",
|
||
"\n",
|
||
" for epoch in range(epochs):\n",
|
||
" start = time.time()\n",
|
||
"\n",
|
||
" for image_batch in dataset:\n",
|
||
" gen_loss, disc_loss = train_step(image_batch)\n",
|
||
" generator_loss_list.append(gen_loss.numpy())\n",
|
||
" discriminator_loss_list.append(disc_loss.numpy())\n",
|
||
"\n",
|
||
" #generate_and_save_images(generator, epoch + 1, seed_images)\n",
|
||
"\n",
|
||
" if (epoch + 1) % 15 == 0:\n",
|
||
" checkpoint.save(file_prefix=checkpoint_prefix)\n",
|
||
"\n",
|
||
" print(f'Time for epoch {epoch} is {time.time() - start}')\n",
|
||
"\n",
|
||
" #generate_and_save_images(generator, epochs, seed_images)\n",
|
||
"\n",
|
||
" loss_file = './data/lossfile.txt'\n",
|
||
" with open(loss_file, 'w') as outfile:\n",
|
||
" outfile.write(str(generator_loss_list))\n",
|
||
" outfile.write('\\n')\n",
|
||
" outfile.write('\\n')\n",
|
||
" outfile.write(str(discriminator_loss_list))\n",
|
||
" outfile.write('\\n')\n",
|
||
" outfile.write('\\n')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b58cebd6",
|
||
"metadata": {},
|
||
"source": [
|
||
"To train simply call this function. **Warning**: this might take a long time so\n",
|
||
"there is a folder of a pretrained network already included in the repository."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 22,
|
||
"id": "26eb959a",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"train(train_dataset, EPOCHS)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2a6252cd",
|
||
"metadata": {},
|
||
"source": [
|
||
"And here is the result of training our model for 100 epochs\n",
|
||
"\n",
|
||
"<!-- dom:MOVIE: [images_from_seed_images/generation.gif] -->\n",
|
||
"<!-- begin movie -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 23,
|
||
"id": "f5244029",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"from IPython.display import HTML\n",
|
||
"_s = \"\"\"\n",
|
||
"<embed src=\"images_from_seed_images/generation.gif\" autoplay=\"false\" loop=\"true\"></embed>\n",
|
||
"<p><em></em></p>\n",
|
||
"\"\"\"\n",
|
||
"HTML(_s)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "87f98505",
|
||
"metadata": {},
|
||
"source": [
|
||
"<!-- end movie -->\n",
|
||
"\n",
|
||
"Now to avoid having to train and everything, which will take a while depending\n",
|
||
"on your computer setup we now load in the model which produced the above gif."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 24,
|
||
"id": "63b2441d",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))\n",
|
||
"restored_generator = checkpoint.generator\n",
|
||
"restored_discriminator = checkpoint.discriminator\n",
|
||
"\n",
|
||
"print(restored_generator)\n",
|
||
"print(restored_discriminator)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "6b7f4858",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Exploring the Latent Space\n",
|
||
"\n",
|
||
"We have successfully loaded in our latest model. Let us now play around a bit\n",
|
||
"and see what kind of things we can learn about this model. Our generator takes\n",
|
||
"an array of 100 numbers. One idea can be to try to systematically change our\n",
|
||
"input. Let us try and see what we get"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 25,
|
||
"id": "7efda30c",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def generate_latent_points(number=100, scale_means=1, scale_stds=1):\n",
|
||
" latent_dim = 100\n",
|
||
" means = scale_means * tf.linspace(-1, 1, num=latent_dim)\n",
|
||
" stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)\n",
|
||
" latent_space_value_range = tf.random.normal([number, latent_dim],\n",
|
||
" means,\n",
|
||
" stds,\n",
|
||
" dtype=tf.float64)\n",
|
||
"\n",
|
||
" return latent_space_value_range\n",
|
||
"\n",
|
||
"def generate_images(latent_points):\n",
|
||
" # notice we set training to false because we are making inferences\n",
|
||
" generated_images = restored_generator.predict(latent_points)\n",
|
||
"\n",
|
||
" return generated_images"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 26,
|
||
"id": "ebcb4e13",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def plot_result(generated_images, number=100):\n",
|
||
" # obviously this assumes sqrt number is an int\n",
|
||
" fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),\n",
|
||
" figsize=(10, 10))\n",
|
||
"\n",
|
||
" for i in range(int(np.sqrt(number))):\n",
|
||
" for j in range(int(np.sqrt(number))):\n",
|
||
" axs[i, j].imshow(generated_images[i*j], cmap='Greys')\n",
|
||
" axs[i, j].axis('off')\n",
|
||
"\n",
|
||
" plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 27,
|
||
"id": "642701d2",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"generated_images = generate_images(generate_latent_points())\n",
|
||
"plot_result(generated_images)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0cc143f4",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Getting Results\n",
|
||
"We see that the generator generates images that look like MNIST\n",
|
||
"numbers: $1, 4, 7, 9$. Let's try to tweak it a bit more to see if we are able\n",
|
||
"to generate a similar plot where we generate every MNIST number. Let us now try\n",
|
||
"to 'move' a bit around in the latent space. **Note**: decrease the plot number if\n",
|
||
"these following cells take too long to run on your computer."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 28,
|
||
"id": "4f808525",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"plot_number = 225\n",
|
||
"\n",
|
||
"generated_images = generate_images(generate_latent_points(number=plot_number,\n",
|
||
" scale_means=5,\n",
|
||
" scale_stds=1))\n",
|
||
"plot_result(generated_images, number=plot_number)\n",
|
||
"\n",
|
||
"generated_images = generate_images(generate_latent_points(number=plot_number,\n",
|
||
" scale_means=-5,\n",
|
||
" scale_stds=1))\n",
|
||
"plot_result(generated_images, number=plot_number)\n",
|
||
"\n",
|
||
"generated_images = generate_images(generate_latent_points(number=plot_number,\n",
|
||
" scale_means=1,\n",
|
||
" scale_stds=5))\n",
|
||
"plot_result(generated_images, number=plot_number)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5b71261e",
|
||
"metadata": {},
|
||
"source": [
|
||
"Again, we have found something interesting. *Moving* around using our means\n",
|
||
"takes us from digit to digit, while *moving* around using our standard\n",
|
||
"deviations seem to increase the number of different digits! In the last image\n",
|
||
"above, we can barely make out every MNIST digit. Let us make on last plot using\n",
|
||
"this information by upping the standard deviation of our Gaussian noises."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 29,
|
||
"id": "88c574cb",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"plot_number = 400\n",
|
||
"generated_images = generate_images(generate_latent_points(number=plot_number,\n",
|
||
" scale_means=1,\n",
|
||
" scale_stds=10))\n",
|
||
"plot_result(generated_images, number=plot_number)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "60489075",
|
||
"metadata": {},
|
||
"source": [
|
||
"A pretty cool result! We see that our generator indeed has learned a\n",
|
||
"distribution which qualitatively looks a whole lot like the MNIST dataset."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cba87cde",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Interpolating Between MNIST Digits\n",
|
||
"Another interesting way to explore the latent space of our generator model is by\n",
|
||
"interpolating between the MNIST digits. This section is largely based on\n",
|
||
"[this excellent blogpost](https://machinelearningmastery.com/how-to-interpolate-and-perform-vector-arithmetic-with-faces-using-a-generative-adversarial-network/)\n",
|
||
"by Jason Brownlee.\n",
|
||
"\n",
|
||
"So let us start by defining a function to interpolate between two points in the\n",
|
||
"latent space."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 30,
|
||
"id": "8262fb8d",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"def interpolation(point_1, point_2, n_steps=10):\n",
|
||
" ratios = np.linspace(0, 1, num=n_steps)\n",
|
||
" vectors = []\n",
|
||
" for i, ratio in enumerate(ratios):\n",
|
||
" vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))\n",
|
||
"\n",
|
||
" return tf.stack(vectors)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1a1ec074",
|
||
"metadata": {},
|
||
"source": [
|
||
"Now we have all we need to do our interpolation analysis."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 31,
|
||
"id": "69c03d1f",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"plot_number = 100\n",
|
||
"latent_points = generate_latent_points(number=plot_number)\n",
|
||
"results = None\n",
|
||
"for i in range(0, 2*np.sqrt(plot_number), 2):\n",
|
||
" interpolated = interpolation(latent_points[i], latent_points[i+1])\n",
|
||
" generated_images = generate_images(interpolated)\n",
|
||
"\n",
|
||
" if results is None:\n",
|
||
" results = generated_images\n",
|
||
" else:\n",
|
||
" results = tf.stack((results, generated_images))\n",
|
||
"\n",
|
||
"plot_results(results, plot_number)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b02e88cc",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Basic ideas of the Principal Component Analysis (PCA)\n",
|
||
"\n",
|
||
"The principal component analysis deals with the problem of fitting a\n",
|
||
"low-dimensional affine subspace $S$ of dimension $d$ much smaller than\n",
|
||
"the total dimension $D$ of the problem at hand (our data\n",
|
||
"set). Mathematically it can be formulated as a statistical problem or\n",
|
||
"a geometric problem. In our discussion of the theorem for the\n",
|
||
"classical PCA, we will stay with a statistical approach. \n",
|
||
"Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable.\n",
|
||
"\n",
|
||
"We have a data set defined by a design/feature matrix $\\boldsymbol{X}$ (see below for its definition) \n",
|
||
"* Each data point is determined by $p$ extrinsic (measurement) variables\n",
|
||
"\n",
|
||
"* We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data?\n",
|
||
"\n",
|
||
"* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. \n",
|
||
"\n",
|
||
"A good read is for example [Vidal, Ma and Sastry](https://www.springer.com/gp/book/9780387878102)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "76a4925b",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Introducing the Covariance and Correlation functions\n",
|
||
"\n",
|
||
"Before we discuss the PCA theorem, we need to remind ourselves about\n",
|
||
"the definition of the covariance and the correlation function. These are quantities \n",
|
||
"\n",
|
||
"Suppose we have defined two vectors\n",
|
||
"$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1cc2d6ef",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
|
||
" \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
|
||
" \\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b07a53be",
|
||
"metadata": {},
|
||
"source": [
|
||
"where for example"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a8f008d7",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a3ad97c5",
|
||
"metadata": {},
|
||
"source": [
|
||
"With this definition and recalling that the variance is defined as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "19aaf866",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "9e747bef",
|
||
"metadata": {},
|
||
"source": [
|
||
"we can rewrite the covariance matrix as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e0864a69",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
|
||
" \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
|
||
" \\end{bmatrix}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "039a6d65",
|
||
"metadata": {},
|
||
"source": [
|
||
"## More on the covariance\n",
|
||
"The covariance takes values between zero and infinity and may thus\n",
|
||
"lead to problems with loss of numerical precision for particularly\n",
|
||
"large values. It is common to scale the covariance matrix by\n",
|
||
"introducing instead the correlation matrix defined via the so-called\n",
|
||
"correlation function"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f9663947",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "224c5a0d",
|
||
"metadata": {},
|
||
"source": [
|
||
"The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n",
|
||
"\\in [-1,1]$. This avoids eventual problems with too large values. We\n",
|
||
"can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
|
||
"and $\\boldsymbol{y}$ as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "51db7478",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
|
||
" \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
|
||
" \\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "95588be8",
|
||
"metadata": {},
|
||
"source": [
|
||
"In the above example this is the function we constructed using **pandas**."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c6e38449",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Reminding ourselves about Linear Regression\n",
|
||
"In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
|
||
"we defined the design/feature matrix $\\boldsymbol{X}$ as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "80b2a71a",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{X}=\\begin{bmatrix}\n",
|
||
"x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
|
||
"x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
|
||
"x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
|
||
"\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
|
||
"x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
|
||
"x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
|
||
"\\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0a864e62",
|
||
"metadata": {},
|
||
"source": [
|
||
"with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n",
|
||
"entries $n$ being the row elements.\n",
|
||
"We can rewrite the design/feature matrix in terms of its column vectors as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "12721f7c",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5d971502",
|
||
"metadata": {},
|
||
"source": [
|
||
"with a given vector"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "49da9cc9",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2560e5d2",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Simple Example\n",
|
||
"With these definitions, we can now rewrite our $2\\times 2$\n",
|
||
"correlation/covariance matrix in terms of a moe general design/feature\n",
|
||
"matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
|
||
"covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "be68f9f9",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
|
||
"\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
|
||
"\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
|
||
"\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
|
||
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
|
||
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
|
||
"\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n",
|
||
"\\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "27ac6510",
|
||
"metadata": {},
|
||
"source": [
|
||
"## The Correlation Matrix\n",
|
||
"\n",
|
||
"and the correlation matrix"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "6acb8936",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
|
||
"1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
|
||
"\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
|
||
"\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
|
||
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
|
||
"\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
|
||
"\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n",
|
||
"\\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "506094b3",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Numpy Functionality\n",
|
||
"\n",
|
||
"The Numpy function **np.cov** calculates the covariance elements using\n",
|
||
"the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
|
||
"the exact mean values. The following simple function uses the\n",
|
||
"**np.vstack** function which takes each vector of dimension $1\\times n$\n",
|
||
"and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d4487e42",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{W}^T = \\begin{bmatrix} x_0 & y_0 \\\\\n",
|
||
" x_1 & y_1 \\\\\n",
|
||
" x_2 & y_2\\\\\n",
|
||
" \\dots & \\dots \\\\\n",
|
||
" x_{n-2} & y_{n-2}\\\\\n",
|
||
" x_{n-1} & y_{n-1} & \n",
|
||
" \\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4c5e9844",
|
||
"metadata": {},
|
||
"source": [
|
||
"which in turn is converted into into the $2\\times 2$ covariance matrix\n",
|
||
"$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n",
|
||
"the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
|
||
"function **np.mean(x)**. We can also extract the eigenvalues of the\n",
|
||
"covariance matrix through the **np.linalg.eig()** function."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 32,
|
||
"id": "ae930dba",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Importing various packages\n",
|
||
"import numpy as np\n",
|
||
"n = 100\n",
|
||
"x = np.random.normal(size=n)\n",
|
||
"print(np.mean(x))\n",
|
||
"y = 4+3*x+np.random.normal(size=n)\n",
|
||
"print(np.mean(y))\n",
|
||
"W = np.vstack((x, y))\n",
|
||
"C = np.cov(W)\n",
|
||
"print(C)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "60e9a1c8",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Correlation Matrix again\n",
|
||
"\n",
|
||
"The previous example can be converted into the correlation matrix by\n",
|
||
"simply scaling the matrix elements with the variances. We should also\n",
|
||
"subtract the mean values for each column. This leads to the following\n",
|
||
"code which sets up the correlations matrix for the previous example in\n",
|
||
"a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 33,
|
||
"id": "faa6e59e",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"n = 100\n",
|
||
"# define two vectors \n",
|
||
"x = np.random.random(size=n)\n",
|
||
"y = 4+3*x+np.random.normal(size=n)\n",
|
||
"#scaling the x and y vectors \n",
|
||
"x = x - np.mean(x)\n",
|
||
"y = y - np.mean(y)\n",
|
||
"variance_x = np.sum(x@x)/n\n",
|
||
"variance_y = np.sum(y@y)/n\n",
|
||
"print(variance_x)\n",
|
||
"print(variance_y)\n",
|
||
"cov_xy = np.sum(x@y)/n\n",
|
||
"cov_xx = np.sum(x@x)/n\n",
|
||
"cov_yy = np.sum(y@y)/n\n",
|
||
"C = np.zeros((2,2))\n",
|
||
"C[0,0]= cov_xx/variance_x\n",
|
||
"C[1,1]= cov_yy/variance_y\n",
|
||
"C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
|
||
"C[1,0]= C[0,1]\n",
|
||
"print(C)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "40ae29f3",
|
||
"metadata": {},
|
||
"source": [
|
||
"We see that the matrix elements along the diagonal are one as they\n",
|
||
"should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
|
||
"this matrix we easily see that it is a positive definite matrix.\n",
|
||
"\n",
|
||
"The above procedure with **numpy** can be made more compact if we use **pandas**."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e2c9e103",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Using Pandas\n",
|
||
"\n",
|
||
"We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 34,
|
||
"id": "d07566bf",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"n = 10\n",
|
||
"x = np.random.normal(size=n)\n",
|
||
"x = x - np.mean(x)\n",
|
||
"y = 4+3*x+np.random.normal(size=n)\n",
|
||
"y = y - np.mean(y)\n",
|
||
"X = (np.vstack((x, y))).T\n",
|
||
"print(X)\n",
|
||
"Xpd = pd.DataFrame(X)\n",
|
||
"print(Xpd)\n",
|
||
"correlation_matrix = Xpd.corr()\n",
|
||
"print(correlation_matrix)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "acec1fe2",
|
||
"metadata": {},
|
||
"source": [
|
||
"## And then the Franke Function\n",
|
||
"\n",
|
||
"We expand this model to the Franke function discussed above."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 35,
|
||
"id": "0a5bbf22",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"\n",
|
||
"\n",
|
||
"def FrankeFunction(x,y):\n",
|
||
"\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
|
||
"\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
|
||
"\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
|
||
"\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
|
||
"\treturn term1 + term2 + term3 + term4\n",
|
||
"\n",
|
||
"\n",
|
||
"def create_X(x, y, n ):\n",
|
||
"\tif len(x.shape) > 1:\n",
|
||
"\t\tx = np.ravel(x)\n",
|
||
"\t\ty = np.ravel(y)\n",
|
||
"\n",
|
||
"\tN = len(x)\n",
|
||
"\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
|
||
"\tX = np.ones((N,l))\n",
|
||
"\n",
|
||
"\tfor i in range(1,n+1):\n",
|
||
"\t\tq = int((i)*(i+1)/2)\n",
|
||
"\t\tfor k in range(i+1):\n",
|
||
"\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
|
||
"\n",
|
||
"\treturn X\n",
|
||
"\n",
|
||
"\n",
|
||
"# Making meshgrid of datapoints and compute Franke's function\n",
|
||
"n = 4\n",
|
||
"N = 100\n",
|
||
"x = np.sort(np.random.uniform(0, 1, N))\n",
|
||
"y = np.sort(np.random.uniform(0, 1, N))\n",
|
||
"z = FrankeFunction(x, y)\n",
|
||
"X = create_X(x, y, n=n) \n",
|
||
"\n",
|
||
"Xpd = pd.DataFrame(X)\n",
|
||
"# subtract the mean values and set up the covariance matrix\n",
|
||
"Xpd = Xpd - Xpd.mean()\n",
|
||
"covariance_matrix = Xpd.cov()\n",
|
||
"print(covariance_matrix)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ec627c6e",
|
||
"metadata": {},
|
||
"source": [
|
||
"We note here that the covariance is zero for the first rows and\n",
|
||
"columns since all matrix elements in the design matrix were set to one\n",
|
||
"(we are fitting the function in terms of a polynomial of degree $n$). We would however not include the intercept\n",
|
||
"and wee can simply\n",
|
||
"drop these elements and construct a correlation\n",
|
||
"matrix without them by centering our matrix elements by subtracting the mean of each column."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b079de1e",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Lnks with the Design Matrix\n",
|
||
"\n",
|
||
"We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b7ce13ea",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "84fe601b",
|
||
"metadata": {},
|
||
"source": [
|
||
"To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b84be038",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{X}=\\begin{bmatrix}\n",
|
||
"x_{00} & x_{01}\\\\\n",
|
||
"x_{10} & x_{11}\\\\\n",
|
||
"\\end{bmatrix}=\\begin{bmatrix}\n",
|
||
"\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
|
||
"\\end{bmatrix}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "bcd07175",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Computing the Expectation Values\n",
|
||
"\n",
|
||
"If we then compute the expectation value"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "825d6441",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
|
||
"x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
|
||
"x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
|
||
"\\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c09ed5ee",
|
||
"metadata": {},
|
||
"source": [
|
||
"which is just"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "621930aa",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n",
|
||
" \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
|
||
" \\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c5374307",
|
||
"metadata": {},
|
||
"source": [
|
||
"where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
|
||
"\n",
|
||
"It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ab2ad5de",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Towards the PCA theorem\n",
|
||
"\n",
|
||
"We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "969874ba",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2b0ea2d2",
|
||
"metadata": {},
|
||
"source": [
|
||
"Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\\boldsymbol{S}$.\n",
|
||
"These matrices are defined as $\\boldsymbol{S}\\in {\\mathbb{R}}^{p\\times p}$ and obey the orthogonality requirements $\\boldsymbol{S}\\boldsymbol{S}^T=\\boldsymbol{S}^T\\boldsymbol{S}=\\boldsymbol{I}$. The matrix can be written out in terms of the column vectors $\\boldsymbol{s}_i$ as $\\boldsymbol{S}=[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$ and $\\boldsymbol{s}_i \\in {\\mathbb{R}}^{p}$.\n",
|
||
"\n",
|
||
"Assume also that there is a transformation $\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}=\\boldsymbol{C}[\\boldsymbol{y}]$ such that the new matrix $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal with elements $[\\lambda_0,\\lambda_1,\\lambda_2,\\dots,\\lambda_{p-1}]$. \n",
|
||
"\n",
|
||
"That is we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "624d3544",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{C}[\\boldsymbol{y}] = \\mathbb{E}[\\boldsymbol{S}^T\\boldsymbol{X}^T\\boldsymbol{X}T\\boldsymbol{S}]=\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3823d17a",
|
||
"metadata": {},
|
||
"source": [
|
||
"since the matrix $\\boldsymbol{S}$ is not a data dependent matrix. Multiplying with $\\boldsymbol{S}$ from the left we have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "46a38924",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "151b9a1e",
|
||
"metadata": {},
|
||
"source": [
|
||
"and since $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2a02d193",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{S}_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}_i.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "977d900a",
|
||
"metadata": {},
|
||
"source": [
|
||
"## More on the PCA Theorem\n",
|
||
"\n",
|
||
"In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is\n",
|
||
"$\\lambda_0 > \\lambda_1 > \\dots > \\lambda_{p-1}$. \n",
|
||
"\n",
|
||
"The eigenvalues tell us then how much we need to stretch the\n",
|
||
"corresponding eigenvectors. Dimensions with large eigenvalues have\n",
|
||
"thus large variations (large variance) and define therefore useful\n",
|
||
"dimensions. The data points are more spread out in the direction of\n",
|
||
"these eigenvectors. Smaller eigenvalues mean on the other hand that\n",
|
||
"the corresponding eigenvectors are shrunk accordingly and the data\n",
|
||
"points are tightly bunched together and there is not much variation in\n",
|
||
"these specific directions. Hopefully then we could leave it out\n",
|
||
"dimensions where the eigenvalues are very small. If $p$ is very large,\n",
|
||
"we could then aim at reducing $p$ to $l << p$ and handle only $l$\n",
|
||
"features/predictors."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a4d95520",
|
||
"metadata": {},
|
||
"source": [
|
||
"## The Algorithm before theorem\n",
|
||
"\n",
|
||
"Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. \n",
|
||
"* Set up the datapoints for the design/feature matrix $\\boldsymbol{X}$ with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ referring to the column numbers and the entries $n$ being the row elements."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4f53f1d9",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{X}=\\begin{bmatrix}\n",
|
||
"x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
|
||
"x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
|
||
"x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
|
||
"\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
|
||
"x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
|
||
"x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
|
||
"\\end{bmatrix},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3bc1325d",
|
||
"metadata": {},
|
||
"source": [
|
||
"* Center the data by subtracting the mean value for each column. This leads to a new matrix $\\boldsymbol{X}\\rightarrow \\overline{\\boldsymbol{X}}$.\n",
|
||
"\n",
|
||
"* Compute then the covariance/correlation matrix $\\mathbb{E}[\\overline{\\boldsymbol{X}}^T\\overline{\\boldsymbol{X}}]$.\n",
|
||
"\n",
|
||
"* Find the eigenpairs of $\\boldsymbol{C}$ with eigenvalues $[\\lambda_0,\\lambda_1,\\dots,\\lambda_{p-1}]$ and eigenvectors $[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$.\n",
|
||
"\n",
|
||
"* Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.\n",
|
||
"\n",
|
||
"* Keep only those $l$ eigenvalues larger than a selected threshold value, discarding thus $p-l$ features since we expect small variations in the data here."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "677fbdd5",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Writing our own PCA code\n",
|
||
"\n",
|
||
"We will use a simple example first with two-dimensional data\n",
|
||
"drawn from a multivariate normal distribution with the following mean and covariance matrix (we have fixed these quantities but will play around with them below):"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3af6eec6",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mu = (-1,2) \\qquad \\Sigma = \\begin{bmatrix} 4 & 2 \\\\\n",
|
||
"2 & 2\n",
|
||
"\\end{bmatrix}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7b4579b4",
|
||
"metadata": {},
|
||
"source": [
|
||
"Note that the mean refers to each column of data. \n",
|
||
"We will generate $n = 10000$ points $X = \\{ x_1, \\ldots, x_N \\}$ from\n",
|
||
"this distribution, and store them in the $1000 \\times 2$ matrix $\\boldsymbol{X}$. This is our design matrix where we have forced the covariance and mean values to take specific values."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8938e57e",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Implementing it\n",
|
||
"The following Python code aids in setting up the data and writing out the design matrix.\n",
|
||
"Note that the function **multivariate** returns also the covariance discussed above and that it is defined by dividing by $n-1$ instead of $n$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 2,
|
||
"id": "ec1e3f1e",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from IPython.display import display\n",
|
||
"n = 10000\n",
|
||
"mean = (-1, 2)\n",
|
||
"cov = [[10, 0.02], [0.02, 0.05]]\n",
|
||
"X = np.random.multivariate_normal(mean, cov, n)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "48ce0d35",
|
||
"metadata": {},
|
||
"source": [
|
||
"Now we are going to implement the PCA algorithm. We will break it down into various substeps."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ecbc0719",
|
||
"metadata": {},
|
||
"source": [
|
||
"## First Step\n",
|
||
"\n",
|
||
"The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0087d2dc",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mu_n = \\frac{1}{n} \\sum_{i=1}^n x_i\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e8489d42",
|
||
"metadata": {},
|
||
"source": [
|
||
"and the mean-centered data $\\bar{X} = \\{ \\bar{x}_1, \\ldots, \\bar{x}_n \\}$ takes the form"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "9a557753",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\bar{x}_i = x_i - \\mu_n.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "de3a6bd4",
|
||
"metadata": {},
|
||
"source": [
|
||
"When you are done with these steps, print out $\\mu_n$ to verify it is\n",
|
||
"close to $\\mu$ and plot your mean centered data to verify it is\n",
|
||
"centered at the origin! \n",
|
||
"The following code elements perform these operations using **pandas** or using our own functionality for doing so. The latter, using **numpy** is rather simple through the **mean()** function."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"id": "04a64c6f",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"df = pd.DataFrame(X)\n",
|
||
"# Pandas does the centering for us\n",
|
||
"df = df -df.mean()\n",
|
||
"# we center it ourselves\n",
|
||
"X_centered = X - X.mean(axis=0)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "380e11e6",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Scaling\n",
|
||
"Alternatively, we could use the functions we discussed\n",
|
||
"earlier for scaling the data set. That is, we could have used the\n",
|
||
"**StandardScaler** function in **Scikit-Learn**, a function which ensures\n",
|
||
"that for each feature/predictor we study the mean value is zero and\n",
|
||
"the variance is one (every column in the design/feature matrix). You\n",
|
||
"would then not get the same results, since we divide by the\n",
|
||
"variance. The diagonal covariance matrix elements will then be one,\n",
|
||
"while the non-diagonal ones need to be divided by $2\\sqrt{2}$ for our\n",
|
||
"specific case."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "313212af",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Centered Data\n",
|
||
"\n",
|
||
"Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "bf5aa29c",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\Sigma_n = \\frac{1}{n-1} \\sum_{i=1}^n \\bar{x}_i^T \\bar{x}_i = \\frac{1}{n-1} \\sum_{i=1}^n (x_i - \\mu_n)^T (x_i - \\mu_n)\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cabe6168",
|
||
"metadata": {},
|
||
"source": [
|
||
"where the data points $x_i \\in \\mathbb{R}^p$ (here in this example $p = 2$) are column vectors and $x^T$ is the transpose of $x$.\n",
|
||
"We can write our own code or simply use either the functionaly of **numpy** or that of **pandas**, as follows"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"id": "16b51366",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
" 0 1\n",
|
||
"0 9.876569 0.022155\n",
|
||
"1 0.022155 0.048984\n",
|
||
"[[9.87656905 0.0221551 ]\n",
|
||
" [0.0221551 0.04898395]]\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"print(df.cov())\n",
|
||
"print(np.cov(X_centered.T))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f4795982",
|
||
"metadata": {},
|
||
"source": [
|
||
"Note that the way we define the covariance matrix here has a factor $n-1$ instead of $n$. This is included in the **cov()** function by **numpy** and **pandas**. \n",
|
||
"Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific $2\\times 2$ covariance matrix."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 5,
|
||
"id": "a17a2264",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Centered covariance using own code\n",
|
||
"[[9.87656905 0.0221551 ]\n",
|
||
" [0.0221551 0.04898395]]\n"
|
||
]
|
||
},
|
||
{
|
||
"data": {
|
||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXIAAAD5CAYAAAA6JL6mAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAjb0lEQVR4nO3de3xU9Z3/8ddnZnIhkURIIpAQjAGRFQpGI1TwbldttVbs2na9/Ly0pXXXdbftdlvq4/Hb3cc+tna7/emv/dmfVlHpr9W2dhddL+uVVgqiQDCCIgETLgIBnARMIJDrfH9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ure size 432x288 with 1 Axes>"
|
||
]
|
||
},
|
||
"metadata": {
|
||
"needs_background": "light"
|
||
},
|
||
"output_type": "display_data"
|
||
}
|
||
],
|
||
"source": [
|
||
"# extract the relevant columns from the centered design matrix of dim n x 2\n",
|
||
"x = X_centered[:,0]\n",
|
||
"y = X_centered[:,1]\n",
|
||
"Cov = np.zeros((2,2))\n",
|
||
"Cov[0,1] = np.sum(x.T@y)/(n-1.0)\n",
|
||
"Cov[0,0] = np.sum(x.T@x)/(n-1.0)\n",
|
||
"Cov[1,1] = np.sum(y.T@y)/(n-1.0)\n",
|
||
"Cov[1,0]= Cov[0,1]\n",
|
||
"print(\"Centered covariance using own code\")\n",
|
||
"print(Cov)\n",
|
||
"plt.plot(x, y, 'x')\n",
|
||
"plt.axis('equal')\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d8c79888",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Exploring\n",
|
||
"\n",
|
||
"Depending on the number of points $n$, we will get results that are close to the covariance values defined above.\n",
|
||
"The plot shows how the data are clustered around a line with slope close to one. Is this expected? Try to change the covariance and the mean values. For example, try to make the variance of the first element much larger than that of the second diagonal element. Try also to shrink the covariance (the non-diagonal elements) and see how the data points are distributed."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0f3c4bbe",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Diagonalize the sample covariance matrix to obtain the principal components\n",
|
||
"\n",
|
||
"Now we are ready to solve for the principal components! To do so we\n",
|
||
"diagonalize the sample covariance matrix $\\Sigma$. We can use the\n",
|
||
"function **np.linalg.eig** to do so. It will return the eigenvalues and\n",
|
||
"eigenvectors of $\\Sigma$. Once we have these we can perform the \n",
|
||
"following tasks:\n",
|
||
"\n",
|
||
"* We compute the percentage of the total variance captured by the first principal component\n",
|
||
"\n",
|
||
"* We plot the mean centered data and lines along the first and second principal components\n",
|
||
"\n",
|
||
"* Then we project the mean centered data onto the first and second principal components, and plot the projected data. \n",
|
||
"\n",
|
||
"* Finally, we approximate the data as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1b2237a0",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"x_i \\approx \\tilde{x}_i = \\mu_n + \\langle x_i, v_0 \\rangle v_0\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "422430b2",
|
||
"metadata": {},
|
||
"source": [
|
||
"where $v_0$ is the first principal component."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2853d3af",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Collecting all Steps\n",
|
||
"\n",
|
||
"Collecting all these steps we can write our own PCA function and\n",
|
||
"compare this with the functionality included in **Scikit-Learn**. \n",
|
||
"\n",
|
||
"The code here outlines some of the elements we could include in the\n",
|
||
"analysis. Feel free to extend upon this in order to address the above\n",
|
||
"questions."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"id": "f1553a35",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Eigenvalues of Covariance matrix\n",
|
||
"9.876618994986675\n",
|
||
"0.0489340085461999\n",
|
||
"First eigenvector\n",
|
||
"[0.99999746 0.00225436]\n",
|
||
"Second eigenvector\n",
|
||
"[-0.00225436 0.99999746]\n",
|
||
"Eigenvector of largest eigenvalue\n",
|
||
"[-0.99999746 -0.00225436]\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"# diagonalize and obtain eigenvalues, not necessarily sorted\n",
|
||
"EigValues, EigVectors = np.linalg.eig(Cov)\n",
|
||
"# sort eigenvectors and eigenvalues\n",
|
||
"#permute = EigValues.argsort()\n",
|
||
"#EigValues = EigValues[permute]\n",
|
||
"#EigVectors = EigVectors[:,permute]\n",
|
||
"print(\"Eigenvalues of Covariance matrix\")\n",
|
||
"for i in range(2):\n",
|
||
" print(EigValues[i])\n",
|
||
"FirstEigvector = EigVectors[:,0]\n",
|
||
"SecondEigvector = EigVectors[:,1]\n",
|
||
"print(\"First eigenvector\")\n",
|
||
"print(FirstEigvector)\n",
|
||
"print(\"Second eigenvector\")\n",
|
||
"print(SecondEigvector)\n",
|
||
"#thereafter we do a PCA with Scikit-learn\n",
|
||
"from sklearn.decomposition import PCA\n",
|
||
"pca = PCA(n_components = 2)\n",
|
||
"X2Dsl = pca.fit_transform(X)\n",
|
||
"print(\"Eigenvector of largest eigenvalue\")\n",
|
||
"print(pca.components_.T[:, 0])"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f14f4a68",
|
||
"metadata": {},
|
||
"source": [
|
||
"This code does not contain all the above elements, but it shows how we can use **Scikit-Learn** to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then?"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ff48c8be",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Classical PCA Theorem\n",
|
||
"\n",
|
||
"We assume now that we have a design matrix $\\boldsymbol{X}$ which has been\n",
|
||
"centered as discussed above. For the sake of simplicity we skip the\n",
|
||
"overline symbol. The matrix is defined in terms of the various column\n",
|
||
"vectors $[\\boldsymbol{x}_0,\\boldsymbol{x}_1,\\dots, \\boldsymbol{x}_{p-1}]$ each with dimension\n",
|
||
"$\\boldsymbol{x}\\in {\\mathbb{R}}^{n}$.\n",
|
||
"\n",
|
||
"The PCA theorem states that minimizing the above reconstruction error\n",
|
||
"corresponds to setting $\\boldsymbol{W}=\\boldsymbol{S}$, the orthogonal matrix which\n",
|
||
"diagonalizes the empirical covariance(correlation) matrix. The optimal\n",
|
||
"low-dimensional encoding of the data is then given by a set of vectors\n",
|
||
"$\\boldsymbol{z}_i$ with at most $l$ vectors, with $l << p$, defined by the\n",
|
||
"orthogonal projection of the data onto the columns spanned by the\n",
|
||
"eigenvectors of the covariance(correlations matrix)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f93b8c77",
|
||
"metadata": {},
|
||
"source": [
|
||
"## The PCA Theorem\n",
|
||
"\n",
|
||
"To show the PCA theorem let us start with the assumption that there is one vector $\\boldsymbol{s}_0$ which corresponds to a solution which minimized the reconstruction error $J$. This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of $\\boldsymbol{w}_0$ and $\\boldsymbol{z}_0$ as\n",
|
||
"\n",
|
||
"We are almost there, we have obtained a relation between minimizing\n",
|
||
"the reconstruction error and the variance and the covariance\n",
|
||
"matrix. Minimizing the error is equivalent to maximizing the variance\n",
|
||
"of the projected data.\n",
|
||
"\n",
|
||
"We could trivially maximize the variance of the projection (and\n",
|
||
"thereby minimize the error in the reconstruction function) by letting\n",
|
||
"the norm-2 of $\\boldsymbol{w}_0$ go to infinity. However, this norm since we\n",
|
||
"want the matrix $\\boldsymbol{W}$ to be an orthogonal matrix, is constrained by\n",
|
||
"$\\vert\\vert \\boldsymbol{w}_0 \\vert\\vert_2^2=1$. Imposing this condition via a\n",
|
||
"Lagrange multiplier we can then in turn maximize"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7d7f444a",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"J(\\boldsymbol{w}_0)= \\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0+\\lambda_0(1-\\boldsymbol{w}_0^T\\boldsymbol{w}_0).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "757137f1",
|
||
"metadata": {},
|
||
"source": [
|
||
"Taking the derivative with respect to $\\boldsymbol{w}_0$ we obtain"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cf073fb5",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial J(\\boldsymbol{w}_0)}{\\partial \\boldsymbol{w}_0}= 2\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0-2\\lambda_0\\boldsymbol{w}_0=0,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "46cacc57",
|
||
"metadata": {},
|
||
"source": [
|
||
"meaning that"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b9d752e0",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0\\boldsymbol{w}_0.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3a2a1499",
|
||
"metadata": {},
|
||
"source": [
|
||
"**The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix**! If we left multiply with $\\boldsymbol{w}_0^T$ we have the variance of the projected data is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4c0d5781",
|
||
"metadata": {},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "92dd2fd5",
|
||
"metadata": {},
|
||
"source": [
|
||
"If we want to maximize the variance (minimize the construction error)\n",
|
||
"we simply pick the eigenvector of the covariance matrix with the\n",
|
||
"largest eigenvalue. This establishes the link between the minimization\n",
|
||
"of the reconstruction function $J$ in terms of an orthogonal matrix\n",
|
||
"and the maximization of the variance and thereby the covariance of our\n",
|
||
"observations encoded in the design/feature matrix $\\boldsymbol{X}$.\n",
|
||
"\n",
|
||
"The proof\n",
|
||
"for the other eigenvectors $\\boldsymbol{w}_1,\\boldsymbol{w}_2,\\dots$ can be\n",
|
||
"established by applying the above arguments and using the fact that\n",
|
||
"our basis of eigenvectors is orthogonal, see [Murphy chapter\n",
|
||
"12.2](https://mitpress.mit.edu/books/machine-learning-1). The\n",
|
||
"discussion in chapter 12.2 of Murphy's text has also a nice link with\n",
|
||
"the Singular Value Decomposition theorem. For categorical data, see\n",
|
||
"chapter 12.4 and discussion therein.\n",
|
||
"\n",
|
||
"For more details, see for example [Vidal, Ma and Sastry, chapter 2](https://www.springer.com/gp/book/9780387878102)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b3fbff3b",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Geometric Interpretation and link with Singular Value Decomposition\n",
|
||
"\n",
|
||
"For a detailed demonstration of the geometric interpretation, see [Vidal, Ma and Sastry, section 2.1.2](https://www.springer.com/gp/book/9780387878102).\n",
|
||
"\n",
|
||
"Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.\n",
|
||
"First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.\n",
|
||
"\n",
|
||
"The following Python code uses NumPy’s **svd()** function to obtain all the principal components of the\n",
|
||
"training set, then extracts the first two principal components. First we center the data using either **pandas** or our own code"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"id": "28f97424",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"text/html": [
|
||
"<div>\n",
|
||
"<style scoped>\n",
|
||
" .dataframe tbody tr th:only-of-type {\n",
|
||
" vertical-align: middle;\n",
|
||
" }\n",
|
||
"\n",
|
||
" .dataframe tbody tr th {\n",
|
||
" vertical-align: top;\n",
|
||
" }\n",
|
||
"\n",
|
||
" .dataframe thead th {\n",
|
||
" text-align: right;\n",
|
||
" }\n",
|
||
"</style>\n",
|
||
"<table border=\"1\" class=\"dataframe\">\n",
|
||
" <thead>\n",
|
||
" <tr style=\"text-align: right;\">\n",
|
||
" <th></th>\n",
|
||
" <th>0</th>\n",
|
||
" <th>1</th>\n",
|
||
" <th>2</th>\n",
|
||
" <th>3</th>\n",
|
||
" <th>4</th>\n",
|
||
" </tr>\n",
|
||
" </thead>\n",
|
||
" <tbody>\n",
|
||
" <tr>\n",
|
||
" <th>0</th>\n",
|
||
" <td>-1.574465</td>\n",
|
||
" <td>0.259153</td>\n",
|
||
" <td>1.197370</td>\n",
|
||
" <td>0.147400</td>\n",
|
||
" <td>0.649382</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>1</th>\n",
|
||
" <td>0.689519</td>\n",
|
||
" <td>0.137652</td>\n",
|
||
" <td>-1.025709</td>\n",
|
||
" <td>0.210340</td>\n",
|
||
" <td>-0.076938</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>2</th>\n",
|
||
" <td>-0.282727</td>\n",
|
||
" <td>0.351636</td>\n",
|
||
" <td>-0.539261</td>\n",
|
||
" <td>1.216683</td>\n",
|
||
" <td>0.340782</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>3</th>\n",
|
||
" <td>0.070889</td>\n",
|
||
" <td>-0.614808</td>\n",
|
||
" <td>1.074067</td>\n",
|
||
" <td>-0.038300</td>\n",
|
||
" <td>-1.450257</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>4</th>\n",
|
||
" <td>1.794282</td>\n",
|
||
" <td>1.458078</td>\n",
|
||
" <td>-0.207545</td>\n",
|
||
" <td>-0.442600</td>\n",
|
||
" <td>-0.147420</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>5</th>\n",
|
||
" <td>1.112383</td>\n",
|
||
" <td>0.647473</td>\n",
|
||
" <td>1.405890</td>\n",
|
||
" <td>0.073598</td>\n",
|
||
" <td>-0.276263</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>6</th>\n",
|
||
" <td>0.397700</td>\n",
|
||
" <td>-1.526744</td>\n",
|
||
" <td>-0.712018</td>\n",
|
||
" <td>1.216290</td>\n",
|
||
" <td>0.418506</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>7</th>\n",
|
||
" <td>-0.280647</td>\n",
|
||
" <td>1.106095</td>\n",
|
||
" <td>-1.646283</td>\n",
|
||
" <td>-0.956563</td>\n",
|
||
" <td>-1.564374</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>8</th>\n",
|
||
" <td>-0.369139</td>\n",
|
||
" <td>-0.751699</td>\n",
|
||
" <td>0.051649</td>\n",
|
||
" <td>-0.213103</td>\n",
|
||
" <td>0.967809</td>\n",
|
||
" </tr>\n",
|
||
" <tr>\n",
|
||
" <th>9</th>\n",
|
||
" <td>-1.557795</td>\n",
|
||
" <td>-1.066837</td>\n",
|
||
" <td>0.401842</td>\n",
|
||
" <td>-1.213743</td>\n",
|
||
" <td>1.138775</td>\n",
|
||
" </tr>\n",
|
||
" </tbody>\n",
|
||
"</table>\n",
|
||
"</div>"
|
||
],
|
||
"text/plain": [
|
||
" 0 1 2 3 4\n",
|
||
"0 -1.574465 0.259153 1.197370 0.147400 0.649382\n",
|
||
"1 0.689519 0.137652 -1.025709 0.210340 -0.076938\n",
|
||
"2 -0.282727 0.351636 -0.539261 1.216683 0.340782\n",
|
||
"3 0.070889 -0.614808 1.074067 -0.038300 -1.450257\n",
|
||
"4 1.794282 1.458078 -0.207545 -0.442600 -0.147420\n",
|
||
"5 1.112383 0.647473 1.405890 0.073598 -0.276263\n",
|
||
"6 0.397700 -1.526744 -0.712018 1.216290 0.418506\n",
|
||
"7 -0.280647 1.106095 -1.646283 -0.956563 -1.564374\n",
|
||
"8 -0.369139 -0.751699 0.051649 -0.213103 0.967809\n",
|
||
"9 -1.557795 -1.066837 0.401842 -1.213743 1.138775"
|
||
]
|
||
},
|
||
"metadata": {},
|
||
"output_type": "display_data"
|
||
},
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
" 0 1 2 3 4\n",
|
||
"0 0.0 0.0 0.0 0.0 0.0\n",
|
||
"1 0.0 0.0 0.0 0.0 0.0\n",
|
||
"2 0.0 0.0 0.0 0.0 0.0\n",
|
||
"3 0.0 0.0 0.0 0.0 0.0\n",
|
||
"4 0.0 0.0 0.0 0.0 0.0\n",
|
||
"5 0.0 0.0 0.0 0.0 0.0\n",
|
||
"6 0.0 0.0 0.0 0.0 0.0\n",
|
||
"7 0.0 0.0 0.0 0.0 0.0\n",
|
||
"8 0.0 0.0 0.0 0.0 0.0\n",
|
||
"9 0.0 0.0 0.0 0.0 0.0\n",
|
||
"[[-1.5378811 -0.94639099]\n",
|
||
" [ 0.86145244 0.89288636]\n",
|
||
" [-0.00445655 0.81633628]\n",
|
||
" [ 0.07145103 -1.00433417]\n",
|
||
" [ 2.03707133 -0.48476997]\n",
|
||
" [ 0.72174172 -1.4557763 ]\n",
|
||
" [-0.55854694 1.60673226]\n",
|
||
" [ 1.6999536 0.43766686]\n",
|
||
" [-1.10405456 0.31718909]\n",
|
||
" [-2.18673098 -0.17953942]]\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"from IPython.display import display\n",
|
||
"np.random.seed(100)\n",
|
||
"# setting up a 10 x 5 vanilla matrix \n",
|
||
"rows = 10\n",
|
||
"cols = 5\n",
|
||
"X = np.random.randn(rows,cols)\n",
|
||
"df = pd.DataFrame(X)\n",
|
||
"# Pandas does the centering for us\n",
|
||
"df = df -df.mean()\n",
|
||
"display(df)\n",
|
||
"\n",
|
||
"# we center it ourselves\n",
|
||
"X_centered = X - X.mean(axis=0)\n",
|
||
"# Then check the difference between pandas and our own set up\n",
|
||
"print(X_centered-df)\n",
|
||
"#Now we do an SVD\n",
|
||
"U, s, V = np.linalg.svd(X_centered)\n",
|
||
"c1 = V.T[:, 0]\n",
|
||
"c2 = V.T[:, 1]\n",
|
||
"W2 = V.T[:, :2]\n",
|
||
"X2D = X_centered.dot(W2)\n",
|
||
"print(X2D)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a057f309",
|
||
"metadata": {},
|
||
"source": [
|
||
"PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering\n",
|
||
"the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t\n",
|
||
"forget to center the data first.\n",
|
||
"\n",
|
||
"Once you have identified all the principal components, you can reduce the dimensionality of the dataset\n",
|
||
"down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components.\n",
|
||
"Selecting this hyperplane ensures that the projection will preserve as much variance as possible."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 8,
|
||
"id": "aa6bdcf5",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"W2 = V.T[:, :2]\n",
|
||
"X2D = X_centered.dot(W2)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "9b6e634b",
|
||
"metadata": {},
|
||
"source": [
|
||
"## PCA and scikit-learn\n",
|
||
"\n",
|
||
"Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The\n",
|
||
"following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note\n",
|
||
"that it automatically takes care of centering the data):"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"id": "27016f13",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"[[ 1.5378811 -0.94639099]\n",
|
||
" [-0.86145244 0.89288636]\n",
|
||
" [ 0.00445655 0.81633628]\n",
|
||
" [-0.07145103 -1.00433417]\n",
|
||
" [-2.03707133 -0.48476997]\n",
|
||
" [-0.72174172 -1.4557763 ]\n",
|
||
" [ 0.55854694 1.60673226]\n",
|
||
" [-1.6999536 0.43766686]\n",
|
||
" [ 1.10405456 0.31718909]\n",
|
||
" [ 2.18673098 -0.17953942]]\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"#thereafter we do a PCA with Scikit-learn\n",
|
||
"from sklearn.decomposition import PCA\n",
|
||
"pca = PCA(n_components = 2)\n",
|
||
"X2D = pca.fit_transform(X)\n",
|
||
"print(X2D)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cba40f30",
|
||
"metadata": {},
|
||
"source": [
|
||
"After fitting the PCA transformer to the dataset, you can access the principal components using the\n",
|
||
"components variable (note that it contains the PCs as horizontal vectors, so, for example, the first\n",
|
||
"principal component is equal to"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"id": "b4c61606",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"text/plain": [
|
||
"array([-0.62373464, -0.5303329 , 0.317367 , 0.01873344, 0.47815203])"
|
||
]
|
||
},
|
||
"execution_count": 10,
|
||
"metadata": {},
|
||
"output_type": "execute_result"
|
||
}
|
||
],
|
||
"source": [
|
||
"pca.components_.T[:, 0]"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b5f6a25b",
|
||
"metadata": {},
|
||
"source": [
|
||
"Another very useful piece of information is the explained variance ratio of each principal component,\n",
|
||
"available via the $explained\\_variance\\_ratio$ variable. It indicates the proportion of the dataset’s\n",
|
||
"variance that lies along the axis of each principal component."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0ac21d70",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Back to the Cancer Data\n",
|
||
"We can now repeat the above but applied to real data, in this case our breast cancer data.\n",
|
||
"Here we compute performance scores on the training data using logistic regression."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 11,
|
||
"id": "1fe89d6a",
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"name": "stdout",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"Train set accuracy from Logistic Regression: 0.95\n",
|
||
"Train set accuracy scaled data: 0.99\n",
|
||
"Train set accuracy scaled and PCA data: 0.96\n"
|
||
]
|
||
},
|
||
{
|
||
"name": "stderr",
|
||
"output_type": "stream",
|
||
"text": [
|
||
"/Users/mhjensen/Software/anaconda3/lib/python3.8/site-packages/sklearn/linear_model/_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):\n",
|
||
"STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n",
|
||
"\n",
|
||
"Increase the number of iterations (max_iter) or scale the data as shown in:\n",
|
||
" https://scikit-learn.org/stable/modules/preprocessing.html\n",
|
||
"Please also refer to the documentation for alternative solver options:\n",
|
||
" https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n",
|
||
" n_iter_i = _check_optimize_result(\n"
|
||
]
|
||
}
|
||
],
|
||
"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",
|
||
"\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
|
||
"\n",
|
||
"logreg = LogisticRegression()\n",
|
||
"logreg.fit(X_train, y_train)\n",
|
||
"print(\"Train set accuracy from Logistic Regression: {:.2f}\".format(logreg.score(X_train,y_train)))\n",
|
||
"# We scale the data\n",
|
||
"from sklearn.preprocessing import StandardScaler\n",
|
||
"scaler = StandardScaler()\n",
|
||
"scaler.fit(X_train)\n",
|
||
"X_train_scaled = scaler.transform(X_train)\n",
|
||
"X_test_scaled = scaler.transform(X_test)\n",
|
||
"# Then perform again a log reg fit\n",
|
||
"logreg.fit(X_train_scaled, y_train)\n",
|
||
"print(\"Train set accuracy scaled data: {:.2f}\".format(logreg.score(X_train_scaled,y_train)))\n",
|
||
"#thereafter we do a PCA with Scikit-learn\n",
|
||
"from sklearn.decomposition import PCA\n",
|
||
"pca = PCA(n_components = 2)\n",
|
||
"X2D_train = pca.fit_transform(X_train_scaled)\n",
|
||
"# and finally compute the log reg fit and the score on the training data\t\n",
|
||
"logreg.fit(X2D_train,y_train)\n",
|
||
"print(\"Train set accuracy scaled and PCA data: {:.2f}\".format(logreg.score(X2D_train,y_train)))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "284835e6",
|
||
"metadata": {},
|
||
"source": [
|
||
"We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. \n",
|
||
"\n",
|
||
"Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to\n",
|
||
"choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).\n",
|
||
"Unless, of course, you are reducing dimensionality for data visualization — in that case you will\n",
|
||
"generally want to reduce the dimensionality down to 2 or 3.\n",
|
||
"The following code computes PCA without reducing dimensionality, then computes the minimum number\n",
|
||
"of dimensions required to preserve 95% of the training set’s variance:"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 12,
|
||
"id": "16dff606",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"pca = PCA()\n",
|
||
"pca.fit(X)\n",
|
||
"cumsum = np.cumsum(pca.explained_variance_ratio_)\n",
|
||
"d = np.argmax(cumsum >= 0.95) + 1"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3ca0f846",
|
||
"metadata": {},
|
||
"source": [
|
||
"You could then set $n\\_components=d$ and run PCA again. However, there is a much better option: instead\n",
|
||
"of specifying the number of principal components you want to preserve, you can set $n\\_components$ to be\n",
|
||
"a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 13,
|
||
"id": "b7dba51f",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"pca = PCA(n_components=0.95)\n",
|
||
"X_reduced = pca.fit_transform(X)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b0c6dd70",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Incremental PCA\n",
|
||
"\n",
|
||
"One problem with the preceding implementation of PCA is that it requires the whole training set to fit in\n",
|
||
"memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have\n",
|
||
"been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch\n",
|
||
"at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new\n",
|
||
"instances arrive)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "43bbd33f",
|
||
"metadata": {},
|
||
"source": [
|
||
"### Randomized PCA\n",
|
||
"\n",
|
||
"Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic\n",
|
||
"algorithm that quickly finds an approximation of the first d principal components. Its computational\n",
|
||
"complexity is $O(m \\times d^2)+O(d^3)$, instead of $O(m \\times n^2) + O(n^3)$, so it is dramatically faster than the\n",
|
||
"previous algorithms when $d$ is much smaller than $n$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "73ac8d86",
|
||
"metadata": {},
|
||
"source": [
|
||
"### Kernel PCA\n",
|
||
"\n",
|
||
"The kernel trick is a mathematical technique that implicitly maps instances into a\n",
|
||
"very high-dimensional space (called the feature space), enabling nonlinear classification and regression\n",
|
||
"with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature\n",
|
||
"space corresponds to a complex nonlinear decision boundary in the original space.\n",
|
||
"It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear\n",
|
||
"projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at\n",
|
||
"preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a\n",
|
||
"twisted manifold.\n",
|
||
"For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 14,
|
||
"id": "5c4a0d77",
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.decomposition import KernelPCA\n",
|
||
"rbf_pca = KernelPCA(n_components = 2, kernel=\"rbf\", gamma=0.04)\n",
|
||
"X_reduced = rbf_pca.fit_transform(X)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "56afa4e0",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Other techniques\n",
|
||
"\n",
|
||
"There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.\n",
|
||
"\n",
|
||
"Here are some of the most popular:\n",
|
||
"* **Multidimensional Scaling (MDS)** reduces dimensionality while trying to preserve the distances between the instances.\n",
|
||
"\n",
|
||
"* **Isomap** creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.\n",
|
||
"\n",
|
||
"* **t-Distributed Stochastic Neighbor Embedding** (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).\n",
|
||
"\n",
|
||
"* Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures."
|
||
]
|
||
}
|
||
],
|
||
"metadata": {
|
||
"kernelspec": {
|
||
"display_name": "Python 3",
|
||
"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.8.8"
|
||
}
|
||
},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 5
|
||
}
|