diff --git a/doc/pub/week43/html/week43-bs.html b/doc/pub/week43/html/week43-bs.html index 63d18e71e..20e7af09c 100644 --- a/doc/pub/week43/html/week43-bs.html +++ b/doc/pub/week43/html/week43-bs.html @@ -1,31 +1,28 @@ - + - Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis - + - - - @@ -134,7 +159,7 @@ end of tocinfo --> - - -
-

 

 

 

- - - - -
-

Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis

+
+

Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis

+
-

-

Morten Hjorth-Jensen [1, 2]
- -

- -

[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+[1] Department of Physics, University of Oslo +
+
+[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +

-

-

Oct 29, 2021

+
+

Nov 2, 2021

+

-

- - -

Read »

- +
-

- -

+ +









+

An extrapolation example

-

An extrapolation example

- -

-The following code provides an example of how recurrent neural +

The following code provides an example of how recurrent neural networks can be used to extrapolate to unknown values of physics data sets. Specifically, the data sets used in this program come from a quantum mechanical many-body calculation of energies as functions of the number of particles. +

-

-

# For matrices and calculations
+
+
+
+
+
+
# For matrices and calculations
 import numpy as np
 # For machine learning (backend for keras)
 import tensorflow as tf
@@ -430,14 +453,26 @@ X_tot = np.arange(2, 0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
 	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
 	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Formatting the Data

-

Formatting the Data

- -

-The way the recurrent neural networks are trained in this program +

The way the recurrent neural networks are trained in this program differs from how machine learning algorithms are usually trained. Typically a machine learning algorithm is trained by learning the relationship between the x data and the y data. In this program, the @@ -447,9 +482,9 @@ typically used time series forcasting, but it can also be used in any extrapolation (time series forecasting is just a specific type of extrapolation along the time axis). This method of data formatting does not use the x data and assumes that the y data are evenly spaced. +

-

-For a standard machine learning algorithm, the training data has the +

For a standard machine learning algorithm, the training data has the form of (x,y) so the machine learning algorithm learns to assiciate a y value with a given x value. This is useful when the test data has x values within the same range as the training data. However, for this @@ -463,8 +498,8 @@ data. As long as the pattern of y data outside of the training region stays relatively stable compared to what was inside the training region, this method of training can produce accurate extrapolations to y values far removed from the training data set. +

-

@@ -472,10 +507,14 @@ y values far removed from the training data set. -

-

# FORMAT_DATA
+
+
+
+
+
+
# FORMAT_DATA
 def format_data(data, length_of_sequence = 2):  
     """
         Inputs:
@@ -547,16 +586,33 @@ y values far removed from the training data set.
     # function and an Adams optimizer.
     model.compile(loss="mean_squared_error", optimizer="adam")  
     return model
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Predicting New Points With A Trained Recurrent Neural Network

-

Predicting New Points With A Trained Recurrent Neural Network

- -

-

def test_rnn (x1, y_test, plot_min, plot_max):
+
+
+
+
+
+
def test_rnn (x1, y_test, plot_min, plot_max):
     """
         Inputs:
             x1 (a list or numpy array): The complete x component of the data set
@@ -647,14 +703,26 @@ test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-<
 # Stop the timer and calculate the total time needed.
 end = timer()
 print('Time: ', end-start)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Other Things to Try

-

Other Things to Try

- -

-Changing the size of the recurrent neural network and its parameters +

Changing the size of the recurrent neural network and its parameters can drastically change the results you get from the model. The below code takes the simple recurrent neural network from above and adds a second hidden layer, changes the number of neurons in the hidden @@ -664,11 +732,16 @@ also be changed but are kept the same as the above network. These parameters can be tuned to provide the optimal result from the network. For some ideas on how to improve the performance of a recurrent neural network. +

-

-

def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
+
+
+
+
+
+
def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
     """
         Inputs:
             length_of_sequences (an int): the number of y values in "x data".  This is determined
@@ -754,21 +827,33 @@ test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-<
 # Stop the timer and calculate the total time needed.
 end = timer()
 print('Time: ', end-start)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Other Types of Recurrent Neural Networks

-

Other Types of Recurrent Neural Networks

- -

-Besides a simple recurrent neural network layer, there are two other +

Besides a simple recurrent neural network layer, there are two other commonly used types of recurrent neural network layers: Long Short Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b. +

-

-The first network created below is similar to the previous network, +

The first network created below is similar to the previous network, but it replaces the SimpleRNN layers with LSTM layers. The second network below has two hidden layers made up of GRUs, which are preceeded by two dense (feeddorward) neural network layers. These @@ -776,11 +861,16 @@ dense layers "preprocess" the data before it reaches the recurrent layers. This architecture has been shown to improve the performance of recurrent neural networks (see the link above and also https://arxiv.org/pdf/1807.02857.pdf. +

-

-

def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
+
+
+
+
+
+
def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
     """
         Inputs:
             length_of_sequences (an int): the number of y values in "x data".  This is determined
@@ -970,14 +1060,26 @@ plt.show()
 # Stop the timer and calculate the total time needed.
 end = timer()
 print('Time: ', end-start)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Generative Models

-

Generative Models

- -

-Generative models describe a class of statistical models that are a contrast +

Generative models describe a class of statistical models that are a contrast to discriminative models. Informally we say that generative models can generate new data instances while discriminative models discriminate between different kinds of data instances. A generative model could generate new photos @@ -988,26 +1090,24 @@ just \( p(x) \) if there are no labels, while discriminative models capture the conditional probability \( p(y | x) \). Discriminative models generally try to draw boundaries in the data space (often high dimensional), while generative models try to model how data is placed throughout the space. +

-

-Note: this material is thanks to Linus Ekstrøm. +

Note: this material is thanks to Linus Ekstrøm.

-











+

Generative Adversarial Networks

-

Generative Adversarial Networks

- -

-Generative Adversarial Networks are a type of unsupervised machine learning +

Generative Adversarial Networks are a type of unsupervised machine learning algorithm proposed by Goodfellow et. al in 2014 (short and good article). +

-

-The simplest formulation of +

The simplest formulation of the model is based on a game theoretic approach, zero sum game, where we pit two neural networks against one another. We define two rival networks, one generator \( g \), and one discriminator \( d \). The generator directly produces samples +

$$ \begin{equation} x = g(z; \theta^{(g)}) @@ -1015,15 +1115,15 @@ $$ \end{equation} $$ -

-









-

Discriminator

-The discriminator attempts to distinguish between samples drawn from the +









+

Discriminator

+

The discriminator attempts to distinguish between samples drawn from the training data and samples drawn from the generator. In other words, it tries to tell the difference between the fake data produced by \( g \) and the actual data samples we want to do prediction on. The discriminator outputs a probability value given by +

$$ \begin{equation} @@ -1032,11 +1132,11 @@ $$ \end{equation} $$ -

-indicating the probability that \( x \) is a real training example rather than a +

indicating the probability that \( x \) is a real training example rather than a fake sample the generator has generated. The simplest way to formulate the learning process in a generative adversarial network is a zero-sum game, in which a function +

$$ \begin{equation} @@ -1045,9 +1145,9 @@ $$ \end{equation} $$ -

-determines the reward for the discriminator, while the generator gets the +

determines the reward for the discriminator, while the generator gets the conjugate reward +

$$ \begin{equation} @@ -1056,13 +1156,11 @@ $$ \end{equation} $$ -

+









+

Learning Process

-

Learning Process

- -

-During learning both of the networks maximize their own reward function, so that +

During learning both of the networks maximize their own reward function, so that the generator gets better and better at tricking the discriminator, while the discriminator gets better and better at telling the difference between the fake and real data. The generator and discriminator alternate on which one trains at @@ -1078,14 +1176,12 @@ tackle otherwise intractable generative problems. As the generator improves with if we continue training after this point then the generator is effectively training on junk data which can undo the learning up to that point. Therefore, we stop training when the discriminator starts outputting \( 1/2 \) everywhere. +

-











+

More about the Learning Process

-

More about the Learning Process

- -

-At convergence we have +

At convergence we have

$$ \begin{equation} @@ -1095,7 +1191,7 @@ $$ \end{equation} $$ -The default choice for \( v \) is +

The default choice for \( v \) is

$$ \begin{equation} v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x) @@ -1105,9 +1201,10 @@ $$ \end{equation} $$ -The main motivation for the design of GANs is that the learning process requires +

The main motivation for the design of GANs is that the learning process requires neither approximate inference (variational autoencoders for example) nor approximation of a partition function. In the case where +

$$ \begin{equation} \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) @@ -1115,15 +1212,14 @@ $$ \end{equation} $$ -is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is +

is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is asymptotically consistent ( Seth Lloyd on QuGANs ). +

-











- -

Additional References

-This is in +

Additional References

+

This is in general not the case and it is possible to get situations where the training process never converges because the generator and discriminator chase one another around in the parameter space indefinitely. A much deeper discussion on @@ -1134,37 +1230,57 @@ Direct quote: "In this best-performing formulation, the generator aims to increase the log probability that the discriminator makes a mistake, rather than aiming to decrease the log probability that the discriminator makes the correct prediction." Another interesting read +

-











- -

Writing Our First Generative Adversarial Network

-Let us now move on to actually implementing a GAN in tensorflow. We will study +

Writing Our First Generative Adversarial Network

+

Let us now move on to actually implementing a GAN in tensorflow. We will study the performance of our GAN on the MNIST dataset. This code is based on and adapted from the google tutorial +

-

-First we import our libraries +

First we import our libraries

-

-

import os
+
+
+
+
+
+
import os
 import time
 import numpy as np
 import tensorflow as tf
 import matplotlib.pyplot as plt
 from tensorflow.keras import layers
 from tensorflow.keras.utils import plot_model
-
-

-Next we define our hyperparameters and import our data the usual way +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Next we define our hyperparameters and import our data the usual way

-

-

BUFFER_SIZE = 60000
+
+
+
+
+
+
BUFFER_SIZE = 60000
 BATCH_SIZE = 256
 EPOCHS = 30
 
@@ -1179,37 +1295,71 @@ train_images = np.reshape(train_images, (train_images.shape[127.5) / 127.5
 training_dataset = tf.data.Dataset.from_tensor_slices(
                       train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

MNIST and GANs

-

MNIST and GANs

+

Let's have a quick look

-

-Let's have a quick look - -

-

plt.imshow(train_images[0], cmap='Greys')
+
+
+
+
+
+
plt.imshow(train_images[0], cmap='Greys')
 plt.show()
-
-

-Now we define our two models. This is where the 'magic' happens. There are a +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Now we define our two models. This is where the 'magic' happens. There are a huge amount of possible formulations for both models. A lot of engineering and trial and error can be done here to try to produce better performing models. For more advanced GANs this is by far the step where you can 'make or break' a model. +

-

-We start with the generator. As stated in the introductory text the generator +

We start with the generator. As stated in the introductory text the generator \( g \) upsamples from a random sample to the shape of what we want to predict. In our case we are trying to predict MNIST images (\( 28\times 28 \) pixels). +

-

-

def generator_model():
+
+
+
+
+
+
def generator_model():
     """
     The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to
     produce an image from a random seed. We start with a Dense layer taking this
@@ -1266,16 +1416,34 @@ our case we are trying to predict MNIST images (\( 28\times 28 \) pixels).
     assert model.output_shape == (None, 28, 28, 1)
 
     return model
-
-

-And there we have our 'simple' generator model. Now we move on to defining our +

+
+ + + +
+
+
+
+
+
+
+
+ + +

And there we have our 'simple' generator model. Now we move on to defining our discriminator model \( d \), which is a convolutional neural network based image classifier. +

-

-

def discriminator_model():
+
+
+
+
+
+
def discriminator_model():
     """
     The discriminator is a convolutional neural network based image classifier
     """
@@ -1304,86 +1472,203 @@ classifier.
     model.add(layers.Dense(1))
 
     return model
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Other Models

+

Let us take a look at our models. Note: double click images for bigger view.

-

Other Models

-Let us take a look at our models. Note: double click images for bigger view. - -

-

generator = generator_model()
+
+
+
+
+
+
generator = generator_model()
 plot_model(generator, show_shapes=True, rankdir='LR')
-
-

- +

+
+ + + +
+
+
+
+
+
+
+
-
discriminator = discriminator_model()
+
+
+
+
+
+
discriminator = discriminator_model()
 plot_model(discriminator, show_shapes=True, rankdir='LR')
-
-

-Next we need a few helper objects we will use in training +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Next we need a few helper objects we will use in training

-

-

cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
+
+
+
+
+
+
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
 generator_optimizer = tf.keras.optimizers.Adam(1e-4)
 discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
-
-

-The first object, cross_entropy is our loss function and the two others are +

+
+ + + +
+
+
+
+
+
+
+
+ + +

The first object, cross_entropy is our loss function and the two others are our optimizers. Notice we use the same learning rate for both \( g \) and \( d \). This is because they need to improve their accuracy at approximately equal speeds to get convergence (not necessarily exactly equal). Now we define our loss functions +

-

-

def generator_loss(fake_output):
+
+
+
+
+
+
def generator_loss(fake_output):
     loss = cross_entropy(tf.ones_like(fake_output), fake_output)
 
     return loss
-
-

- +

+
+ + + +
+
+
+
+
+
+
+
-
def discriminator_loss(real_output, fake_output):
+
+
+
+
+
+
def discriminator_loss(real_output, fake_output):
     real_loss = cross_entropy(tf.ones_like(real_output), real_output)
     fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)
     total_loss = real_loss + fake_loss
 
     return total_loss
-
-

-Next we define a kind of seed to help us compare the learning process over -multiple training epochs. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Next we define a kind of seed to help us compare the learning process over +multiple training epochs. +

-

-

noise_dimension = 100
+
+
+
+
+
+
noise_dimension = 100
 n_examples_to_generate = 16
 seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Training Step

-

Training Step

- -

-Now we have everything we need to define our training step, which we will apply +

Now we have everything we need to define our training step, which we will apply for every step in our training loop. Notice the @tf.function flag signifying that the function is tensorflow 'compiled'. Removing this flag doubles the computation time. +

-

-

@tf.function
+
+
+
+
+
+
@tf.function
 def train_step(images):
     noise = tf.random.normal([BATCH_SIZE, noise_dimension])
 
@@ -1406,15 +1691,33 @@ computation time.
                                             discriminator.trainable_variables))
 
     return gen_loss, disc_loss
-
-

-Next we define a helper function to produce an output over our training epochs +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Next we define a helper function to produce an output over our training epochs to see the predictive progression of our generator model. Note: I am including this code here, but comment it out in the training loop. -

+

-
def generate_and_save_images(model, epoch, test_input):
+
+
+
+
+
+
def generate_and_save_images(model, epoch, test_input):
     # we're making inferences here
     predictions = model(test_input, training=False)
 
@@ -1428,33 +1731,68 @@ this code here, but comment it out in the training loop.
     plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')
     plt.close()
     #plt.show()
-
-

-









+

+
+ + + +
+
+
+
+
+
+
+
+ -

Checkpoints

-Setting up checkpoints to periodically save our model during training so that + +









+

Checkpoints

+

Setting up checkpoints to periodically save our model during training so that everything is not lost even if the program were to somehow terminate while training. +

-

-

# Setting up checkpoints to save model during training
+
+
+
+
+
+
# Setting up checkpoints to save model during training
 checkpoint_dir = './training_checkpoints'
 checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')
 checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
                             discriminator_optimizer=discriminator_optimizer,
                             generator=generator,
                             discriminator=discriminator)
-
-

-Now we define our training loop +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Now we define our training loop

-

-

def train(dataset, epochs):
+
+
+
+
+
+
def train(dataset, epochs):
     generator_loss_list = []
     discriminator_loss_list = []
 
@@ -1483,53 +1821,103 @@ Now we define our training loop
         outfile.write(str(discriminator_loss_list))
         outfile.write('\n')
         outfile.write('\n')
-
-

-To train simply call this function. Warning: this might take a long time so -there is a folder of a pretrained network already included in the repository. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

To train simply call this function. Warning: this might take a long time so +there is a folder of a pretrained network already included in the repository. +

-

-

train(train_dataset, EPOCHS)
-
-

-And here is the result of training our model for 100 epochs +

+
+
+
+
+
train(train_dataset, EPOCHS)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-

+

And here is the result of training our model for 100 epochs

-

-Now to avoid having to train and everything, which will take a while depending +

Now to avoid having to train and everything, which will take a while depending on your computer setup we now load in the model which produced the above gif. +

-

-

checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
+
+
+
+
+
+
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
 restored_generator = checkpoint.generator
 restored_discriminator = checkpoint.discriminator
 
 print(restored_generator)
 print(restored_discriminator)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Exploring the Latent Space

-

Exploring the Latent Space

- -

-We have successfully loaded in our latest model. Let us now play around a bit +

We have successfully loaded in our latest model. Let us now play around a bit and see what kind of things we can learn about this model. Our generator takes an array of 100 numbers. One idea can be to try to systematically change our input. Let us try and see what we get +

-

-

def generate_latent_points(number=100, scale_means=1, scale_stds=1):
+
+
+
+
+
+
def generate_latent_points(number=100, scale_means=1, scale_stds=1):
     latent_dim = 100
     means = scale_means * tf.linspace(-1, 1, num=latent_dim)
     stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)
@@ -1545,11 +1933,26 @@ input. Let us try and see what we get
     generated_images = restored_generator.predict(latent_points)
 
     return generated_images
-
-

- +

+
+ + + +
+
+
+
+
+
+
+
-
def plot_result(generated_images, number=100):
+
+
+
+
+
+
def plot_result(generated_images, number=100):
     # obviously this assumes sqrt number is an int
     fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),
                             figsize=(10, 10))
@@ -1560,27 +1963,60 @@ input. Let us try and see what we get
             axs[i, j].axis('off')
 
     plt.show()
-
-

- +

+
+ + + +
+
+
+
+
+
+
+
-
generated_images = generate_images(generate_latent_points())
+
+
+
+
+
+
generated_images = generate_images(generate_latent_points())
 plot_result(generated_images)
-
-

-









+

+
+ + + +
+
+
+
+
+
+
+
+ -

Getting Results

-We see that the generator generates images that look like MNIST + +









+

Getting Results

+

We see that the generator generates images that look like MNIST numbers: \( 1, 4, 7, 9 \). Let's try to tweak it a bit more to see if we are able to generate a similar plot where we generate every MNIST number. Let us now try to 'move' a bit around in the latent space. Note: decrease the plot number if these following cells take too long to run on your computer. +

-

-

plot_number = 225
+
+
+
+
+
+
plot_number = 225
 
 generated_images = generate_images(generate_latent_points(number=plot_number,
                                                           scale_means=5,
@@ -1596,58 +2032,110 @@ generated_images = generate_images(generate_latent_points(number=plot_number,
                                                           scale_means=1,
                                                           scale_stds=5))
 plot_result(generated_images, number=plot_number)
-
-

-Again, we have found something interesting. Moving around using our means +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Again, we have found something interesting. Moving around using our means takes us from digit to digit, while moving around using our standard deviations seem to increase the number of different digits! In the last image above, we can barely make out every MNIST digit. Let us make on last plot using this information by upping the standard deviation of our Gaussian noises. +

-

-

plot_number = 400
+
+
+
+
+
+
plot_number = 400
 generated_images = generate_images(generate_latent_points(number=plot_number,
                                                           scale_means=1,
                                                           scale_stds=10))
 plot_result(generated_images, number=plot_number)
-
-

-A pretty cool result! We see that our generator indeed has learned a +

+
+ + + +
+
+
+
+
+
+
+
+ + +

A pretty cool result! We see that our generator indeed has learned a distribution which qualitatively looks a whole lot like the MNIST dataset. +

-











- -

Interpolating Between MNIST Digits

-Another interesting way to explore the latent space of our generator model is by +

Interpolating Between MNIST Digits

+

Another interesting way to explore the latent space of our generator model is by interpolating between the MNIST digits. This section is largely based on this excellent blogpost by Jason Brownlee. +

-

-So let us start by defining a function to interpolate between two points in the +

So let us start by defining a function to interpolate between two points in the latent space. +

-

-

def interpolation(point_1, point_2, n_steps=10):
+
+
+
+
+
+
def interpolation(point_1, point_2, n_steps=10):
     ratios = np.linspace(0, 1, num=n_steps)
     vectors = []
     for i, ratio in enumerate(ratios):
         vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))
 
     return tf.stack(vectors)
-
-

-Now we have all we need to do our interpolation analysis. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Now we have all we need to do our interpolation analysis.

-

-

plot_number = 100
+
+
+
+
+
+
plot_number = 100
 latent_points = generate_latent_points(number=plot_number)
 results = None
 for i in range(0, 2*np.sqrt(plot_number), 2):
@@ -1660,86 +2148,94 @@ results = None
         results = tf.stack((results, generated_images))
 
 plot_results(results, plot_number)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Basic ideas of the Principal Component Analysis (PCA)

-

Basic ideas of the Principal Component Analysis (PCA)

- -

-The principal component analysis deals with the problem of fitting a +

The principal component analysis deals with the problem of fitting a low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than the total dimension \( D \) of the problem at hand (our data set). Mathematically it can be formulated as a statistical problem or a geometric problem. In our discussion of the theorem for the classical PCA, we will stay with a statistical approach. Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable. +

-

-We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) - +

We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition)

+

A good read is for example Vidal, Ma and Sastry.

-A good read is for example Vidal, Ma and Sastry. - -











+

Introducing the Covariance and Correlation functions

-

Introducing the Covariance and Correlation functions

+

Before we discuss the PCA theorem, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities +

-

-Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities - -

-Suppose we have defined two vectors +

Suppose we have defined two vectors \( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +

$$ \boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ \end{bmatrix}, $$ -where for example +

where for example

$$ \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). $$ -With this definition and recalling that the variance is defined as +

With this definition and recalling that the variance is defined as

$$ \mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, $$ -we can rewrite the covariance matrix as +

we can rewrite the covariance matrix as

$$ \boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ \end{bmatrix}. $$ -

-









-

More on the covariance

-The covariance takes values between zero and infinity and may thus +









+

More on the covariance

+

The covariance takes values between zero and infinity and may thus lead to problems with loss of numerical precision for particularly large values. It is common to scale the covariance matrix by introducing instead the correlation matrix defined via the so-called correlation function +

$$ \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. $$ -

-The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] +

The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \in [-1,1] \). This avoids eventual problems with too large values. We can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) and \( \boldsymbol{y} \) as +

$$ \boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ @@ -1747,15 +2243,13 @@ $$ \end{bmatrix}, $$ -

-In the above example this is the function we constructed using pandas. +

In the above example this is the function we constructed using pandas.

-











- -

Reminding ourselves about Linear Regression

-In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression +

Reminding ourselves about Linear Regression

+

In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix \( \boldsymbol{X} \) as +

$$ \boldsymbol{X}=\begin{bmatrix} @@ -1768,26 +2262,27 @@ x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ \end{bmatrix}, $$ -with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the +

with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the entries \( n \) being the row elements. We can rewrite the design/feature matrix in terms of its column vectors as +

$$ \boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, $$ -with a given vector +

with a given vector

$$ \boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. $$ -

-









-

Simple Example

-With these definitions, we can now rewrite our \( 2\times 2 \) +









+

Simple Example

+

With these definitions, we can now rewrite our \( 2\times 2 \) correlation/covariance matrix in terms of a moe general design/feature matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) +

$$ \boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} @@ -1800,13 +2295,11 @@ $$ \end{bmatrix}, $$ -

+









+

The Correlation Matrix

-

The Correlation Matrix

- -

-and the correlation matrix +

and the correlation matrix

$$ \boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} 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}]\\ @@ -1818,17 +2311,16 @@ $$ \end{bmatrix}, $$ -

+









+

Numpy Functionality

-

Numpy Functionality

- -

-The Numpy function np.cov calculates the covariance elements using +

The Numpy function np.cov calculates the covariance elements using the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have the exact mean values. The following simple function uses the np.vstack function which takes each vector of dimension \( 1\times n \) and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) +

$$ \boldsymbol{W}^T = \begin{bmatrix} x_0 & y_0 \\ @@ -1840,17 +2332,21 @@ $$ \end{bmatrix}, $$ -

-which in turn is converted into into the \( 2\times 2 \) covariance matrix +

which in turn is converted into into the \( 2\times 2 \) covariance matrix \( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy function np.mean(x). We can also extract the eigenvalues of the covariance matrix through the np.linalg.eig() function. +

-

-

# Importing various packages
+
+
+
+
+
+
# Importing various packages
 import numpy as np
 n = 100
 x = np.random.normal(size=n)
@@ -1860,23 +2356,40 @@ y = 4+3*
 W = np.vstack((x, y))
 C = np.cov(W)
 print(C)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Correlation Matrix again

-

Correlation Matrix again

- -

-The previous example can be converted into the correlation matrix by +

The previous example can be converted into the correlation matrix by simply scaling the matrix elements with the variances. We should also subtract the mean values for each column. This leads to the following code which sets up the correlations matrix for the previous example in -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). +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). +

-

-

import numpy as np
+
+
+
+
+
+
import numpy as np
 n = 100
 # define two vectors                                                                                           
 x = np.random.random(size=n)
@@ -1897,26 +2410,40 @@ C[1,1]=
 C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
 C[1,0]= C[0,1]
 print(C)
-
-

-We see that the matrix elements along the diagonal are one as they +

+
+ + + +
+
+
+
+
+
+
+
+ + +

We see that the matrix elements along the diagonal are one as they should be and that the matrix is symmetric. Furthermore, diagonalizing this matrix we easily see that it is a positive definite matrix. +

-

-The above procedure with numpy can be made more compact if we use pandas. +

The above procedure with numpy can be made more compact if we use pandas.

-











+

Using Pandas

-

Using Pandas

- -

-We whow here how we can set up the correlation matrix using pandas, as done in this simple code -

+

We whow here how we can set up the correlation matrix using pandas, as done in this simple code

-
import numpy as np
+
+
+
+
+
+
import numpy as np
 import pandas as pd
 n = 10
 x = np.random.normal(size=n)
@@ -1929,19 +2456,35 @@ Xpd = pd.DataFrame(X)
 print(Xpd)
 correlation_matrix = Xpd.corr()
 print(correlation_matrix)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

And then the Franke Function

-

And then the Franke Function

+

We expand this model to the Franke function discussed above.

-

-We expand this model to the Franke function discussed above. - -

-

# Common imports
+
+
+
+
+
+
# Common imports
 import numpy as np
 import pandas as pd
 
@@ -1984,28 +2527,38 @@ Xpd = pd.DataFrame(X)
 Xpd = Xpd - Xpd.mean()
 covariance_matrix = Xpd.cov()
 print(covariance_matrix)
-
-

-We note here that the covariance is zero for the first rows and +

+
+ + + +
+
+
+
+
+
+
+
+ + +

We note here that the covariance is zero for the first rows and columns since all matrix elements in the design matrix were set to one (we are fitting the function in terms of a polynomial of degree \( n \)). We would however not include the intercept and wee can simply drop these elements and construct a correlation -matrix without them by centering our matrix elements by subtracting the mean of each column. +matrix without them by centering our matrix elements by subtracting the mean of each column. +

-











+

Lnks with the Design Matrix

-

Lnks with the Design Matrix

- -

-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as +

We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as

$$ \boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. $$ -

-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) +

To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)

$$ \boldsymbol{X}=\begin{bmatrix} x_{00} & x_{01}\\ @@ -2015,13 +2568,11 @@ x_{10} & x_{11}\\ \end{bmatrix}. $$ -

+









+

Computing the Expectation Values

-

Computing the Expectation Values

- -

-If we then compute the expectation value +

If we then compute the expectation value

$$ \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix} x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ @@ -2029,63 +2580,56 @@ x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ \end{bmatrix}, $$ -which is just +

which is just

$$ \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] \\ \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ \end{bmatrix}, $$ -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} \). +

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} \).

-

-It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). +

It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).

-











+

Towards the PCA theorem

-

Towards the PCA theorem

- -

-We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as +

We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as

$$ \boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. $$ -Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). +

Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). 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} \). +

-

-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}] \). +

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}] \).

-

-That is we have +

That is we have

$$ \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}, $$ -since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have +

since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have

$$ \boldsymbol{S}\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}, $$ -and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that +

and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that

$$ \boldsymbol{S}_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}_i. $$ -

+









+

More on the PCA Theorem

-

More on the PCA Theorem

+

In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is +\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). +

-

-In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). - -

-The eigenvalues tell us then how much we need to stretch the +

The eigenvalues tell us then how much we need to stretch the corresponding eigenvectors. Dimensions with large eigenvalues have thus large variations (large variance) and define therefore useful dimensions. The data points are more spread out in the direction of @@ -2096,19 +2640,15 @@ these specific directions. Hopefully then we could leave it out dimensions where the eigenvalues are very small. If \( p \) is very large, we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) features/predictors. +

-











+

The Algorithm before theorem

-

The Algorithm before theorem

- -

-Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. - +

Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here.

- $$ \boldsymbol{X}=\begin{bmatrix} x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ @@ -2120,7 +2660,6 @@ x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ \end{bmatrix}, $$ - -









+

Writing our own PCA code

-

Writing our own PCA code

- -

-We will use a simple example first with two-dimensional data +

We will use a simple example first with two-dimensional data 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): +

$$ \mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ 2 & 2 \end{bmatrix} $$ -Note that the mean refers to each column of data. +

Note that the mean refers to each column of data. We will generate \( n = 10000 \) points \( X = \{ x_1, \ldots, x_N \} \) from 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. +

-











- -

Implementing it

-The following Python code aids in setting up the data and writing out the design matrix. +

Implementing it

+

The following Python code aids in setting up the data and writing out the design matrix. Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). -

+

-
import numpy as np
+
+
+
+
+
+
import numpy as np
 import pandas as pd
 import matplotlib.pyplot as plt
 from IPython.display import display
@@ -2163,44 +2704,72 @@ n = 10000
 mean = (-1, 2)
 cov = [[4, 2], [2, 2]]
 X = np.random.multivariate_normal(mean, cov, n)
-
-

-Now we are going to implement the PCA algorithm. We will break it down into various substeps. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Now we are going to implement the PCA algorithm. We will break it down into various substeps.

-











+

First Step

-

First Step

- -

-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 +

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

$$ \mu_n = \frac{1}{n} \sum_{i=1}^n x_i $$ -and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form +

and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form

$$ \bar{x}_i = x_i - \mu_n. $$ -When you are done with these steps, print out \( \mu_n \) to verify it is +

When you are done with these steps, print out \( \mu_n \) to verify it is close to \( \mu \) and plot your mean centered data to verify it is centered at the origin! 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. -

+

-
df = pd.DataFrame(X)
+
+
+
+
+
+
df = pd.DataFrame(X)
 # Pandas does the centering for us
 df = df -df.mean()
 # we center it ourselves
 X_centered = X - X.mean(axis=0)
-
-

-









+

+
+ + + +
+
+
+
+
+
+
+
+ -

Scaling

-Alternatively, we could use the functions we discussed + +









+

Scaling

+

Alternatively, we could use the functions we discussed earlier for scaling the data set. That is, we could have used the StandardScaler function in Scikit-Learn, a function which ensures that for each feature/predictor we study the mean value is zero and @@ -2209,35 +2778,56 @@ would then not get the same results, since we divide by the variance. The diagonal covariance matrix elements will then be one, while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our specific case. +

-











+

Centered Data

-

Centered Data

- -

-Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation +

Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation

$$ \begin{equation*} \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) \end{equation*} $$ -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 \). +

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 \). We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows -

+

-
print(df.cov())
+
+
+
+
+
+
print(df.cov())
 print(np.cov(X_centered.T))
-
-

-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. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

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. Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. -

+

-
# extract the relevant columns from the centered design matrix of dim n x 2
+
+
+
+
+
+
# extract the relevant columns from the centered design matrix of dim n x 2
 x = X_centered[:,0]
 y = X_centered[:,1]
 Cov = np.zeros((2,2))
@@ -2250,27 +2840,38 @@ Cov[1,0]
 plt.plot(x, y, 'x')
 plt.axis('equal')
 plt.show()
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Exploring

-

Exploring

+

Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. +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. +

-

-Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. -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. - -











+

Diagonalize the sample covariance matrix to obtain the principal components

-

Diagonalize the sample covariance matrix to obtain the principal components

- -

-Now we are ready to solve for the principal components! To do so we +

Now we are ready to solve for the principal components! To do so we diagonalize the sample covariance matrix \( \Sigma \). We can use the function np.linalg.eig to do so. It will return the eigenvalues and eigenvectors of \( \Sigma \). Once we have these we can perform the following tasks: +

- $$ \begin{equation*} x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 \end{equation*} $$ -where \( v_0 \) is the first principal component. +

where \( v_0 \) is the first principal component.

-











+

Collecting all Steps

-

Collecting all Steps

+

Collecting all these steps we can write our own PCA function and +compare this with the functionality included in Scikit-Learn. +

-

-Collecting all these steps we can write our own PCA function and -compare this with the functionality included in Scikit-Learn. - -

-The code here outlines some of the elements we could include in the +

The code here outlines some of the elements we could include in the analysis. Feel free to extend upon this in order to address the above questions. +

-

-

# diagonalize and obtain eigenvalues, not necessarily sorted
+
+
+
+
+
+
# diagonalize and obtain eigenvalues, not necessarily sorted
 EigValues, EigVectors = np.linalg.eig(Cov)
 # sort eigenvectors and eigenvalues
 #permute = EigValues.argsort()
@@ -2325,83 +2927,90 @@ pca = PCA(n_components = 2)
 X2Dsl = pca.fit_transform(X)
 print("Eigenvector of largest eigenvalue")
 print(pca.components_.T[:, 0])
-
-

-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? +

+
+ + + +
+
+
+
+
+
+
+
+ + +

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?

-











+

Classical PCA Theorem

-

Classical PCA Theorem

- -

-We assume now that we have a design matrix \( \boldsymbol{X} \) which has been +

We assume now that we have a design matrix \( \boldsymbol{X} \) which has been centered as discussed above. For the sake of simplicity we skip the overline symbol. The matrix is defined in terms of the various column vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension \( \boldsymbol{x}\in {\mathbb{R}}^{n} \). +

-

-The PCA theorem states that minimizing the above reconstruction error +

The PCA theorem states that minimizing the above reconstruction error corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which diagonalizes the empirical covariance(correlation) matrix. The optimal low-dimensional encoding of the data is then given by a set of vectors \( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the orthogonal projection of the data onto the columns spanned by the eigenvectors of the covariance(correlations matrix). +

-











+

The PCA Theorem

-

The PCA Theorem

+

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

-

-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 - -

-We are almost there, we have obtained a relation between minimizing +

We are almost there, we have obtained a relation between minimizing the reconstruction error and the variance and the covariance matrix. Minimizing the error is equivalent to maximizing the variance of the projected data. +

-

-We could trivially maximize the variance of the projection (and +

We could trivially maximize the variance of the projection (and thereby minimize the error in the reconstruction function) by letting the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by \( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a Lagrange multiplier we can then in turn maximize +

$$ 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). $$ -Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain +

Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain

$$ \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, $$ -meaning that +

meaning that

$$ \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. $$ -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 +

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

$$ \boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. $$ -

-If we want to maximize the variance (minimize the construction error) +

If we want to maximize the variance (minimize the construction error) we simply pick the eigenvector of the covariance matrix with the largest eigenvalue. This establishes the link between the minimization of the reconstruction function \( J \) in terms of an orthogonal matrix and the maximization of the variance and thereby the covariance of our observations encoded in the design/feature matrix \( \boldsymbol{X} \). +

-

-The proof +

The proof for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be established by applying the above arguments and using the fact that our basis of eigenvectors is orthogonal, see Murphy chapter @@ -2409,29 +3018,30 @@ our basis of eigenvectors is orthogonal, see Vidal, Ma and Sastry, chapter 2. +

For more details, see for example Vidal, Ma and Sastry, chapter 2.

-











+

-

Geometric Interpretation and link with Singular Value Decomposition

+

For a detailed demonstration of the geometric interpretation, see Vidal, Ma and Sastry, section 2.1.2.

-

-For a detailed demonstration of the geometric interpretation, see Vidal, Ma and Sastry, section 2.1.2. - -

-Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. +

Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. +

-

-The following Python code uses NumPy’s svd() function to obtain all the principal components of the +

The following Python code uses NumPy’s svd() function to obtain all the principal components of the training set, then extracts the first two principal components. First we center the data using either pandas or our own code -

+

-
import numpy as np
+
+
+
+
+
+
import numpy as np
 import pandas as pd
 from IPython.display import display
 np.random.seed(100)
@@ -2455,64 +3065,134 @@ c2 = V.T[:, 1]
 W2 = V.T[:, :2]
 X2D = X_centered.dot(W2)
 print(X2D)
-
-

-PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering +

+
+ + + +
+
+
+
+
+
+
+
+ + +

PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t forget to center the data first. +

-

-Once you have identified all the principal components, you can reduce the dimensionality of the dataset +

Once you have identified all the principal components, you can reduce the dimensionality of the dataset down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

+

-
W2 = V.T[:, :2]
+
+
+
+
+
+
W2 = V.T[:, :2]
 X2D = X_centered.dot(W2)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

PCA and scikit-learn

-

PCA and scikit-learn

- -

-Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The +

Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note that it automatically takes care of centering the data): -

+

-
#thereafter we do a PCA with Scikit-learn
+
+
+
+
+
+
#thereafter we do a PCA with Scikit-learn
 from sklearn.decomposition import PCA
 pca = PCA(n_components = 2)
 X2D = pca.fit_transform(X)
 print(X2D)
-
-

-After fitting the PCA transformer to the dataset, you can access the principal components using the +

+
+ + + +
+
+
+
+
+
+
+
+ + +

After fitting the PCA transformer to the dataset, you can access the principal components using the components variable (note that it contains the PCs as horizontal vectors, so, for example, the first principal component is equal to -

+

-
pca.components_.T[:, 0]
-
-

-Another very useful piece of information is the explained variance ratio of each principal component, +

+
+
+
+
+
pca.components_.T[:, 0]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +

Another very useful piece of information is the explained variance ratio of each principal component, available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. +variance that lies along the axis of each principal component. +

-











- -

Back to the Cancer Data

-We can now repeat the above but applied to real data, in this case our breast cancer data. +

Back to the Cancer Data

+

We can now repeat the above but applied to real data, in this case our breast cancer data. Here we compute performance scores on the training data using logistic regression. -

+

-
import matplotlib.pyplot as plt
+
+
+
+
+
+
import matplotlib.pyplot as plt
 import numpy as np
 from sklearn.model_selection import  train_test_split 
 from sklearn.datasets import load_breast_cancer
@@ -2540,59 +3220,104 @@ X2D_train = pca.fit_transform(X_train_scaled)
 # and finally compute the log reg fit and the score on the training data	
 logreg.fit(X2D_train,y_train)
 print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
-
-

-We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. +

+
+ + + +
+
+
+
+
+
+
+
+ -

-Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to +

We see that our training data after the PCA decomposition has a performance similar to the non-scaled data.

+ +

Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). Unless, of course, you are reducing dimensionality for data visualization — in that case you will generally want to reduce the dimensionality down to 2 or 3. The following code computes PCA without reducing dimensionality, then computes the minimum number of dimensions required to preserve 95% of the training set’s variance: -

+

-
pca = PCA()
+
+
+
+
+
+
pca = PCA()
 pca.fit(X)
 cumsum = np.cumsum(pca.explained_variance_ratio_)
 d = np.argmax(cumsum >= 0.95) + 1
-
-

-You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead +

+
+ + + +
+
+
+
+
+
+
+
+ + +

You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

+

-
pca = PCA(n_components=0.95)
+
+
+
+
+
+
pca = PCA(n_components=0.95)
 X_reduced = pca.fit_transform(X)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Incremental PCA

-

Incremental PCA

- -

-One problem with the preceding implementation of PCA is that it requires the whole training set to fit in +

One problem with the preceding implementation of PCA is that it requires the whole training set to fit in memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new instances arrive). +

+

Randomized PCA

-

Randomized PCA

- -

-Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic +

Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic algorithm that quickly finds an approximation of the first d principal components. Its computational 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 previous algorithms when \( d \) is much smaller than \( n \). +

+

Kernel PCA

-

Kernel PCA

- -

-The kernel trick is a mathematical technique that implicitly maps instances into a +

The kernel trick is a mathematical technique that implicitly maps instances into a very high-dimensional space (called the feature space), enabling nonlinear classification and regression with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature space corresponds to a complex nonlinear decision boundary in the original space. @@ -2601,41 +3326,49 @@ projections for dimensionality reduction. This is called Kernel PCA (kPCA). It i preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a twisted manifold. For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

+

-
from sklearn.decomposition import KernelPCA
+
+
+
+
+
+
from sklearn.decomposition import KernelPCA
 rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
 X_reduced = rbf_pca.fit_transform(X)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Other techniques

-

Other techniques

- -

-There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. - -

-Here are some of the most popular: +

There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.

+

Here are some of the most popular:

- - - -
© 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
- - - diff --git a/doc/pub/week43/html/week43.html b/doc/pub/week43/html/week43.html index bd2b93d1e..6b1437d42 100644 --- a/doc/pub/week43/html/week43.html +++ b/doc/pub/week43/html/week43.html @@ -1,36 +1,105 @@ - + - Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis - - - - @@ -169,54 +273,44 @@ MathJax.Hub.Config({ - - +
+

Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis

+
- - -

Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis

- -

-

Morten Hjorth-Jensen [1, 2]
- -

+

+[1] Department of Physics, University of Oslo +
+
+[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
+
+
+

Nov 2, 2021

+
+
-
[1] Department of Physics, University of Oslo
-
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
-

-

Oct 29, 2021

-
-











- -

Plans for week 43

+

Plans for week 43

-
-Excellent lectures on CNNs and RNNs. +Excellent lectures on CNNs and RNNs

-

-

-More resources. +More resources

-

-











- -

Reading Recommendations

+

Reading Recommendations

+









+

Summary on Deep Learning Methods

+ +

We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).

+ +

The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images.











+

CNNs in brief

-

Summary on Deep Learning Methods

- -

-We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs). - -

-The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images. - -

-









- -

CNNs in brief

- -

-In summary: +

In summary:

- -For more material on convolutional networks, we strongly recommend +

For more material on convolutional networks, we strongly recommend the course IN5400 – Machine Learning for Image Analysis and the slides of CS231 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. +

-

-However, both standard feed forwards networks and CNNs perform well on data with unknown length. +

However, both standard feed forwards networks and CNNs perform well on data with unknown length.

-

-This is where recurrent nueral networks (RNNs) come to our rescue. +

This is where recurrent nueral networks (RNNs) come to our rescue.

-











+

Recurrent neural networks: Overarching view

-

Recurrent neural networks: Overarching view

- -

-Till now our focus has been, including convolutional neural networks +

Till now our focus has been, including convolutional neural networks as well, on feedforward neural networks. The output or the activations flow only in one direction, from the input layer to the output layer. +

-

-A recurrent neural network (RNN) looks very much like a feedforward +

A recurrent neural network (RNN) looks very much like a feedforward neural network, except that it also has connections pointing -backward. +backward. +

-

-RNNs are used to analyze time series data such as stock prices, and +

RNNs are used to analyze time series data such as stock prices, and tell you when to buy or sell. In autonomous driving systems, they can anticipate car trajectories and help avoid accidents. More generally, they can work on sequences of arbitrary lengths, rather than on @@ -308,24 +386,24 @@ fixed-sized inputs like all the nets we have discussed so far. For example, they can take sentences, documents, or audio samples as input, making them extremely useful for natural language processing systems such as automatic translation and speech-to-text. +

-











+

Set up of an RNN

-

Set up of an RNN

+

More to text to be added

-

-More to text to be added - -











+

A simple example

-

A simple example

- -

-

# Start importing packages
+
+
+
+
+
+
# Start importing packages
 import pandas as pd
 import numpy as np
 import matplotlib.pyplot as plt
@@ -393,22 +471,39 @@ plt.plot(index,df)
 plt.plot(index,predicted)
 plt.axvline(df.index[Tp], c="r")
 plt.show()
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

An extrapolation example

-

An extrapolation example

- -

-The following code provides an example of how recurrent neural +

The following code provides an example of how recurrent neural networks can be used to extrapolate to unknown values of physics data sets. Specifically, the data sets used in this program come from a quantum mechanical many-body calculation of energies as functions of the number of particles. +

-

-

# For matrices and calculations
+
+
+
+
+
+
# For matrices and calculations
 import numpy as np
 # For machine learning (backend for keras)
 import tensorflow as tf
@@ -435,14 +530,26 @@ X_tot = np.= np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
 	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
 	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Formatting the Data

-

Formatting the Data

- -

-The way the recurrent neural networks are trained in this program +

The way the recurrent neural networks are trained in this program differs from how machine learning algorithms are usually trained. Typically a machine learning algorithm is trained by learning the relationship between the x data and the y data. In this program, the @@ -452,9 +559,9 @@ typically used time series forcasting, but it can also be used in any extrapolation (time series forecasting is just a specific type of extrapolation along the time axis). This method of data formatting does not use the x data and assumes that the y data are evenly spaced. +

-

-For a standard machine learning algorithm, the training data has the +

For a standard machine learning algorithm, the training data has the form of (x,y) so the machine learning algorithm learns to assiciate a y value with a given x value. This is useful when the test data has x values within the same range as the training data. However, for this @@ -468,8 +575,8 @@ data. As long as the pattern of y data outside of the training region stays relatively stable compared to what was inside the training region, this method of training can produce accurate extrapolations to y values far removed from the training data set. +

-

@@ -477,10 +584,14 @@ y values far removed from the training data set. -

-

# FORMAT_DATA
+
+
+
+
+
+
# FORMAT_DATA
 def format_data(data, length_of_sequence = 2):  
     """
         Inputs:
@@ -552,16 +663,33 @@ y values far removed from the training data set.
     # function and an Adams optimizer.
     model.compile(loss="mean_squared_error", optimizer="adam")  
     return model
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Predicting New Points With A Trained Recurrent Neural Network

-

Predicting New Points With A Trained Recurrent Neural Network

- -

-

def test_rnn (x1, y_test, plot_min, plot_max):
+
+
+
+
+
+
def test_rnn (x1, y_test, plot_min, plot_max):
     """
         Inputs:
             x1 (a list or numpy array): The complete x component of the data set
@@ -652,14 +780,26 @@ test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim# Stop the timer and calculate the total time needed.
 end = timer()
 print('Time: ', end-start)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Other Things to Try

-

Other Things to Try

- -

-Changing the size of the recurrent neural network and its parameters +

Changing the size of the recurrent neural network and its parameters can drastically change the results you get from the model. The below code takes the simple recurrent neural network from above and adds a second hidden layer, changes the number of neurons in the hidden @@ -669,11 +809,16 @@ also be changed but are kept the same as the above network. These parameters can be tuned to provide the optimal result from the network. For some ideas on how to improve the performance of a recurrent neural network. +

-

-

def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
+
+
+
+
+
+
def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
     """
         Inputs:
             length_of_sequences (an int): the number of y values in "x data".  This is determined
@@ -759,21 +904,33 @@ test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim# Stop the timer and calculate the total time needed.
 end = timer()
 print('Time: ', end-start)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Other Types of Recurrent Neural Networks

-

Other Types of Recurrent Neural Networks

- -

-Besides a simple recurrent neural network layer, there are two other +

Besides a simple recurrent neural network layer, there are two other commonly used types of recurrent neural network layers: Long Short Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b. +

-

-The first network created below is similar to the previous network, +

The first network created below is similar to the previous network, but it replaces the SimpleRNN layers with LSTM layers. The second network below has two hidden layers made up of GRUs, which are preceeded by two dense (feeddorward) neural network layers. These @@ -781,11 +938,16 @@ dense layers "preprocess" the data before it reaches the recurrent layers. This architecture has been shown to improve the performance of recurrent neural networks (see the link above and also https://arxiv.org/pdf/1807.02857.pdf. +

-

-

def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
+
+
+
+
+
+
def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
     """
         Inputs:
             length_of_sequences (an int): the number of y values in "x data".  This is determined
@@ -975,14 +1137,26 @@ plt.show()
 # Stop the timer and calculate the total time needed.
 end = timer()
 print('Time: ', end-start)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Generative Models

-

Generative Models

- -

-Generative models describe a class of statistical models that are a contrast +

Generative models describe a class of statistical models that are a contrast to discriminative models. Informally we say that generative models can generate new data instances while discriminative models discriminate between different kinds of data instances. A generative model could generate new photos @@ -993,26 +1167,24 @@ just \( p(x) \) if there are no labels, while discriminative models capture the conditional probability \( p(y | x) \). Discriminative models generally try to draw boundaries in the data space (often high dimensional), while generative models try to model how data is placed throughout the space. +

-

-Note: this material is thanks to Linus Ekstrøm. +

Note: this material is thanks to Linus Ekstrøm.

-











+

Generative Adversarial Networks

-

Generative Adversarial Networks

- -

-Generative Adversarial Networks are a type of unsupervised machine learning +

Generative Adversarial Networks are a type of unsupervised machine learning algorithm proposed by Goodfellow et. al in 2014 (short and good article). +

-

-The simplest formulation of +

The simplest formulation of the model is based on a game theoretic approach, zero sum game, where we pit two neural networks against one another. We define two rival networks, one generator \( g \), and one discriminator \( d \). The generator directly produces samples +

$$ \begin{equation} x = g(z; \theta^{(g)}) @@ -1020,15 +1192,15 @@ $$ \end{equation} $$ -

-









-

Discriminator

-The discriminator attempts to distinguish between samples drawn from the +









+

Discriminator

+

The discriminator attempts to distinguish between samples drawn from the training data and samples drawn from the generator. In other words, it tries to tell the difference between the fake data produced by \( g \) and the actual data samples we want to do prediction on. The discriminator outputs a probability value given by +

$$ \begin{equation} @@ -1037,11 +1209,11 @@ $$ \end{equation} $$ -

-indicating the probability that \( x \) is a real training example rather than a +

indicating the probability that \( x \) is a real training example rather than a fake sample the generator has generated. The simplest way to formulate the learning process in a generative adversarial network is a zero-sum game, in which a function +

$$ \begin{equation} @@ -1050,9 +1222,9 @@ $$ \end{equation} $$ -

-determines the reward for the discriminator, while the generator gets the +

determines the reward for the discriminator, while the generator gets the conjugate reward +

$$ \begin{equation} @@ -1061,13 +1233,11 @@ $$ \end{equation} $$ -

+









+

Learning Process

-

Learning Process

- -

-During learning both of the networks maximize their own reward function, so that +

During learning both of the networks maximize their own reward function, so that the generator gets better and better at tricking the discriminator, while the discriminator gets better and better at telling the difference between the fake and real data. The generator and discriminator alternate on which one trains at @@ -1083,14 +1253,12 @@ tackle otherwise intractable generative problems. As the generator improves with if we continue training after this point then the generator is effectively training on junk data which can undo the learning up to that point. Therefore, we stop training when the discriminator starts outputting \( 1/2 \) everywhere. +

-











+

More about the Learning Process

-

More about the Learning Process

- -

-At convergence we have +

At convergence we have

$$ \begin{equation} @@ -1100,7 +1268,7 @@ $$ \end{equation} $$ -The default choice for \( v \) is +

The default choice for \( v \) is

$$ \begin{equation} v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x) @@ -1110,9 +1278,10 @@ $$ \end{equation} $$ -The main motivation for the design of GANs is that the learning process requires +

The main motivation for the design of GANs is that the learning process requires neither approximate inference (variational autoencoders for example) nor approximation of a partition function. In the case where +

$$ \begin{equation} \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) @@ -1120,15 +1289,14 @@ $$ \end{equation} $$ -is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is +

is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is asymptotically consistent ( Seth Lloyd on QuGANs ). +

-











- -

Additional References

-This is in +

Additional References

+

This is in general not the case and it is possible to get situations where the training process never converges because the generator and discriminator chase one another around in the parameter space indefinitely. A much deeper discussion on @@ -1139,37 +1307,57 @@ Direct quote: "In this best-performing formulation, the generator aims to increase the log probability that the discriminator makes a mistake, rather than aiming to decrease the log probability that the discriminator makes the correct prediction." Another interesting read +

-











- -

Writing Our First Generative Adversarial Network

-Let us now move on to actually implementing a GAN in tensorflow. We will study +

Writing Our First Generative Adversarial Network

+

Let us now move on to actually implementing a GAN in tensorflow. We will study the performance of our GAN on the MNIST dataset. This code is based on and adapted from the google tutorial +

-

-First we import our libraries +

First we import our libraries

-

-

import os
+
+
+
+
+
+
import os
 import time
 import numpy as np
 import tensorflow as tf
 import matplotlib.pyplot as plt
 from tensorflow.keras import layers
 from tensorflow.keras.utils import plot_model
-
-

-Next we define our hyperparameters and import our data the usual way +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Next we define our hyperparameters and import our data the usual way

-

-

BUFFER_SIZE = 60000
+
+
+
+
+
+
BUFFER_SIZE = 60000
 BATCH_SIZE = 256
 EPOCHS = 30
 
@@ -1184,37 +1372,71 @@ train_images = np= (train_images - 127.5) / 127.5
 training_dataset = tf.data.Dataset.from_tensor_slices(
                       train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

MNIST and GANs

-

MNIST and GANs

+

Let's have a quick look

-

-Let's have a quick look - -

-

plt.imshow(train_images[0], cmap='Greys')
+
+
+
+
+
+
plt.imshow(train_images[0], cmap='Greys')
 plt.show()
-
-

-Now we define our two models. This is where the 'magic' happens. There are a +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Now we define our two models. This is where the 'magic' happens. There are a huge amount of possible formulations for both models. A lot of engineering and trial and error can be done here to try to produce better performing models. For more advanced GANs this is by far the step where you can 'make or break' a model. +

-

-We start with the generator. As stated in the introductory text the generator +

We start with the generator. As stated in the introductory text the generator \( g \) upsamples from a random sample to the shape of what we want to predict. In our case we are trying to predict MNIST images (\( 28\times 28 \) pixels). +

-

-

def generator_model():
+
+
+
+
+
+
def generator_model():
     """
     The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to
     produce an image from a random seed. We start with a Dense layer taking this
@@ -1271,16 +1493,34 @@ our case we are trying to predict MNIST images (\( 28\times 28 \) pixels).
     assert model.output_shape == (None, 28, 28, 1)
 
     return model
-
-

-And there we have our 'simple' generator model. Now we move on to defining our +

+
+ + + +
+
+
+
+
+
+
+
+ + +

And there we have our 'simple' generator model. Now we move on to defining our discriminator model \( d \), which is a convolutional neural network based image classifier. +

-

-

def discriminator_model():
+
+
+
+
+
+
def discriminator_model():
     """
     The discriminator is a convolutional neural network based image classifier
     """
@@ -1309,86 +1549,203 @@ classifier.
     model.add(layers.Dense(1))
 
     return model
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Other Models

+

Let us take a look at our models. Note: double click images for bigger view.

-

Other Models

-Let us take a look at our models. Note: double click images for bigger view. - -

-

generator = generator_model()
+
+
+
+
+
+
generator = generator_model()
 plot_model(generator, show_shapes=True, rankdir='LR')
-
-

- +

+
+ + + +
+
+
+
+
+
+
+
-
discriminator = discriminator_model()
+
+
+
+
+
+
discriminator = discriminator_model()
 plot_model(discriminator, show_shapes=True, rankdir='LR')
-
-

-Next we need a few helper objects we will use in training +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Next we need a few helper objects we will use in training

-

-

cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
+
+
+
+
+
+
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
 generator_optimizer = tf.keras.optimizers.Adam(1e-4)
 discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
-
-

-The first object, cross_entropy is our loss function and the two others are +

+
+ + + +
+
+
+
+
+
+
+
+ + +

The first object, cross_entropy is our loss function and the two others are our optimizers. Notice we use the same learning rate for both \( g \) and \( d \). This is because they need to improve their accuracy at approximately equal speeds to get convergence (not necessarily exactly equal). Now we define our loss functions +

-

-

def generator_loss(fake_output):
+
+
+
+
+
+
def generator_loss(fake_output):
     loss = cross_entropy(tf.ones_like(fake_output), fake_output)
 
     return loss
-
-

- +

+
+ + + +
+
+
+
+
+
+
+
-
def discriminator_loss(real_output, fake_output):
+
+
+
+
+
+
def discriminator_loss(real_output, fake_output):
     real_loss = cross_entropy(tf.ones_like(real_output), real_output)
     fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)
     total_loss = real_loss + fake_loss
 
     return total_loss
-
-

-Next we define a kind of seed to help us compare the learning process over -multiple training epochs. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Next we define a kind of seed to help us compare the learning process over +multiple training epochs. +

-

-

noise_dimension = 100
+
+
+
+
+
+
noise_dimension = 100
 n_examples_to_generate = 16
 seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Training Step

-

Training Step

- -

-Now we have everything we need to define our training step, which we will apply +

Now we have everything we need to define our training step, which we will apply for every step in our training loop. Notice the @tf.function flag signifying that the function is tensorflow 'compiled'. Removing this flag doubles the computation time. +

-

-

@tf.function
+
+
+
+
+
+
@tf.function
 def train_step(images):
     noise = tf.random.normal([BATCH_SIZE, noise_dimension])
 
@@ -1411,15 +1768,33 @@ computation time.
                                             discriminator.trainable_variables))
 
     return gen_loss, disc_loss
-
-

-Next we define a helper function to produce an output over our training epochs +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Next we define a helper function to produce an output over our training epochs to see the predictive progression of our generator model. Note: I am including this code here, but comment it out in the training loop. -

+

-
def generate_and_save_images(model, epoch, test_input):
+
+
+
+
+
+
def generate_and_save_images(model, epoch, test_input):
     # we're making inferences here
     predictions = model(test_input, training=False)
 
@@ -1433,33 +1808,68 @@ this code here, but comment it out in the training loop.
     plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')
     plt.close()
     #plt.show()
-
-

-









+

+
+ + + +
+
+
+
+
+
+
+
+ -

Checkpoints

-Setting up checkpoints to periodically save our model during training so that + +









+

Checkpoints

+

Setting up checkpoints to periodically save our model during training so that everything is not lost even if the program were to somehow terminate while training. +

-

-

# Setting up checkpoints to save model during training
+
+
+
+
+
+
# Setting up checkpoints to save model during training
 checkpoint_dir = './training_checkpoints'
 checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')
 checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
                             discriminator_optimizer=discriminator_optimizer,
                             generator=generator,
                             discriminator=discriminator)
-
-

-Now we define our training loop +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Now we define our training loop

-

-

def train(dataset, epochs):
+
+
+
+
+
+
def train(dataset, epochs):
     generator_loss_list = []
     discriminator_loss_list = []
 
@@ -1488,53 +1898,103 @@ Now we define our training loop
         outfile.write(str(discriminator_loss_list))
         outfile.write('\n')
         outfile.write('\n')
-
-

-To train simply call this function. Warning: this might take a long time so -there is a folder of a pretrained network already included in the repository. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

To train simply call this function. Warning: this might take a long time so +there is a folder of a pretrained network already included in the repository. +

-

-

train(train_dataset, EPOCHS)
-
-

-And here is the result of training our model for 100 epochs +

+
+
+
+
+
train(train_dataset, EPOCHS)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-

+

And here is the result of training our model for 100 epochs

-

-Now to avoid having to train and everything, which will take a while depending +

Now to avoid having to train and everything, which will take a while depending on your computer setup we now load in the model which produced the above gif. +

-

-

checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
+
+
+
+
+
+
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
 restored_generator = checkpoint.generator
 restored_discriminator = checkpoint.discriminator
 
 print(restored_generator)
 print(restored_discriminator)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Exploring the Latent Space

-

Exploring the Latent Space

- -

-We have successfully loaded in our latest model. Let us now play around a bit +

We have successfully loaded in our latest model. Let us now play around a bit and see what kind of things we can learn about this model. Our generator takes an array of 100 numbers. One idea can be to try to systematically change our input. Let us try and see what we get +

-

-

def generate_latent_points(number=100, scale_means=1, scale_stds=1):
+
+
+
+
+
+
def generate_latent_points(number=100, scale_means=1, scale_stds=1):
     latent_dim = 100
     means = scale_means * tf.linspace(-1, 1, num=latent_dim)
     stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)
@@ -1550,11 +2010,26 @@ input. Let us try and see what we get
     generated_images = restored_generator.predict(latent_points)
 
     return generated_images
-
-

- +

+
+ + + +
+
+
+
+
+
+
+
-
def plot_result(generated_images, number=100):
+
+
+
+
+
+
def plot_result(generated_images, number=100):
     # obviously this assumes sqrt number is an int
     fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),
                             figsize=(10, 10))
@@ -1565,27 +2040,60 @@ input. Let us try and see what we get
             axs[i, j].axis('off')
 
     plt.show()
-
-

- +

+
+ + + +
+
+
+
+
+
+
+
-
generated_images = generate_images(generate_latent_points())
+
+
+
+
+
+
generated_images = generate_images(generate_latent_points())
 plot_result(generated_images)
-
-

-









+

+
+ + + +
+
+
+
+
+
+
+
+ -

Getting Results

-We see that the generator generates images that look like MNIST + +









+

Getting Results

+

We see that the generator generates images that look like MNIST numbers: \( 1, 4, 7, 9 \). Let's try to tweak it a bit more to see if we are able to generate a similar plot where we generate every MNIST number. Let us now try to 'move' a bit around in the latent space. Note: decrease the plot number if these following cells take too long to run on your computer. +

-

-

plot_number = 225
+
+
+
+
+
+
plot_number = 225
 
 generated_images = generate_images(generate_latent_points(number=plot_number,
                                                           scale_means=5,
@@ -1601,58 +2109,110 @@ generated_images = generate_images(generate_
                                                           scale_means=1,
                                                           scale_stds=5))
 plot_result(generated_images, number=plot_number)
-
-

-Again, we have found something interesting. Moving around using our means +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Again, we have found something interesting. Moving around using our means takes us from digit to digit, while moving around using our standard deviations seem to increase the number of different digits! In the last image above, we can barely make out every MNIST digit. Let us make on last plot using this information by upping the standard deviation of our Gaussian noises. +

-

-

plot_number = 400
+
+
+
+
+
+
plot_number = 400
 generated_images = generate_images(generate_latent_points(number=plot_number,
                                                           scale_means=1,
                                                           scale_stds=10))
 plot_result(generated_images, number=plot_number)
-
-

-A pretty cool result! We see that our generator indeed has learned a +

+
+ + + +
+
+
+
+
+
+
+
+ + +

A pretty cool result! We see that our generator indeed has learned a distribution which qualitatively looks a whole lot like the MNIST dataset. +

-











- -

Interpolating Between MNIST Digits

-Another interesting way to explore the latent space of our generator model is by +

Interpolating Between MNIST Digits

+

Another interesting way to explore the latent space of our generator model is by interpolating between the MNIST digits. This section is largely based on this excellent blogpost by Jason Brownlee. +

-

-So let us start by defining a function to interpolate between two points in the +

So let us start by defining a function to interpolate between two points in the latent space. +

-

-

def interpolation(point_1, point_2, n_steps=10):
+
+
+
+
+
+
def interpolation(point_1, point_2, n_steps=10):
     ratios = np.linspace(0, 1, num=n_steps)
     vectors = []
     for i, ratio in enumerate(ratios):
         vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))
 
     return tf.stack(vectors)
-
-

-Now we have all we need to do our interpolation analysis. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Now we have all we need to do our interpolation analysis.

-

-

plot_number = 100
+
+
+
+
+
+
plot_number = 100
 latent_points = generate_latent_points(number=plot_number)
 results = None
 for i in range(0, 2*np.sqrt(plot_number), 2):
@@ -1665,86 +2225,94 @@ results = = tf.stack((results, generated_images))
 
 plot_results(results, plot_number)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Basic ideas of the Principal Component Analysis (PCA)

-

Basic ideas of the Principal Component Analysis (PCA)

- -

-The principal component analysis deals with the problem of fitting a +

The principal component analysis deals with the problem of fitting a low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than the total dimension \( D \) of the problem at hand (our data set). Mathematically it can be formulated as a statistical problem or a geometric problem. In our discussion of the theorem for the classical PCA, we will stay with a statistical approach. Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable. +

-

-We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) - +

We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition)

+

A good read is for example Vidal, Ma and Sastry.

-A good read is for example Vidal, Ma and Sastry. - -











+

Introducing the Covariance and Correlation functions

-

Introducing the Covariance and Correlation functions

+

Before we discuss the PCA theorem, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities +

-

-Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities - -

-Suppose we have defined two vectors +

Suppose we have defined two vectors \( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +

$$ \boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ \end{bmatrix}, $$ -where for example +

where for example

$$ \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). $$ -With this definition and recalling that the variance is defined as +

With this definition and recalling that the variance is defined as

$$ \mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, $$ -we can rewrite the covariance matrix as +

we can rewrite the covariance matrix as

$$ \boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ \end{bmatrix}. $$ -

-









-

More on the covariance

-The covariance takes values between zero and infinity and may thus +









+

More on the covariance

+

The covariance takes values between zero and infinity and may thus lead to problems with loss of numerical precision for particularly large values. It is common to scale the covariance matrix by introducing instead the correlation matrix defined via the so-called correlation function +

$$ \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. $$ -

-The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] +

The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \in [-1,1] \). This avoids eventual problems with too large values. We can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) and \( \boldsymbol{y} \) as +

$$ \boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ @@ -1752,15 +2320,13 @@ $$ \end{bmatrix}, $$ -

-In the above example this is the function we constructed using pandas. +

In the above example this is the function we constructed using pandas.

-











- -

Reminding ourselves about Linear Regression

-In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression +

Reminding ourselves about Linear Regression

+

In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression we defined the design/feature matrix \( \boldsymbol{X} \) as +

$$ \boldsymbol{X}=\begin{bmatrix} @@ -1773,26 +2339,27 @@ x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ \end{bmatrix}, $$ -with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the +

with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the entries \( n \) being the row elements. We can rewrite the design/feature matrix in terms of its column vectors as +

$$ \boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, $$ -with a given vector +

with a given vector

$$ \boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. $$ -

-









-

Simple Example

-With these definitions, we can now rewrite our \( 2\times 2 \) +









+

Simple Example

+

With these definitions, we can now rewrite our \( 2\times 2 \) correlation/covariance matrix in terms of a moe general design/feature matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) +

$$ \boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} @@ -1805,13 +2372,11 @@ $$ \end{bmatrix}, $$ -

+









+

The Correlation Matrix

-

The Correlation Matrix

- -

-and the correlation matrix +

and the correlation matrix

$$ \boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} 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}]\\ @@ -1823,17 +2388,16 @@ $$ \end{bmatrix}, $$ -

+









+

Numpy Functionality

-

Numpy Functionality

- -

-The Numpy function np.cov calculates the covariance elements using +

The Numpy function np.cov calculates the covariance elements using the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have the exact mean values. The following simple function uses the np.vstack function which takes each vector of dimension \( 1\times n \) and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) +

$$ \boldsymbol{W}^T = \begin{bmatrix} x_0 & y_0 \\ @@ -1845,17 +2409,21 @@ $$ \end{bmatrix}, $$ -

-which in turn is converted into into the \( 2\times 2 \) covariance matrix +

which in turn is converted into into the \( 2\times 2 \) covariance matrix \( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy function np.mean(x). We can also extract the eigenvalues of the covariance matrix through the np.linalg.eig() function. +

-

-

# Importing various packages
+
+
+
+
+
+
# Importing various packages
 import numpy as np
 n = 100
 x = np.random.normal(size=n)
@@ -1865,23 +2433,40 @@ y = 4+3*
 W = np.vstack((x, y))
 C = np.cov(W)
 print(C)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Correlation Matrix again

-

Correlation Matrix again

- -

-The previous example can be converted into the correlation matrix by +

The previous example can be converted into the correlation matrix by simply scaling the matrix elements with the variances. We should also subtract the mean values for each column. This leads to the following code which sets up the correlations matrix for the previous example in -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). +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). +

-

-

import numpy as np
+
+
+
+
+
+
import numpy as np
 n = 100
 # define two vectors                                                                                           
 x = np.random.random(size=n)
@@ -1902,26 +2487,40 @@ C[1,1]0,1]= cov_xy/np.sqrt(variance_y*variance_x)
 C[1,0]= C[0,1]
 print(C)
-
-

-We see that the matrix elements along the diagonal are one as they +

+
+ + + +
+
+
+
+
+
+
+
+ + +

We see that the matrix elements along the diagonal are one as they should be and that the matrix is symmetric. Furthermore, diagonalizing this matrix we easily see that it is a positive definite matrix. +

-

-The above procedure with numpy can be made more compact if we use pandas. +

The above procedure with numpy can be made more compact if we use pandas.

-











+

Using Pandas

-

Using Pandas

- -

-We whow here how we can set up the correlation matrix using pandas, as done in this simple code -

+

We whow here how we can set up the correlation matrix using pandas, as done in this simple code

-
import numpy as np
+
+
+
+
+
+
import numpy as np
 import pandas as pd
 n = 10
 x = np.random.normal(size=n)
@@ -1934,19 +2533,35 @@ Xpd = pd.print(Xpd)
 correlation_matrix = Xpd.corr()
 print(correlation_matrix)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

And then the Franke Function

-

And then the Franke Function

+

We expand this model to the Franke function discussed above.

-

-We expand this model to the Franke function discussed above. - -

-

# Common imports
+
+
+
+
+
+
# Common imports
 import numpy as np
 import pandas as pd
 
@@ -1989,28 +2604,38 @@ Xpd = pd.= Xpd - Xpd.mean()
 covariance_matrix = Xpd.cov()
 print(covariance_matrix)
-
-

-We note here that the covariance is zero for the first rows and +

+
+ + + +
+
+
+
+
+
+
+
+ + +

We note here that the covariance is zero for the first rows and columns since all matrix elements in the design matrix were set to one (we are fitting the function in terms of a polynomial of degree \( n \)). We would however not include the intercept and wee can simply drop these elements and construct a correlation -matrix without them by centering our matrix elements by subtracting the mean of each column. +matrix without them by centering our matrix elements by subtracting the mean of each column. +

-











+

Lnks with the Design Matrix

-

Lnks with the Design Matrix

- -

-We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as +

We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as

$$ \boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. $$ -

-To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) +

To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)

$$ \boldsymbol{X}=\begin{bmatrix} x_{00} & x_{01}\\ @@ -2020,13 +2645,11 @@ x_{10} & x_{11}\\ \end{bmatrix}. $$ -

+









+

Computing the Expectation Values

-

Computing the Expectation Values

- -

-If we then compute the expectation value +

If we then compute the expectation value

$$ \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix} x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ @@ -2034,63 +2657,56 @@ x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ \end{bmatrix}, $$ -which is just +

which is just

$$ \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] \\ \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ \end{bmatrix}, $$ -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} \). +

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} \).

-

-It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). +

It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).

-











+

Towards the PCA theorem

-

Towards the PCA theorem

- -

-We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as +

We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as

$$ \boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. $$ -Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). +

Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). 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} \). +

-

-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}] \). +

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}] \).

-

-That is we have +

That is we have

$$ \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}, $$ -since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have +

since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have

$$ \boldsymbol{S}\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}, $$ -and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that +

and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that

$$ \boldsymbol{S}_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}_i. $$ -

+









+

More on the PCA Theorem

-

More on the PCA Theorem

+

In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is +\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). +

-

-In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). - -

-The eigenvalues tell us then how much we need to stretch the +

The eigenvalues tell us then how much we need to stretch the corresponding eigenvectors. Dimensions with large eigenvalues have thus large variations (large variance) and define therefore useful dimensions. The data points are more spread out in the direction of @@ -2101,19 +2717,15 @@ these specific directions. Hopefully then we could leave it out dimensions where the eigenvalues are very small. If \( p \) is very large, we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) features/predictors. +

-











+

The Algorithm before theorem

-

The Algorithm before theorem

- -

-Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. - +

Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here.

  • 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.
- $$ \boldsymbol{X}=\begin{bmatrix} x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ @@ -2125,7 +2737,6 @@ x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ \end{bmatrix}, $$ -
  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}^T\overline{\boldsymbol{X}}] \).
  • @@ -2133,34 +2744,36 @@ $$
  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • 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.
-









+

Writing our own PCA code

-

Writing our own PCA code

- -

-We will use a simple example first with two-dimensional data +

We will use a simple example first with two-dimensional data 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): +

$$ \mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ 2 & 2 \end{bmatrix} $$ -Note that the mean refers to each column of data. +

Note that the mean refers to each column of data. We will generate \( n = 10000 \) points \( X = \{ x_1, \ldots, x_N \} \) from 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. +

-











- -

Implementing it

-The following Python code aids in setting up the data and writing out the design matrix. +

Implementing it

+

The following Python code aids in setting up the data and writing out the design matrix. Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). -

+

-
import numpy as np
+
+
+
+
+
+
import numpy as np
 import pandas as pd
 import matplotlib.pyplot as plt
 from IPython.display import display
@@ -2168,44 +2781,72 @@ n = 10000= (-1, 2)
 cov = [[4, 2], [2, 2]]
 X = np.random.multivariate_normal(mean, cov, n)
-
-

-Now we are going to implement the PCA algorithm. We will break it down into various substeps. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

Now we are going to implement the PCA algorithm. We will break it down into various substeps.

-











+

First Step

-

First Step

- -

-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 +

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

$$ \mu_n = \frac{1}{n} \sum_{i=1}^n x_i $$ -and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form +

and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form

$$ \bar{x}_i = x_i - \mu_n. $$ -When you are done with these steps, print out \( \mu_n \) to verify it is +

When you are done with these steps, print out \( \mu_n \) to verify it is close to \( \mu \) and plot your mean centered data to verify it is centered at the origin! 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. -

+

-
df = pd.DataFrame(X)
+
+
+
+
+
+
df = pd.DataFrame(X)
 # Pandas does the centering for us
 df = df -df.mean()
 # we center it ourselves
 X_centered = X - X.mean(axis=0)
-
-

-









+

+
+ + + +
+
+
+
+
+
+
+
+ -

Scaling

-Alternatively, we could use the functions we discussed + +









+

Scaling

+

Alternatively, we could use the functions we discussed earlier for scaling the data set. That is, we could have used the StandardScaler function in Scikit-Learn, a function which ensures that for each feature/predictor we study the mean value is zero and @@ -2214,35 +2855,56 @@ would then not get the same results, since we divide by the variance. The diagonal covariance matrix elements will then be one, while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our specific case. +

-











+

Centered Data

-

Centered Data

- -

-Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation +

Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation

$$ \begin{equation*} \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) \end{equation*} $$ -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 \). +

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 \). We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows -

+

-
print(df.cov())
+
+
+
+
+
+
print(df.cov())
 print(np.cov(X_centered.T))
-
-

-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. +

+
+ + + +
+
+
+
+
+
+
+
+ + +

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. Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. -

+

-
# extract the relevant columns from the centered design matrix of dim n x 2
+
+
+
+
+
+
# extract the relevant columns from the centered design matrix of dim n x 2
 x = X_centered[:,0]
 y = X_centered[:,1]
 Cov = np.zeros((2,2))
@@ -2255,27 +2917,38 @@ Cov[1,0]
 plt.plot(x, y, 'x')
 plt.axis('equal')
 plt.show()
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Exploring

-

Exploring

+

Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. +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. +

-

-Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. -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. - -











+

Diagonalize the sample covariance matrix to obtain the principal components

-

Diagonalize the sample covariance matrix to obtain the principal components

- -

-Now we are ready to solve for the principal components! To do so we +

Now we are ready to solve for the principal components! To do so we diagonalize the sample covariance matrix \( \Sigma \). We can use the function np.linalg.eig to do so. It will return the eigenvalues and eigenvectors of \( \Sigma \). Once we have these we can perform the following tasks: +

  • We compute the percentage of the total variance captured by the first principal component
  • @@ -2283,33 +2956,34 @@ following tasks:
  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • Finally, we approximate the data as
- $$ \begin{equation*} x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 \end{equation*} $$ -where \( v_0 \) is the first principal component. +

where \( v_0 \) is the first principal component.

-











+

Collecting all Steps

-

Collecting all Steps

+

Collecting all these steps we can write our own PCA function and +compare this with the functionality included in Scikit-Learn. +

-

-Collecting all these steps we can write our own PCA function and -compare this with the functionality included in Scikit-Learn. - -

-The code here outlines some of the elements we could include in the +

The code here outlines some of the elements we could include in the analysis. Feel free to extend upon this in order to address the above questions. +

-

-

# diagonalize and obtain eigenvalues, not necessarily sorted
+
+
+
+
+
+
# diagonalize and obtain eigenvalues, not necessarily sorted
 EigValues, EigVectors = np.linalg.eig(Cov)
 # sort eigenvectors and eigenvalues
 #permute = EigValues.argsort()
@@ -2330,83 +3004,90 @@ pca = PCA(n_components = pca.fit_transform(X)
 print("Eigenvector of largest eigenvalue")
 print(pca.components_.T[:, 0])
-
-

-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? +

+
+ + + +
+
+
+
+
+
+
+
+ + +

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?

-











+

Classical PCA Theorem

-

Classical PCA Theorem

- -

-We assume now that we have a design matrix \( \boldsymbol{X} \) which has been +

We assume now that we have a design matrix \( \boldsymbol{X} \) which has been centered as discussed above. For the sake of simplicity we skip the overline symbol. The matrix is defined in terms of the various column vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension \( \boldsymbol{x}\in {\mathbb{R}}^{n} \). +

-

-The PCA theorem states that minimizing the above reconstruction error +

The PCA theorem states that minimizing the above reconstruction error corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which diagonalizes the empirical covariance(correlation) matrix. The optimal low-dimensional encoding of the data is then given by a set of vectors \( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the orthogonal projection of the data onto the columns spanned by the eigenvectors of the covariance(correlations matrix). +

-











+

The PCA Theorem

-

The PCA Theorem

+

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

-

-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 - -

-We are almost there, we have obtained a relation between minimizing +

We are almost there, we have obtained a relation between minimizing the reconstruction error and the variance and the covariance matrix. Minimizing the error is equivalent to maximizing the variance of the projected data. +

-

-We could trivially maximize the variance of the projection (and +

We could trivially maximize the variance of the projection (and thereby minimize the error in the reconstruction function) by letting the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by \( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a Lagrange multiplier we can then in turn maximize +

$$ 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). $$ -Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain +

Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain

$$ \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, $$ -meaning that +

meaning that

$$ \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. $$ -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 +

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

$$ \boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. $$ -

-If we want to maximize the variance (minimize the construction error) +

If we want to maximize the variance (minimize the construction error) we simply pick the eigenvector of the covariance matrix with the largest eigenvalue. This establishes the link between the minimization of the reconstruction function \( J \) in terms of an orthogonal matrix and the maximization of the variance and thereby the covariance of our observations encoded in the design/feature matrix \( \boldsymbol{X} \). +

-

-The proof +

The proof for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be established by applying the above arguments and using the fact that our basis of eigenvectors is orthogonal, see Murphy chapter @@ -2414,29 +3095,30 @@ our basis of eigenvectors is orthogonal, see Vidal, Ma and Sastry, chapter 2. +

For more details, see for example Vidal, Ma and Sastry, chapter 2.

-











+

-

Geometric Interpretation and link with Singular Value Decomposition

+

For a detailed demonstration of the geometric interpretation, see Vidal, Ma and Sastry, section 2.1.2.

-

-For a detailed demonstration of the geometric interpretation, see Vidal, Ma and Sastry, section 2.1.2. - -

-Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. +

Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. +

-

-The following Python code uses NumPy’s svd() function to obtain all the principal components of the +

The following Python code uses NumPy’s svd() function to obtain all the principal components of the training set, then extracts the first two principal components. First we center the data using either pandas or our own code -

+

-
import numpy as np
+
+
+
+
+
+
import numpy as np
 import pandas as pd
 from IPython.display import display
 np.random.seed(100)
@@ -2460,64 +3142,134 @@ c2 = V.T
 W2 = V.T[:, :2]
 X2D = X_centered.dot(W2)
 print(X2D)
-
-

-PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering +

+
+ + + +
+
+
+
+
+
+
+
+ + +

PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t forget to center the data first. +

-

-Once you have identified all the principal components, you can reduce the dimensionality of the dataset +

Once you have identified all the principal components, you can reduce the dimensionality of the dataset down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

+

-
W2 = V.T[:, :2]
+
+
+
+
+
+
W2 = V.T[:, :2]
 X2D = X_centered.dot(W2)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

PCA and scikit-learn

-

PCA and scikit-learn

- -

-Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The +

Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note that it automatically takes care of centering the data): -

+

-
#thereafter we do a PCA with Scikit-learn
+
+
+
+
+
+
#thereafter we do a PCA with Scikit-learn
 from sklearn.decomposition import PCA
 pca = PCA(n_components = 2)
 X2D = pca.fit_transform(X)
 print(X2D)
-
-

-After fitting the PCA transformer to the dataset, you can access the principal components using the +

+
+ + + +
+
+
+
+
+
+
+
+ + +

After fitting the PCA transformer to the dataset, you can access the principal components using the components variable (note that it contains the PCs as horizontal vectors, so, for example, the first principal component is equal to -

+

-
pca.components_.T[:, 0]
-
-

-Another very useful piece of information is the explained variance ratio of each principal component, +

+
+
+
+
+
pca.components_.T[:, 0]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +

Another very useful piece of information is the explained variance ratio of each principal component, available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. +variance that lies along the axis of each principal component. +

-











- -

Back to the Cancer Data

-We can now repeat the above but applied to real data, in this case our breast cancer data. +

Back to the Cancer Data

+

We can now repeat the above but applied to real data, in this case our breast cancer data. Here we compute performance scores on the training data using logistic regression. -

+

-
import matplotlib.pyplot as plt
+
+
+
+
+
+
import matplotlib.pyplot as plt
 import numpy as np
 from sklearn.model_selection import  train_test_split 
 from sklearn.datasets import load_breast_cancer
@@ -2545,59 +3297,104 @@ X2D_train = pca
 # and finally compute the log reg fit and the score on the training data	
 logreg.fit(X2D_train,y_train)
 print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
-
-

-We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. +

+
+ + + +
+
+
+
+
+
+
+
+ -

-Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to +

We see that our training data after the PCA decomposition has a performance similar to the non-scaled data.

+ +

Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). Unless, of course, you are reducing dimensionality for data visualization — in that case you will generally want to reduce the dimensionality down to 2 or 3. The following code computes PCA without reducing dimensionality, then computes the minimum number of dimensions required to preserve 95% of the training set’s variance: -

+

-
pca = PCA()
+
+
+
+
+
+
pca = PCA()
 pca.fit(X)
 cumsum = np.cumsum(pca.explained_variance_ratio_)
 d = np.argmax(cumsum >= 0.95) + 1
-
-

-You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead +

+
+ + + +
+
+
+
+
+
+
+
+ + +

You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

+

-
pca = PCA(n_components=0.95)
+
+
+
+
+
+
pca = PCA(n_components=0.95)
 X_reduced = pca.fit_transform(X)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Incremental PCA

-

Incremental PCA

- -

-One problem with the preceding implementation of PCA is that it requires the whole training set to fit in +

One problem with the preceding implementation of PCA is that it requires the whole training set to fit in memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new instances arrive). +

+

Randomized PCA

-

Randomized PCA

- -

-Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic +

Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic algorithm that quickly finds an approximation of the first d principal components. Its computational 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 previous algorithms when \( d \) is much smaller than \( n \). +

+

Kernel PCA

-

Kernel PCA

- -

-The kernel trick is a mathematical technique that implicitly maps instances into a +

The kernel trick is a mathematical technique that implicitly maps instances into a very high-dimensional space (called the feature space), enabling nonlinear classification and regression with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature space corresponds to a complex nonlinear decision boundary in the original space. @@ -2606,41 +3403,49 @@ projections for dimensionality reduction. This is called Kernel PCA (kPCA). It i preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a twisted manifold. For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

+

-
from sklearn.decomposition import KernelPCA
+
+
+
+
+
+
from sklearn.decomposition import KernelPCA
 rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
 X_reduced = rbf_pca.fit_transform(X)
-
-

+

+
+ + + +
+
+
+
+
+
+
+
+ + +









+

Other techniques

-

Other techniques

- -

-There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. - -

-Here are some of the most popular: +

There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.

+

Here are some of the most popular:

  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • 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.
  • 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).
  • 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.
- - - -
© 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
- - - diff --git a/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz b/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz index c6261b79a..de7261a04 100644 Binary files a/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz and b/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz differ diff --git a/doc/pub/week43/ipynb/week43.ipynb b/doc/pub/week43/ipynb/week43.ipynb index 66765cf9b..0d4a0f0cd 100644 --- a/doc/pub/week43/ipynb/week43.ipynb +++ b/doc/pub/week43/ipynb/week43.ipynb @@ -2,32 +2,48 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "bb8912ae", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "ceeae681", + "metadata": { + "editable": true + }, "source": [ - "\n", "# Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis\n", - "\n", - " \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: **Oct 29, 2021**\n", - "\n", - "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", - "\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": { + "editable": true + }, + "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", - "\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", - "\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", @@ -36,29 +52,48 @@ "\n", "* [Video on Deep Learning](https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi)\n", "\n", - "\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)\n", - "\n", - "\n", - "\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": { + "editable": true + }, + "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.\n", - "\n", + "* Aurelien Geron, chapter 14 on RNNs." + ] + }, + { + "cell_type": "markdown", + "id": "842f5497", + "metadata": { + "editable": true + }, + "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.\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": { + "editable": true + }, + "source": [ "## CNNs in brief\n", "\n", "In summary:\n", @@ -78,11 +113,18 @@ "[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", - "\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.\n", - "\n", + "This is where recurrent nueral networks (RNNs) come to our rescue." + ] + }, + { + "cell_type": "markdown", + "id": "cd85c599", + "metadata": { + "editable": true + }, + "source": [ "## Recurrent neural networks: Overarching view\n", "\n", "Till now our focus has been, including convolutional neural networks\n", @@ -100,21 +142,38 @@ "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.\n", - "\n", - "\n", + "systems such as automatic translation and speech-to-text." + ] + }, + { + "cell_type": "markdown", + "id": "44578951", + "metadata": { + "editable": true + }, + "source": [ "## Set up of an RNN\n", "\n", - "More to text to be added\n", - "\n", + "More to text to be added" + ] + }, + { + "cell_type": "markdown", + "id": "dcef62c4", + "metadata": { + "editable": true + }, + "source": [ "## A simple example" ] }, { "cell_type": "code", "execution_count": 1, + "id": "d1e1f8b0", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -192,7 +251,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7a672f93", + "metadata": { + "editable": true + }, "source": [ "## An extrapolation example\n", "\n", @@ -205,8 +267,10 @@ { "cell_type": "code", "execution_count": 2, + "id": "fec7cd79", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -242,7 +306,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3c152c36", + "metadata": { + "editable": true + }, "source": [ "## Formatting the Data\n", "\n", @@ -272,7 +339,6 @@ "region, this method of training can produce accurate extrapolations to\n", "y values far removed from the training data set.\n", "\n", - "\n", "\n", "\n", "\n", @@ -284,8 +350,10 @@ { "cell_type": "code", "execution_count": 3, + "id": "b2900154", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -365,7 +433,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eecb1945", + "metadata": { + "editable": true + }, "source": [ "## Predicting New Points With A Trained Recurrent Neural Network" ] @@ -373,8 +444,10 @@ { "cell_type": "code", "execution_count": 4, + "id": "32b674b8", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -473,11 +546,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7fd7f5d6", + "metadata": { + "editable": true + }, "source": [ "## Other Things to Try\n", "\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", @@ -493,8 +568,10 @@ { "cell_type": "code", "execution_count": 5, + "id": "6b4b438e", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -588,7 +665,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "05df6234", + "metadata": { + "editable": true + }, "source": [ "## Other Types of Recurrent Neural Networks\n", "\n", @@ -611,8 +691,10 @@ { "cell_type": "code", "execution_count": 6, + "id": "e0262cbb", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -810,7 +892,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e006cdfd", + "metadata": { + "editable": true + }, "source": [ "## Generative Models\n", "\n", @@ -826,8 +911,16 @@ "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. \n", - "\n", + "**Note**: this material is thanks to Linus Ekstrøm." + ] + }, + { + "cell_type": "markdown", + "id": "276dd606", + "metadata": { + "editable": true + }, + "source": [ "## Generative Adversarial Networks\n", "\n", "**Generative Adversarial Networks** are a type of unsupervised machine learning\n", @@ -843,7 +936,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ae501166", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -858,7 +954,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "409bdfef", + "metadata": { + "editable": true + }, "source": [ "## Discriminator\n", "The discriminator attempts to distinguish between samples drawn from the\n", @@ -870,7 +969,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fb082c5d", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -885,7 +987,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1525ddb5", + "metadata": { + "editable": true + }, "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", @@ -895,7 +1000,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6aa70c91", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -910,7 +1018,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "777e450d", + "metadata": { + "editable": true + }, "source": [ "determines the reward for the discriminator, while the generator gets the\n", "conjugate reward" @@ -918,7 +1029,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cf5297d4", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -933,7 +1047,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dbfbe4f0", + "metadata": { + "editable": true + }, "source": [ "## Learning Process\n", "\n", @@ -952,9 +1069,16 @@ " 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.\n", - "\n", - "\n", + " we stop training when the discriminator starts outputting $1/2$ everywhere." + ] + }, + { + "cell_type": "markdown", + "id": "6aa3b96a", + "metadata": { + "editable": true + }, + "source": [ "## More about the Learning Process\n", "\n", "At convergence we have" @@ -962,7 +1086,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a787801c", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -978,14 +1105,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8c433b7e", + "metadata": { + "editable": true + }, "source": [ "The default choice for $v$ is" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "117a59ec", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1002,7 +1135,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "036ab1a1", + "metadata": { + "editable": true + }, "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", @@ -1011,7 +1147,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0e3d13b4", + "metadata": { + "editable": true + }, "source": [ "\n", "
\n", @@ -1026,12 +1165,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7a743892", + "metadata": { + "editable": true + }, "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) ).\n", - "\n", + "( [Seth Lloyd on QuGANs](https://arxiv.org/pdf/1804.09139.pdf) )." + ] + }, + { + "cell_type": "markdown", + "id": "d4384dbb", + "metadata": { + "editable": true + }, + "source": [ "## Additional References\n", "This is in\n", "general not the case and it is possible to get situations where the training\n", @@ -1043,9 +1193,16 @@ "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)\n", - "\n", - "\n", + "prediction.\" [Another interesting read](https://arxiv.org/abs/1701.00160)" + ] + }, + { + "cell_type": "markdown", + "id": "b6f72b0f", + "metadata": { + "editable": true + }, + "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", @@ -1058,8 +1215,10 @@ { "cell_type": "code", "execution_count": 7, + "id": "f62f2392", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1074,7 +1233,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bf56bc45", + "metadata": { + "editable": true + }, "source": [ "Next we define our hyperparameters and import our data the usual way" ] @@ -1082,8 +1244,10 @@ { "cell_type": "code", "execution_count": 8, + "id": "77f775a5", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1106,7 +1270,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b850456f", + "metadata": { + "editable": true + }, "source": [ "## MNIST and GANs\n", "\n", @@ -1116,8 +1283,10 @@ { "cell_type": "code", "execution_count": 9, + "id": "18c95981", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1127,7 +1296,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "552a9eb3", + "metadata": { + "editable": true + }, "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", @@ -1143,8 +1315,10 @@ { "cell_type": "code", "execution_count": 10, + "id": "66828365", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1209,7 +1383,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "af3c3094", + "metadata": { + "editable": true + }, "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", @@ -1219,8 +1396,10 @@ { "cell_type": "code", "execution_count": 11, + "id": "6483f1ba", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1257,7 +1436,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7d330ae6", + "metadata": { + "editable": true + }, "source": [ "## Other Models\n", "Let us take a look at our models. **Note**: double click images for bigger view." @@ -1266,8 +1448,10 @@ { "cell_type": "code", "execution_count": 12, + "id": "3e5f5e35", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1278,8 +1462,10 @@ { "cell_type": "code", "execution_count": 13, + "id": "b1bac2c7", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1289,7 +1475,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "faa440ef", + "metadata": { + "editable": true + }, "source": [ "Next we need a few helper objects we will use in training" ] @@ -1297,8 +1486,10 @@ { "cell_type": "code", "execution_count": 14, + "id": "07992584", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1309,7 +1500,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e7750195", + "metadata": { + "editable": true + }, "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", @@ -1321,8 +1515,10 @@ { "cell_type": "code", "execution_count": 15, + "id": "6764500d", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1335,8 +1531,10 @@ { "cell_type": "code", "execution_count": 16, + "id": "451117b8", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1350,7 +1548,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a1a2558f", + "metadata": { + "editable": true + }, "source": [ "Next we define a kind of seed to help us compare the learning process over\n", "multiple training epochs." @@ -1359,8 +1560,10 @@ { "cell_type": "code", "execution_count": 17, + "id": "fd419bf0", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1371,7 +1574,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "21d5ab6b", + "metadata": { + "editable": true + }, "source": [ "## Training Step\n", "\n", @@ -1384,8 +1590,10 @@ { "cell_type": "code", "execution_count": 18, + "id": "5e3d108e", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1416,7 +1624,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2a3a8802", + "metadata": { + "editable": true + }, "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", @@ -1426,8 +1637,10 @@ { "cell_type": "code", "execution_count": 19, + "id": "bca416b1", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1449,7 +1662,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "651e1db3", + "metadata": { + "editable": true + }, "source": [ "## Checkpoints\n", "Setting up checkpoints to periodically save our model during training so that\n", @@ -1460,8 +1676,10 @@ { "cell_type": "code", "execution_count": 20, + "id": "d8cedbc7", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1476,7 +1694,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a53622bb", + "metadata": { + "editable": true + }, "source": [ "Now we define our training loop" ] @@ -1484,8 +1705,10 @@ { "cell_type": "code", "execution_count": 21, + "id": "9f4c3228", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1522,7 +1745,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b58cebd6", + "metadata": { + "editable": true + }, "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." @@ -1531,8 +1757,10 @@ { "cell_type": "code", "execution_count": 22, + "id": "26eb959a", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1541,7 +1769,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2a6252cd", + "metadata": { + "editable": true + }, "source": [ "And here is the result of training our model for 100 epochs\n", "\n", @@ -1552,8 +1783,10 @@ { "cell_type": "code", "execution_count": 23, + "id": "f5244029", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1567,11 +1800,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "87f98505", + "metadata": { + "editable": true + }, "source": [ "\n", "\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." ] @@ -1579,8 +1814,10 @@ { "cell_type": "code", "execution_count": 24, + "id": "63b2441d", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1594,7 +1831,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6b7f4858", + "metadata": { + "editable": true + }, "source": [ "## Exploring the Latent Space\n", "\n", @@ -1607,8 +1847,10 @@ { "cell_type": "code", "execution_count": 25, + "id": "7efda30c", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1633,8 +1875,10 @@ { "cell_type": "code", "execution_count": 26, + "id": "ebcb4e13", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1654,8 +1898,10 @@ { "cell_type": "code", "execution_count": 27, + "id": "642701d2", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1665,7 +1911,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0cc143f4", + "metadata": { + "editable": true + }, "source": [ "## Getting Results\n", "We see that the generator generates images that look like MNIST\n", @@ -1678,8 +1927,10 @@ { "cell_type": "code", "execution_count": 28, + "id": "4f808525", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1703,7 +1954,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5b71261e", + "metadata": { + "editable": true + }, "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", @@ -1715,8 +1969,10 @@ { "cell_type": "code", "execution_count": 29, + "id": "88c574cb", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1729,11 +1985,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "60489075", + "metadata": { + "editable": true + }, "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.\n", - "\n", + "distribution which qualitatively looks a whole lot like the MNIST dataset." + ] + }, + { + "cell_type": "markdown", + "id": "cba87cde", + "metadata": { + "editable": true + }, + "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", @@ -1747,8 +2014,10 @@ { "cell_type": "code", "execution_count": 30, + "id": "8262fb8d", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1763,7 +2032,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1a1ec074", + "metadata": { + "editable": true + }, "source": [ "Now we have all we need to do our interpolation analysis." ] @@ -1771,8 +2043,10 @@ { "cell_type": "code", "execution_count": 31, + "id": "69c03d1f", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1793,7 +2067,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b02e88cc", + "metadata": { + "editable": true + }, "source": [ "## Basic ideas of the Principal Component Analysis (PCA)\n", "\n", @@ -1812,9 +2089,16 @@ "\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).\n", - "\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": { + "editable": true + }, + "source": [ "## Introducing the Covariance and Correlation functions\n", "\n", "Before we discuss the PCA theorem, we need to remind ourselves about\n", @@ -1826,7 +2110,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1cc2d6ef", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", @@ -1837,14 +2124,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b07a53be", + "metadata": { + "editable": true + }, "source": [ "where for example" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "a8f008d7", + "metadata": { + "editable": true + }, "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", @@ -1853,14 +2146,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a3ad97c5", + "metadata": { + "editable": true + }, "source": [ "With this definition and recalling that the variance is defined as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "19aaf866", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n", @@ -1869,14 +2168,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9e747bef", + "metadata": { + "editable": true + }, "source": [ "we can rewrite the covariance matrix as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e0864a69", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", @@ -1887,7 +2192,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "039a6d65", + "metadata": { + "editable": true + }, "source": [ "## More on the covariance\n", "The covariance takes values between zero and infinity and may thus\n", @@ -1899,7 +2207,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f9663947", + "metadata": { + "editable": true + }, "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", @@ -1908,7 +2219,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "224c5a0d", + "metadata": { + "editable": true + }, "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", @@ -1918,7 +2232,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "51db7478", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", @@ -1929,10 +2246,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "95588be8", + "metadata": { + "editable": true + }, + "source": [ + "In the above example this is the function we constructed using **pandas**." + ] + }, + { + "cell_type": "markdown", + "id": "c6e38449", + "metadata": { + "editable": true + }, "source": [ - "In the above example this is the function we constructed using **pandas**.\n", - "\n", "## 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" @@ -1940,7 +2268,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "80b2a71a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}=\\begin{bmatrix}\n", @@ -1956,7 +2287,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0a864e62", + "metadata": { + "editable": true + }, "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", @@ -1965,7 +2299,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "12721f7c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n", @@ -1974,14 +2311,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5d971502", + "metadata": { + "editable": true + }, "source": [ "with a given vector" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "49da9cc9", + "metadata": { + "editable": true + }, "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", @@ -1990,7 +2333,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2560e5d2", + "metadata": { + "editable": true + }, "source": [ "## Simple Example\n", "With these definitions, we can now rewrite our $2\\times 2$\n", @@ -2001,7 +2347,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "be68f9f9", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n", @@ -2017,7 +2366,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "27ac6510", + "metadata": { + "editable": true + }, "source": [ "## The Correlation Matrix\n", "\n", @@ -2026,7 +2378,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6acb8936", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n", @@ -2042,7 +2397,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "506094b3", + "metadata": { + "editable": true + }, "source": [ "## Numpy Functionality\n", "\n", @@ -2055,7 +2413,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d4487e42", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{W}^T = \\begin{bmatrix} x_0 & y_0 \\\\\n", @@ -2070,7 +2431,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4c5e9844", + "metadata": { + "editable": true + }, "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", @@ -2082,8 +2446,10 @@ { "cell_type": "code", "execution_count": 32, + "id": "ae930dba", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2101,7 +2467,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "60e9a1c8", + "metadata": { + "editable": true + }, "source": [ "## Correlation Matrix again\n", "\n", @@ -2115,8 +2484,10 @@ { "cell_type": "code", "execution_count": 33, + "id": "faa6e59e", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2145,14 +2516,25 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "40ae29f3", + "metadata": { + "editable": true + }, "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**.\n", - "\n", + "The above procedure with **numpy** can be made more compact if we use **pandas**." + ] + }, + { + "cell_type": "markdown", + "id": "e2c9e103", + "metadata": { + "editable": true + }, + "source": [ "## Using Pandas\n", "\n", "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code" @@ -2161,8 +2543,10 @@ { "cell_type": "code", "execution_count": 34, + "id": "d07566bf", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2183,7 +2567,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "acec1fe2", + "metadata": { + "editable": true + }, "source": [ "## And then the Franke Function\n", "\n", @@ -2193,8 +2580,10 @@ { "cell_type": "code", "execution_count": 35, + "id": "0a5bbf22", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2245,15 +2634,26 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ec627c6e", + "metadata": { + "editable": true + }, "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. \n", - "\n", + "matrix without them by centering our matrix elements by subtracting the mean of each column." + ] + }, + { + "cell_type": "markdown", + "id": "b079de1e", + "metadata": { + "editable": true + }, + "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" @@ -2261,7 +2661,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b7ce13ea", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n", @@ -2270,14 +2673,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "84fe601b", + "metadata": { + "editable": true + }, "source": [ "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b84be038", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}=\\begin{bmatrix}\n", @@ -2291,7 +2700,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bcd07175", + "metadata": { + "editable": true + }, "source": [ "## Computing the Expectation Values\n", "\n", @@ -2300,7 +2712,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "825d6441", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n", @@ -2312,14 +2727,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c09ed5ee", + "metadata": { + "editable": true + }, "source": [ "which is just" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "621930aa", + "metadata": { + "editable": true + }, "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", @@ -2330,13 +2751,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c5374307", + "metadata": { + "editable": true + }, "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}$.\n", - "\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": { + "editable": true + }, + "source": [ "## Towards the PCA theorem\n", "\n", "We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as" @@ -2344,7 +2775,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "969874ba", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n", @@ -2353,7 +2787,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2b0ea2d2", + "metadata": { + "editable": true + }, "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", @@ -2365,7 +2802,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "624d3544", + "metadata": { + "editable": true + }, "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", @@ -2374,14 +2814,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3823d17a", + "metadata": { + "editable": true + }, "source": [ "since the matrix $\\boldsymbol{S}$ is not a data dependent matrix. Multiplying with $\\boldsymbol{S}$ from the left we have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "46a38924", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n", @@ -2390,14 +2836,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "151b9a1e", + "metadata": { + "editable": true + }, "source": [ "and since $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "2a02d193", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{S}_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}_i.\n", @@ -2406,14 +2858,16 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "977d900a", + "metadata": { + "editable": true + }, "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", - "\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", @@ -2424,8 +2878,16 @@ "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.\n", - "\n", + "features/predictors." + ] + }, + { + "cell_type": "markdown", + "id": "a4d95520", + "metadata": { + "editable": true + }, + "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", @@ -2434,7 +2896,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4f53f1d9", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}=\\begin{bmatrix}\n", @@ -2450,7 +2915,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3bc1325d", + "metadata": { + "editable": true + }, "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", @@ -2460,8 +2928,16 @@ "\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.\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": { + "editable": true + }, + "source": [ "## Writing our own PCA code\n", "\n", "We will use a simple example first with two-dimensional data\n", @@ -2470,7 +2946,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3af6eec6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu = (-1,2) \\qquad \\Sigma = \\begin{bmatrix} 4 & 2 \\\\\n", @@ -2481,12 +2960,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7b4579b4", + "metadata": { + "editable": true + }, "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.\n", - "\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": { + "editable": true + }, + "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$." @@ -2495,8 +2985,10 @@ { "cell_type": "code", "execution_count": 36, + "id": "ec1e3f1e", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2512,10 +3004,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "48ce0d35", + "metadata": { + "editable": true + }, + "source": [ + "Now we are going to implement the PCA algorithm. We will break it down into various substeps." + ] + }, + { + "cell_type": "markdown", + "id": "ecbc0719", + "metadata": { + "editable": true + }, "source": [ - "Now we are going to implement the PCA algorithm. We will break it down into various substeps.\n", - "\n", "## 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" @@ -2523,7 +3026,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0087d2dc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mu_n = \\frac{1}{n} \\sum_{i=1}^n x_i\n", @@ -2532,14 +3038,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e8489d42", + "metadata": { + "editable": true + }, "source": [ "and the mean-centered data $\\bar{X} = \\{ \\bar{x}_1, \\ldots, \\bar{x}_n \\}$ takes the form" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9a557753", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\bar{x}_i = x_i - \\mu_n.\n", @@ -2548,7 +3060,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "de3a6bd4", + "metadata": { + "editable": true + }, "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", @@ -2559,8 +3074,10 @@ { "cell_type": "code", "execution_count": 37, + "id": "04a64c6f", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2573,7 +3090,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "380e11e6", + "metadata": { + "editable": true + }, "source": [ "## Scaling\n", "Alternatively, we could use the functions we discussed\n", @@ -2584,8 +3104,16 @@ "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.\n", - "\n", + "specific case." + ] + }, + { + "cell_type": "markdown", + "id": "313212af", + "metadata": { + "editable": true + }, + "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" @@ -2593,7 +3121,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bf5aa29c", + "metadata": { + "editable": true + }, "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", @@ -2602,7 +3133,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cabe6168", + "metadata": { + "editable": true + }, "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" @@ -2611,8 +3145,10 @@ { "cell_type": "code", "execution_count": 38, + "id": "16b51366", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2622,7 +3158,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f4795982", + "metadata": { + "editable": true + }, "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." @@ -2631,8 +3170,10 @@ { "cell_type": "code", "execution_count": 39, + "id": "a17a2264", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2653,13 +3194,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d8c79888", + "metadata": { + "editable": true + }, "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. \n", - "\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": { + "editable": true + }, + "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", @@ -2679,7 +3231,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1b2237a0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "x_i \\approx \\tilde{x}_i = \\mu_n + \\langle x_i, v_0 \\rangle v_0\n", @@ -2688,10 +3243,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "422430b2", + "metadata": { + "editable": true + }, + "source": [ + "where $v_0$ is the first principal component." + ] + }, + { + "cell_type": "markdown", + "id": "2853d3af", + "metadata": { + "editable": true + }, "source": [ - "where $v_0$ is the first principal component. \n", - "\n", "## Collecting all Steps\n", "\n", "Collecting all these steps we can write our own PCA function and\n", @@ -2705,8 +3271,10 @@ { "cell_type": "code", "execution_count": 40, + "id": "f1553a35", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2735,10 +3303,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f14f4a68", + "metadata": { + "editable": true + }, + "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": { + "editable": true + }, "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? \n", - "\n", "## Classical PCA Theorem\n", "\n", "We assume now that we have a design matrix $\\boldsymbol{X}$ which has been\n", @@ -2747,30 +3326,31 @@ "vectors $[\\boldsymbol{x}_0,\\boldsymbol{x}_1,\\dots, \\boldsymbol{x}_{p-1}]$ each with dimension\n", "$\\boldsymbol{x}\\in {\\mathbb{R}}^{n}$.\n", "\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).\n", - "\n", - "\n", - "\n", + "eigenvectors of the covariance(correlations matrix)." + ] + }, + { + "cell_type": "markdown", + "id": "f93b8c77", + "metadata": { + "editable": true + }, + "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", - "\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", - "\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", @@ -2781,7 +3361,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7d7f444a", + "metadata": { + "editable": true + }, "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", @@ -2790,14 +3373,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "757137f1", + "metadata": { + "editable": true + }, "source": [ "Taking the derivative with respect to $\\boldsymbol{w}_0$ we obtain" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "cf073fb5", + "metadata": { + "editable": true + }, "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", @@ -2806,14 +3395,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "46cacc57", + "metadata": { + "editable": true + }, "source": [ "meaning that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b9d752e0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0\\boldsymbol{w}_0.\n", @@ -2822,14 +3417,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3a2a1499", + "metadata": { + "editable": true + }, "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", - "metadata": {}, + "id": "4c0d5781", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0.\n", @@ -2838,7 +3439,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "92dd2fd5", + "metadata": { + "editable": true + }, "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", @@ -2856,13 +3460,20 @@ "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).\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": { + "editable": true + }, + "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", - "\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", @@ -2873,8 +3484,10 @@ { "cell_type": "code", "execution_count": 41, + "id": "28f97424", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2906,7 +3519,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a057f309", + "metadata": { + "editable": true + }, "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", @@ -2920,8 +3536,10 @@ { "cell_type": "code", "execution_count": 42, + "id": "aa6bdcf5", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2931,7 +3549,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9b6e634b", + "metadata": { + "editable": true + }, "source": [ "## PCA and scikit-learn\n", "\n", @@ -2943,8 +3564,10 @@ { "cell_type": "code", "execution_count": 43, + "id": "27016f13", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2957,7 +3580,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cba40f30", + "metadata": { + "editable": true + }, "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", @@ -2967,8 +3593,10 @@ { "cell_type": "code", "execution_count": 44, + "id": "b4c61606", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -2977,12 +3605,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b5f6a25b", + "metadata": { + "editable": true + }, "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. \n", - "\n", + "variance that lies along the axis of each principal component." + ] + }, + { + "cell_type": "markdown", + "id": "0ac21d70", + "metadata": { + "editable": true + }, + "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." @@ -2991,8 +3630,10 @@ { "cell_type": "code", "execution_count": 45, + "id": "1fe89d6a", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -3028,11 +3669,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "284835e6", + "metadata": { + "editable": true + }, "source": [ "We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. \n", "\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", @@ -3044,8 +3687,10 @@ { "cell_type": "code", "execution_count": 46, + "id": "16dff606", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -3057,7 +3702,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3ca0f846", + "metadata": { + "editable": true + }, "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", @@ -3067,8 +3715,10 @@ { "cell_type": "code", "execution_count": 47, + "id": "b7dba51f", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -3078,7 +3728,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b0c6dd70", + "metadata": { + "editable": true + }, "source": [ "## Incremental PCA\n", "\n", @@ -3086,17 +3739,31 @@ "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).\n", - "\n", - "\n", + "instances arrive)." + ] + }, + { + "cell_type": "markdown", + "id": "43bbd33f", + "metadata": { + "editable": true + }, + "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$.\n", - "\n", - "\n", + "previous algorithms when $d$ is much smaller than $n$." + ] + }, + { + "cell_type": "markdown", + "id": "73ac8d86", + "metadata": { + "editable": true + }, + "source": [ "### Kernel PCA\n", "\n", "The kernel trick is a mathematical technique that implicitly maps instances into a\n", @@ -3113,8 +3780,10 @@ { "cell_type": "code", "execution_count": 48, + "id": "5c4a0d77", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -3125,11 +3794,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "56afa4e0", + "metadata": { + "editable": true + }, "source": [ "## Other techniques\n", "\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", @@ -3145,5 +3816,5 @@ ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/doc/pub/week44/html/._week44-bs000.html b/doc/pub/week44/html/._week44-bs000.html new file mode 100644 index 000000000..b724a2829 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs000.html @@ -0,0 +1,379 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +
+
+

Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees

+
+ + +
+Morten Hjorth-Jensen [1, 2] +
+ +
+[1] Department of Physics, University of Oslo +
+
+[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
+
+
+

Nov 2, 2021

+
+
+ + + +

Read »

+ + +
+ +

+ +

+ +
+ + + + +
+ © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + diff --git a/doc/pub/week44/html/._week44-bs001.html b/doc/pub/week44/html/._week44-bs001.html new file mode 100644 index 000000000..9e9a971e2 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs001.html @@ -0,0 +1,381 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Overview of week 44

+ +
    +
  • Thursday: Wrapping up PCA from last week, Clustering and basics of decision trees, classification and regression algorithms
  • +
  • Friday: Decision trees, voting models and bagging
  • +
+ + + +
+
+ +
    +
  1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion.
  2. +
  3. Clustering and PCA, see Geron's chapter 8 and Lecture notes
  4. +
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs002.html b/doc/pub/week44/html/._week44-bs002.html new file mode 100644 index 000000000..f5f26a55a --- /dev/null +++ b/doc/pub/week44/html/._week44-bs002.html @@ -0,0 +1,359 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Thursday, Principal Component Analysis

+ +

For the principal component analysis, +see slides from week 43, in particular from slide 28 and forward +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs003.html b/doc/pub/week44/html/._week44-bs003.html new file mode 100644 index 000000000..264de96c9 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs003.html @@ -0,0 +1,368 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Thursday: Clustering and Unsupervised Learning

+ +

In general terms cluster analysis, or clustering, is the task of grouping a +data-set into different distinct categories based on some measure of equality of +the data. This measure is often referred to as a metric or similarity +measure in the literature (note: sometimes we deal with a dissimilarity +measure instead). Usually, these metrics are formulated as some kind of +distance function between points in a high-dimensional space. +

+ +

The simplest, and also the most +common is the Euclidean distance. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs004.html b/doc/pub/week44/html/._week44-bs004.html new file mode 100644 index 000000000..981db4260 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs004.html @@ -0,0 +1,364 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Basic Idea of the \( k \)-means Clustering Algorithm

+ +

The simplest of all clustering algorithms is the k-means algorithm +, sometimes also referred to as Lloyds algorithm. It is the simplest and also +the most common. From its simplicity it obtains both strengths and weaknesses. +These will be discussed in more detail later. The \( k \)-means algorithm is a +centroid based clustering algorithm. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs005.html b/doc/pub/week44/html/._week44-bs005.html new file mode 100644 index 000000000..5f27c8ef8 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs005.html @@ -0,0 +1,378 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

The \( k \)-means Algorithm

+ +

Assume, we are given \( n \) data points and we wish to split the data into \( K < n \) +different categories, or clusters. We label each cluster by an integer +

+ +$$ k\in\{1, \cdots, K \}. +$$ + +

In the basic k-means algorithm each point is assigned to only +one cluster \( k \), and these assignments are non-injective i.e. many-to-one. We +can think of these mappings as an encoder \( k = C(i) \), which assigns the \( i \)-th +data-point \( \bf x_i \) to the \( k \)-th cluster. +

+ +

\( k \)-means algorithm in words:

+
    +
  1. We start with guesses / random initializations of our \( k \) cluster centers / centroids
  2. +
  3. For each centroid the points that are most similar are identified
  4. +
  5. Then we move / replace each centroid with a coordinate average of all the points that were assigned to that centroid.
  6. +
  7. Iterate this points 2, 3) until the centroids no longer move (to some tolerance)
  8. +
+

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs006.html b/doc/pub/week44/html/._week44-bs006.html new file mode 100644 index 000000000..bbb20d077 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs006.html @@ -0,0 +1,377 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Basic Math of the \( k \)-means Algorithm

+ +

We assume we have \( n \) data-points

+$$ +\begin{equation}\tag{1} + \boldsymbol{x_i} = \{x_{i, 1}, \cdots, x_{i, p}\}\in\mathbb{R}^p. +\end{equation} +$$ + +

which we wish to group into \( K < n \) clusters. For our dissimilarity measure we +use the squared Euclidean distance +

+$$ +\begin{equation}\tag{2} + d(\boldsymbol{x_i}, \boldsymbol{x_i'}) = \sum_{j=1}^p(x_{ij} - x_{i'j})^2 + = ||\boldsymbol{x_i} - \boldsymbol{x_{i'}}||^2 +\end{equation} +$$ + + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs007.html b/doc/pub/week44/html/._week44-bs007.html new file mode 100644 index 000000000..cddf8fc39 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs007.html @@ -0,0 +1,382 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Within Cluster Point Scatter

+ +

We define the so called within-cluster point scatter which gives us a +measure of how close each data point assigned to the same cluster tends to be to +the all the others. +

+$$ +\begin{equation}\tag{3} + W(C) = \frac{1}{2}\sum_{k=1}^K\sum_{C(i)=k} + \sum_{C(i')=k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}}) = + \sum_{k=1}^KN_k\sum_{C(i)=k}||\boldsymbol{x_i} - \boldsymbol{\overline{x_k}}||^2 +\end{equation} +$$ + +

where \( \boldsymbol{\overline{x_k}} \) is the mean vector associated with the \( k \)-th +cluster, and \( N_k = \sum_{i=1}^nI(C(i) = k) \), where the \( I() \) notation is +similar to the Kronecker delta (Commonly used in statistics, it just means that +when \( i = k \) we have the encoder \( C(i) \)). In other words, the within-cluster +scatter measures the compactness of each cluster with respect to the data points +assigned to each cluster. This is the quantity that the \( k \)-means algorithm aims +to minimize. We refer to this quantity \( W(C) \) as the within cluster scatter +because of its relation to the total scatter. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs008.html b/doc/pub/week44/html/._week44-bs008.html new file mode 100644 index 000000000..09212e6e7 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs008.html @@ -0,0 +1,379 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

More Details

+ +

We have

+$$ +\begin{equation}\tag{4} + T = W(C) + B(C) = \frac{1}{2}\sum_{i=1}^n + \sum_{i'=1}^nd(\boldsymbol{x_i}, \boldsymbol{x_{i'}}) + = \frac{1}{2}\sum_{k=1}^K\sum_{C(i)=k} + \Big(\sum_{C(i') = k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}}) + + \sum_{C(i')\neq k}d(\boldsymbol{x_i}, \boldsymbol{x_{i'}})\Big). +\end{equation} +$$ + +

This is a quantity that is conserved throughout the \( k \)-means algorithm. It can +be thought of as the total amount of information in the data, and it is composed +of the aforementioned within-cluster scatter and the between-cluster scatter +\( B(C) \). In methods such as principle component analysis the total scatter is not +conserved. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs009.html b/doc/pub/week44/html/._week44-bs009.html new file mode 100644 index 000000000..7abf980fc --- /dev/null +++ b/doc/pub/week44/html/._week44-bs009.html @@ -0,0 +1,370 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Total Cluster Variance

+

Given a cluster mean \( \boldsymbol{m_k} \) we define the total cluster variance

+$$ +\begin{equation}\tag{5} + \min_{C, \{\boldsymbol{m_k}\}_1^K}\sum_{k=1}^KN_k\sum||\boldsymbol{x_i} - \boldsymbol{m_k}||^2 +\end{equation} +$$ + +

Now we have all the pieces necessary to formally revisit the \( k \)-means algorithm.

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs010.html b/doc/pub/week44/html/._week44-bs010.html new file mode 100644 index 000000000..9ed4f4c8f --- /dev/null +++ b/doc/pub/week44/html/._week44-bs010.html @@ -0,0 +1,370 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

The \( k \)-means Clustering Algorithm

+ +

The \( k \)-means clustering algorithm goes as follows

+ +
    +
  1. For a given cluster assignment \( C \), and \( k \) cluster means \( \left\{m_1, \cdots, m_k\right\} \). We minimize the total cluster variance with respect to the cluster means \( \{m_k\} \) yielding the means of the currently assigned clusters.
  2. +
  3. Given a current set of \( k \) means \( \{m_k\} \) the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is $$C(i) = \underset{1\leq k\leq K}{\mathrm{argmin}} ||\boldsymbol{x_i} - \boldsymbol{m_k}||^2$$
  4. +
  5. Steps 1 and 2 are repeated until the assignments do not change.
  6. +
+

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs011.html b/doc/pub/week44/html/._week44-bs011.html new file mode 100644 index 000000000..c827535b8 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs011.html @@ -0,0 +1,370 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Summarizing

+ +
    +
  1. Before we start we specify a number \( k \) which is the number of clusters we want to try to separate our data into.
  2. +
  3. We initially choose \( k \) random data points in our data as our initial centroids, or means (this is where the name comes from).
  4. +
  5. Assign each data point to their closest centroid, based on the squared Euclidean distance.
  6. +
  7. For each of the \( k \) cluster we update the centroid by calculating new mean values for all the data points in the cluster.
  8. +
  9. Iteratively minimize the within cluster scatter by performing steps (3, 4) until the new assignments stop changing (can be to some tolerance) or until a maximum number of iterations have passed.
  10. +
+

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs012.html b/doc/pub/week44/html/._week44-bs012.html new file mode 100644 index 000000000..61702355d --- /dev/null +++ b/doc/pub/week44/html/._week44-bs012.html @@ -0,0 +1,480 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Writing our own Code, the Data Set

+ +

Let us now program the most basic version of the algorithm using nothing but +Python with numpy arrays. This code is kept intentionally simple to gradually +progress our understanding. There is no vectorization of any kind, and even most +helper functions are not utilized. +

+ +

We need first a dataset to do our cluster analysis on. In our case +this is a plain vanilla data set using random numbers using a +Gaussian distribution. +

+ + + +
+
+
+
+
+
import time
+import numpy as np
+import tensorflow as tf
+from matplotlib import image
+import matplotlib.pyplot as plt
+from sklearn.cluster import KMeans
+from IPython.display import display
+
+np.random.seed(2021)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +

Next we define functions, for ease of use later, to generate Gaussians and to +set up our toy data set. +

+ + +
+
+
+
+
+
def gaussian_points(dim=2, n_points=1000, mean_vector=np.array([0, 0]),
+                    sample_variance=1):
+    """
+    Very simple custom function to generate gaussian distributed point clusters
+    with variable dimension, number of points, means in each direction
+    (must match dim) and sample variance.
+
+    Inputs:
+        dim (int)
+        n_points (int)
+        mean_vector (np.array) (where index 0 is x, index 1 is y etc.)
+        sample_variance (float)
+
+    Returns:
+        data (np.array): with dimensions (dim x n_points)
+    """
+
+    mean_matrix = np.zeros(dim) + mean_vector
+    covariance_matrix = np.eye(dim) * sample_variance
+    data = np.random.multivariate_normal(mean_matrix, covariance_matrix,
+                                    n_points)
+    return data
+
+
+
+def generate_simple_clustering_dataset(dim=2, n_points=1000, plotting=True,
+                                    return_data=True):
+    """
+    Toy model to illustrate k-means clustering
+    """
+
+    data1 = gaussian_points(mean_vector=np.array([5, 5]))
+    data2 = gaussian_points()
+    data3 = gaussian_points(mean_vector=np.array([1, 4.5]))
+    data4 = gaussian_points(mean_vector=np.array([5, 1]))
+    data = np.concatenate((data1, data2, data3, data4), axis=0)
+
+    if plotting:
+        fig, ax = plt.subplots()
+        ax.scatter(data[:, 0], data[:, 1], alpha=0.2)
+        ax.set_title('Toy Model Dataset')
+        plt.show()
+
+
+    if return_data:
+        return data
+
+
+data = generate_simple_clustering_dataset()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs013.html b/doc/pub/week44/html/._week44-bs013.html new file mode 100644 index 000000000..0b21b654c --- /dev/null +++ b/doc/pub/week44/html/._week44-bs013.html @@ -0,0 +1,423 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Implementing the \( k \)-means Algorithm

+ +

With the above dataset we start +implementing the \( k \)-means algorithm. +

+ + + +
+
+
+
+
+
n_samples, dimensions = data.shape
+n_clusters = 4
+
+# we randomly initialize our centroids
+np.random.seed(2021)
+centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :]
+distances = np.zeros((n_samples, n_clusters))
+
+# first we need to calculate the distance to each centroid from our data
+for k in range(n_clusters):
+    for n in range(n_samples):
+        dist = 0
+        for d in range(dimensions):
+            dist += np.abs(data[n, d] - centroids[k, d])**2
+            distances[n, k] = dist
+
+# we initialize an array to keep track of to which cluster each point belongs
+# the way we set it up here the index tracks which point and the value which
+# cluster the point belongs to
+cluster_labels = np.zeros(n_samples, dtype='int')
+
+# next we loop through our samples and for every point assign it to the cluster
+# to which it has the smallest distance to
+for n in range(n_samples):
+    # tracking variables (all of this is basically just an argmin)
+    smallest = 1e10
+    smallest_row_index = 1e10
+    for k in range(n_clusters):
+        if distances[n, k] < smallest:
+            smallest = distances[n, k]
+            smallest_row_index = k
+
+    cluster_labels[n] = smallest_row_index
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs014.html b/doc/pub/week44/html/._week44-bs014.html new file mode 100644 index 000000000..8087209d5 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs014.html @@ -0,0 +1,409 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Plotting

+ + +
+
+
+
+
+
fig = plt.figure()
+ax = fig.add_subplot()
+unique_cluster_labels = np.unique(cluster_labels)
+for i in unique_cluster_labels:
+    ax.scatter(data[cluster_labels == i, 0],
+               data[cluster_labels == i, 1],
+               label = i,
+               alpha = 0.2)
+    ax.scatter(centroids[:, 0], centroids[:, 1], c='black')
+
+ax.set_title("First Grouping of Points to Centroids")
+
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +

So what do we have so far? We have 'picked' \( k \) centroids at random from our +data points. There are other ways of more intelligently choosing their +initializations, however for our purposes randomly is fine. Then we have +initialized an array 'distances' which holds the information of the distance, +or dissimilarity, of every point to of our centroids. Finally, we have +initialized an array 'cluster_labels' which according to our distances array +holds the information of to which centroid every point is assigned. This was the +first pass of our algorithm. Essentially, all we need to do now is repeat the +distance and assignment steps above until we have reached a desired convergence +or a maximum amount of iterations. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs015.html b/doc/pub/week44/html/._week44-bs015.html new file mode 100644 index 000000000..8f735ec2f --- /dev/null +++ b/doc/pub/week44/html/._week44-bs015.html @@ -0,0 +1,430 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Continuing

+ + + +
+
+
+
+
+
max_iterations = 100
+tolerance = 1e-8
+
+for iteration in range(max_iterations):
+    prev_centroids = centroids.copy()
+    for k in range(n_clusters):
+        # this array will be used to update our centroid positions
+        vector_mean = np.zeros(dimensions)
+        mean_divisor = 0
+        for n in range(n_samples):
+            if cluster_labels[n] == k:
+                vector_mean += data[n, :]
+                mean_divisor += 1
+
+        # update according to the k means
+        centroids[k, :] = vector_mean / mean_divisor
+
+    # we find the dissimilarity
+    for k in range(n_clusters):
+        for n in range(n_samples):
+            dist = 0
+            for d in range(dimensions):
+                dist += np.abs(data[n, d] - centroids[k, d])**2
+                distances[n, k] = dist
+
+    # assign each point
+    for n in range(n_samples):
+        smallest = 1e10
+        smallest_row_index = 1e10
+        for k in range(n_clusters):
+            if distances[n, k] < smallest:
+                smallest = distances[n, k]
+                smallest_row_index = k
+
+        cluster_labels[n] = smallest_row_index
+
+    # convergence criteria
+    centroid_difference = np.sum(np.abs(centroids - prev_centroids))
+    if centroid_difference < tolerance:
+        print(f'Converged at iteration {iteration}')
+        break
+
+    elif iteration == max_iterations:
+        print(f'Did not converge in {max_iterations} iterations')
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs016.html b/doc/pub/week44/html/._week44-bs016.html new file mode 100644 index 000000000..9844c8ec4 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs016.html @@ -0,0 +1,489 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Wrapping it up

+

We now have a simple , un-optimized \( k \)-means +clustering implementation. Lets plot the final result +

+ + + +
+
+
+
+
+
fig = plt.figure()
+ax = fig.add_subplot()
+unique_cluster_labels = np.unique(cluster_labels)
+for i in unique_cluster_labels:
+    ax.scatter(data[cluster_labels == i, 0],
+               data[cluster_labels == i, 1],
+               label = i,
+               alpha = 0.2)
+    ax.scatter(centroids[:, 0], centroids[:, 1], c='black')
+
+ax.set_title("Final Result of K-means Clustering")
+
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
def naive_kmeans(data, n_clusters=4, max_iterations=100, tolerance=1e-8):
+    start_time = time.time()
+
+    n_samples, dimensions = data.shape
+    n_clusters = 4
+    #np.random.seed(2021)
+    centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :]
+    distances = np.zeros((n_samples, n_clusters))
+
+    for k in range(n_clusters):
+        for n in range(n_samples):
+            dist = 0
+            for d in range(dimensions):
+                dist += np.abs(data[n, d] - centroids[k, d])**2
+                distances[n, k] = dist
+
+    cluster_labels = np.zeros(n_samples, dtype='int')
+
+    for n in range(n_samples):
+        smallest = 1e10
+        smallest_row_index = 1e10
+        for k in range(n_clusters):
+            if distances[n, k] < smallest:
+                smallest = distances[n, k]
+                smallest_row_index = k
+
+        cluster_labels[n] = smallest_row_index
+
+    for iteration in range(max_iterations):
+        prev_centroids = centroids.copy()
+        for k in range(n_clusters):
+            vector_mean = np.zeros(dimensions)
+            mean_divisor = 0
+            for n in range(n_samples):
+                if cluster_labels[n] == k:
+                    vector_mean += data[n, :]
+                    mean_divisor += 1
+
+            centroids[k, :] = vector_mean / mean_divisor
+
+        for k in range(n_clusters):
+            for n in range(n_samples):
+                dist = 0
+                for d in range(dimensions):
+                    dist += np.abs(data[n, d] - centroids[k, d])**2
+                    distances[n, k] = dist
+
+        for n in range(n_samples):
+            smallest = 1e10
+            smallest_row_index = 1e10
+            for k in range(n_clusters):
+                if distances[n, k] < smallest:
+                    smallest = distances[n, k]
+                    smallest_row_index = k
+
+            cluster_labels[n] = smallest_row_index
+
+        centroid_difference = np.sum(np.abs(centroids - prev_centroids))
+        if centroid_difference < tolerance:
+            print(f'Converged at iteration {iteration}')
+            print(f'Runtime: {time.time() - start_time} seconds')
+
+            return cluster_labels, centroids
+
+    print(f'Did not converge in {max_iterations} iterations')
+    print(f'Runtime: {time.time() - start_time} seconds')
+
+    return cluster_labels, centroids
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs017.html b/doc/pub/week44/html/._week44-bs017.html new file mode 100644 index 000000000..f85de7e77 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs017.html @@ -0,0 +1,388 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + +
+
+

 

 

 

+ + +

Decision trees, overarching aims

+ +

We start here with the most basic algorithm, the so-called decision +tree. With this basic algorithm we can in turn build more complex +networks, spanning from homogeneous and heterogenous forests (bagging, +random forests and more) to one of the most popular supervised +algorithms nowadays, the extreme gradient boosting, or just +XGBoost. But let us start with the simplest possible ingredient. +

+ +

Decision trees are supervised learning algorithms used for both, +classification and regression tasks. +

+ +

The main idea of decision trees +is to find those descriptive features which contain the most +information regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. +

+ +

The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the most +informative feature is done until we accomplish a stopping criteria +where we then finally end up in so called leaf nodes. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs018.html b/doc/pub/week44/html/._week44-bs018.html new file mode 100644 index 000000000..c1bb2ffdc --- /dev/null +++ b/doc/pub/week44/html/._week44-bs018.html @@ -0,0 +1,375 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Basics of a tree

+ +

A decision tree is typically divided into a root node, the interior nodes, +and the final leaf nodes or just leaves. These entities are then connected by so-called branches. +

+ +

The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs019.html b/doc/pub/week44/html/._week44-bs019.html new file mode 100644 index 000000000..8de318c6b --- /dev/null +++ b/doc/pub/week44/html/._week44-bs019.html @@ -0,0 +1,365 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

A Sketch of a Tree, Regression problem

+ + + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs020.html b/doc/pub/week44/html/._week44-bs020.html new file mode 100644 index 000000000..1f0d7de18 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs020.html @@ -0,0 +1,365 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

A Sketch of a Tree, Classification problem

+ + + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs021.html b/doc/pub/week44/html/._week44-bs021.html new file mode 100644 index 000000000..78270c5fc --- /dev/null +++ b/doc/pub/week44/html/._week44-bs021.html @@ -0,0 +1,371 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

A typical Decision Tree with its pertinent Jargon, Classification Problem

+ +

+
+

+
+

+ +

This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches.

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs022.html b/doc/pub/week44/html/._week44-bs022.html new file mode 100644 index 000000000..6da4a8f19 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs022.html @@ -0,0 +1,375 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

General Features

+ +

The overarching approach to decision trees is a top-down approach.

+ +
    +
  • A leaf provides the classification of a given instance.
  • +
  • A node specifies a test of some attribute of the instance.
  • +
  • A branch corresponds to a possible values of an attribute.
  • +
  • An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
  • +
+

This process is then repeated for the subtree rooted at the new +node. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs023.html b/doc/pub/week44/html/._week44-bs023.html new file mode 100644 index 000000000..22edb57c7 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs023.html @@ -0,0 +1,375 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

How do we set it up?

+ +

In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: +

+ +
    +
  1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
  2. +
  3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
  4. +
  5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
  6. +
  7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
  8. +
+

Then we are essentially done!

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs024.html b/doc/pub/week44/html/._week44-bs024.html new file mode 100644 index 000000000..adcc7f3d7 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs024.html @@ -0,0 +1,473 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Decision trees and Regression

+ + +
+
+
+
+
+
import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x<steps:
+    distance+=np.random.randint(-1,2)
+    distance_list.append(distance)
+    x+=1
+    steps_list.append(x)
+plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
+
+steps_list=np.asarray(steps_list)
+distance_list=np.asarray(distance_list)
+
+X=steps_list[:,np.newaxis]
+
+#Polynomial fits
+
+#Degree 2
+poly_features=PolynomialFeatures(degree=2, include_bias=False)
+X_poly=poly_features.fit_transform(X)
+
+lin_reg=LinearRegression()
+poly_fit=lin_reg.fit(X_poly,distance_list)
+b=lin_reg.coef_
+c=lin_reg.intercept_
+print ("2nd degree coefficients:")
+print ("zero power: ",c)
+print ("first power: ", b[0])
+print ("second power: ",b[1])
+
+z = np.arange(0, steps, .01)
+z_mod=b[1]*z**2+b[0]*z+c
+
+fit_mod=b[1]*X**2+b[0]*X+c
+plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
+plt.title("Polynomial Regression")
+
+plt.xlabel("Steps")
+plt.ylabel("Distance")
+
+#Degree 10
+poly_features10=PolynomialFeatures(degree=10, include_bias=False)
+X_poly10=poly_features10.fit_transform(X)
+
+poly_fit10=lin_reg.fit(X_poly10,distance_list)
+
+y_plot=poly_fit10.predict(X_poly10)
+plt.plot(X, y_plot, color='black', label="10th Degree Fit")
+
+plt.legend()
+plt.show()
+
+
+#Decision Tree Regression
+from sklearn.tree import DecisionTreeRegressor
+regr_1=DecisionTreeRegressor(max_depth=2)
+regr_2=DecisionTreeRegressor(max_depth=5)
+regr_3=DecisionTreeRegressor(max_depth=7)
+regr_1.fit(X, distance_list)
+regr_2.fit(X, distance_list)
+regr_3.fit(X, distance_list)
+
+X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
+y_1 = regr_1.predict(X_test)
+y_2 = regr_2.predict(X_test)
+y_3=regr_3.predict(X_test)
+
+# Plot the results
+plt.figure()
+plt.scatter(X, distance_list, s=2.5, c="black", label="data")
+plt.plot(X_test, y_1, color="red",
+         label="max_depth=2", linewidth=2)
+plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
+plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
+
+plt.xlabel("Data")
+plt.ylabel("Darget")
+plt.title("Decision Tree Regression")
+plt.legend()
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs025.html b/doc/pub/week44/html/._week44-bs025.html new file mode 100644 index 000000000..1d30c9a6d --- /dev/null +++ b/doc/pub/week44/html/._week44-bs025.html @@ -0,0 +1,384 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Building a tree, regression

+ +

There are mainly two steps

+
    +
  1. We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
  2. +
  3. For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
  4. +
+

How do we construct the regions \( R_1,\dots,R_J \)? In theory, the +regions could have any shape. However, we choose to divide the +predictor space into high-dimensional rectangles, or boxes, for +simplicity and for ease of interpretation of the resulting predictive +model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the +MSE, given by +

+ +$$ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +$$ + +

where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \). +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs026.html b/doc/pub/week44/html/._week44-bs026.html new file mode 100644 index 000000000..2f16b4418 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs026.html @@ -0,0 +1,377 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

A top-down approach, recursive binary splitting

+ +

Unfortunately, it is computationally infeasible to consider every +possible partition of the feature space into \( J \) boxes. The common +strategy is to take a top-down approach +

+ +

The approach is top-down because it begins at the top of the tree (all +observations belong to a single region) and then successively splits +the predictor space; each split is indicated via two new branches +further down on the tree. It is greedy because at each step of the +tree-building process, the best split is made at that particular step, +rather than looking ahead and picking a split that will lead to a +better tree in some future step. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs027.html b/doc/pub/week44/html/._week44-bs027.html new file mode 100644 index 000000000..f6f5f9332 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs027.html @@ -0,0 +1,409 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Making a tree

+ +

In order to implement the recursive binary splitting we start by selecting +the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +

+$$ +\left\{X\vert x_j < s\right\}, +$$ + +

and

+$$ +\left\{X\vert x_j \geq s\right\}, +$$ + +

so that we obtain the lowest MSE, that is

+$$ +\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, +$$ + +

which we want to minimize by considering all predictors +\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for +each predictor. These values could be determined by randomly assigned +numbers or by starting at the midpoint and then proceed till we find +an optimal value. +

+ +

For any \( j \) and \( s \), we define the pair of half-planes where +\( \overline{y}_{R_1} \) is the mean response for the training +observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean +response for the training observations in \( R_2(j,s) \). +

+ +

Finding the values of \( j \) and \( s \) that minimize the above equation can be +done quite quickly, especially when the number of features \( p \) is not +too large. +

+ +

Next, we repeat the process, looking +for the best predictor and best cutpoint in order to split the data +further so as to minimize the MSE within each of the resulting +regions. However, this time, instead of splitting the entire predictor +space, we split one of the two previously identified regions. We now +have three regions. Again, we look to split one of these three regions +further, so as to minimize the MSE. The process continues until a +stopping criterion is reached; for instance, we may continue until no +region contains more than five observations. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs028.html b/doc/pub/week44/html/._week44-bs028.html new file mode 100644 index 000000000..e52a76f46 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs028.html @@ -0,0 +1,379 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Pruning the tree

+ +

The above procedure is rather straightforward, but leads often to +overfitting and unnecessarily large and complicated trees. The basic +idea is to grow a large tree \( T_0 \) and then prune it back in order to +obtain a subtree. A smaller tree with fewer splits (fewer regions) can +lead to smaller variance and better interpretation at the cost of a +little more bias. +

+ +

The so-called Cost complexity pruning algorithm gives us a +way to do just this. Rather than considering every possible subtree, +we consider a sequence of trees indexed by a nonnegative tuning +parameter \( \alpha \). +

+ +

Read more at the following Scikit-Learn link on pruning.

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs029.html b/doc/pub/week44/html/._week44-bs029.html new file mode 100644 index 000000000..897335630 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs029.html @@ -0,0 +1,391 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Cost complexity pruning

+ +

For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that

+$$ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +$$ + +

is as small as possible. Here \( \overline{T} \) is +the number of terminal nodes of the tree \( T \) , \( R_m \) is the +rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. +

+ +

The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +complexity and its fit to the training data. When \( \alpha = 0 \), then the +subtree \( T \) will simply equal \( T_0 \), +because then the above equation just measures the +training error. +However, as \( \alpha \) increases, there is a price to pay for +having a tree with many terminal nodes. The above equation will +tend to be minimized for a smaller subtree. +

+ +

It turns out that as we increase \( \alpha \) from zero +branches get pruned from the tree in a nested and predictable fashion, +so obtaining the whole sequence of subtrees as a function of \( \alpha \) is +easy. We can select a value of \( \alpha \) using a validation set or using +cross-validation. We then return to the full data set and obtain the +subtree corresponding to \( \alpha \). +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs030.html b/doc/pub/week44/html/._week44-bs030.html new file mode 100644 index 000000000..c5ec85bfd --- /dev/null +++ b/doc/pub/week44/html/._week44-bs030.html @@ -0,0 +1,382 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Schematic Regression Procedure

+ +
+
+ + +
    +
  1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
  2. +
  3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
  4. +
  5. Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
  6. +
      +
    • repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
    • +
    • Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
    • +
    • Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
    • +
    +
  7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
  8. +
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs031.html b/doc/pub/week44/html/._week44-bs031.html new file mode 100644 index 000000000..de54bfba6 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs031.html @@ -0,0 +1,377 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

A Classification Tree

+ +

A classification tree is very similar to a regression tree, except +that it is used to predict a qualitative response rather than a +quantitative one. Recall that for a regression tree, the predicted +response for an observation is given by the mean response of the +training observations that belong to the same terminal node. In +contrast, for a classification tree, we predict that each observation +belongs to the most commonly occurring class of training observations +in the region to which it belongs. In interpreting the results of a +classification tree, we are often interested not only in the class +prediction corresponding to a particular terminal node region, but +also in the class proportions among the training observations that +fall into that region. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs032.html b/doc/pub/week44/html/._week44-bs032.html new file mode 100644 index 000000000..ab885b59e --- /dev/null +++ b/doc/pub/week44/html/._week44-bs032.html @@ -0,0 +1,382 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Growing a classification tree

+ +

The task of growing a +classification tree is quite similar to the task of growing a +regression tree. Just as in the regression setting, we use recursive +binary splitting to grow a classification tree. However, in the +classification setting, the MSE cannot be used as a criterion for making +the binary splits. A natural alternative to MSE is the classification +error rate. Since we plan to assign an observation in a given region +to the most commonly occurring error rate class of training +observations in that region, the classification error rate is simply +the fraction of the training observations in that region that do not +belong to the most common class. +

+ +

When building a classification tree, either the Gini index or the +entropy are typically used to evaluate the quality of a particular +split, since these two approaches are more sensitive to node purity +than is the classification error rate. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs033.html b/doc/pub/week44/html/._week44-bs033.html new file mode 100644 index 000000000..29e0c5334 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs033.html @@ -0,0 +1,404 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Classification tree, how to split nodes

+ +

If our targets are the outcome of a classification process that takes +for example \( k=1,2,\dots,K \) values, the only thing we need to think of +is to set up the splitting criteria for each node. +

+ +

We define a PDF \( p_{mk} \) that represents the number of observations of +a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent +this likelihood function in terms of the proportion \( I(y_i=k) \) of +observations of this class in the region \( R_m \) as +

+ +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k). +$$ + +

We let \( p_{mk} \) represent the majority class of observations in region +\( m \). The three most common ways of splitting a node are given by +

+ +
    +
  • Misclassification error
  • +
+$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +$$ + +
    +
  • Gini index \( g \)
  • +
+$$ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +$$ + +
    +
  • Information entropy or just entropy \( s \)
  • +
+$$ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +$$ + + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs034.html b/doc/pub/week44/html/._week44-bs034.html new file mode 100644 index 000000000..1b8598014 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs034.html @@ -0,0 +1,418 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Visualizing the Tree, Classification

+ + +
+
+
+
+
+
import os
+from sklearn.datasets import load_breast_cancer
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.metrics import confusion_matrix
+from sklearn.tree import export_graphviz
+
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import pandas as pd
+import numpy as np
+
+
+cancer = load_breast_cancer()
+X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+print(X)
+y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
+y = pd.get_dummies(y)
+print(y)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/cancer.dot",
+    feature_names=cancer.feature_names,
+    class_names=cancer.target_names,
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs035.html b/doc/pub/week44/html/._week44-bs035.html new file mode 100644 index 000000000..ba122ecfd --- /dev/null +++ b/doc/pub/week44/html/._week44-bs035.html @@ -0,0 +1,409 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Visualizing the Tree, The Moons

+ + +
+
+
+
+
+
# Common imports
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+from pydot import graph_from_dot_data
+import pandas as pd
+import os
+
+np.random.seed(42)
+X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
+X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/moons.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
+os.system(cmd)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs036.html b/doc/pub/week44/html/._week44-bs036.html new file mode 100644 index 000000000..9d6cc2c38 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs036.html @@ -0,0 +1,395 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Other ways of visualizing the trees

+ +

Scikit-Learn has also another way to visualize the trees which is very useful, here with the Iris data.

+ + + +
+
+
+
+
+
from sklearn.datasets import load_iris
+from sklearn import tree
+X, y = load_iris(return_X_y=True)
+tree_clf = tree.DecisionTreeClassifier()
+tree_clf = tree_clf.fit(X, y)
+# and then plot the tree
+tree.plot_tree(tree_clf) 
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs037.html b/doc/pub/week44/html/._week44-bs037.html new file mode 100644 index 000000000..6c2d4e747 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs037.html @@ -0,0 +1,398 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Printing out as text

+ +

Alternatively, the tree can also be exported in textual format with the function exporttext. +This method doesn’t require the installation of external libraries and is more compact: +

+ + + +
+
+
+
+
+
from sklearn.datasets import load_iris
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.tree import export_text
+iris = load_iris()
+decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
+decision_tree = decision_tree.fit(iris.data, iris.target)
+r = export_text(decision_tree, feature_names=iris['feature_names'])
+print(r)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs038.html b/doc/pub/week44/html/._week44-bs038.html new file mode 100644 index 000000000..b0302e228 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs038.html @@ -0,0 +1,374 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Algorithms for Setting up Decision Trees

+ +

Two algorithms stand out in the set up of decision trees:

+
    +
  1. The CART (Classification And Regression Tree) algorithm for both classification and regression
  2. +
  3. The ID3 algorithm based on the computation of the information gain for classification
  4. +
+

We discuss both algorithms with applications here. The popular library +Scikit-Learn uses the CART algorithm. For classification problems +you can use either the gini index or the entropy to split a tree +in two branches. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs039.html b/doc/pub/week44/html/._week44-bs039.html new file mode 100644 index 000000000..818ecb02f --- /dev/null +++ b/doc/pub/week44/html/._week44-bs039.html @@ -0,0 +1,386 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

The CART algorithm for Classification

+ +

For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +This could be for example a threshold set by a number below a certain circumference of a malign tumor. +

+ +

How do we find these two quantities? +We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). +The cost function it tries to minimize is then +

+$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, +$$ + +

where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) + is the number of instances in the left/right subset +

+ +

Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the +\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other +hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), +\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs040.html b/doc/pub/week44/html/._week44-bs040.html new file mode 100644 index 000000000..250c5e1a7 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs040.html @@ -0,0 +1,386 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

The CART algorithm for Regression

+ +

The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now +

+$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. +$$ + +

Here the MSE for a specific node is defined as

+$$ +\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, +$$ + +

with

+$$ +\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, +$$ + +

the mean value of all observations in a specific node.

+ +

Without any regularization, the regression task for decision trees, +just like for classification tasks, is prone to overfitting. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs041.html b/doc/pub/week44/html/._week44-bs041.html new file mode 100644 index 000000000..624799d58 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs041.html @@ -0,0 +1,402 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Computing the Gini index

+ +

The example we will look at is a classical one in many Machine +Learning applications. Based on various meteorological features, we +have several so-called attributes which decide whether we at the end +will do some outdoor activity like skiing, going for a bike ride etc +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +attributes for each feature are then sunny, overcast and rain for the +outlook, hot, cold and mild for temperature, high and normal for +humidity and weak and strong for wind. +

+ +

The table here summarizes the various attributes and

+
+
+ + + + + + + + + + + + + + + + + + + + +
Day Outlook Temperature Humidity Wind Ride
1 Sunny Hot High Weak 0
2 Sunny Hot High Strong 1
3 Overcast Hot High Weak 1
4 Rain Mild High Weak 1
5 Rain Cool Normal Weak 1
6 Rain Cool Normal Strong 0
7 Overcast Cool Normal Strong 1
8 Sunny Mild High Weak 0
9 Sunny Cool Normal Weak 1
10 Rain Mild Normal Weak 1
11 Sunny Mild Normal Strong 1
12 Overcast Mild High Strong 1
13 Overcast Hot Normal Weak 1
14 Rain Mild High Strong 0
+
+
+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs042.html b/doc/pub/week44/html/._week44-bs042.html new file mode 100644 index 000000000..e888f7925 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs042.html @@ -0,0 +1,453 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Simple Python Code to read in Data and perform Classification

+ + + +
+
+
+
+
+
# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.tree import export_graphviz
+from sklearn.preprocessing import StandardScaler, OneHotEncoder
+from sklearn.compose import ColumnTransformer
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+    os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+    os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+    os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+    return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+    return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+    plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("rideclass.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
+ridedata = pd.DataFrame(ridedata)
+
+# Features and targets
+X = ridedata.loc[:, ridedata.columns != 'Ride'].values
+y = ridedata.loc[:, ridedata.columns == 'Ride'].values
+
+# Create the encoder.
+encoder = OneHotEncoder(handle_unknown="ignore")
+# Assume for simplicity all features are categorical.
+encoder.fit(X)    
+# Apply the encoder.
+X = encoder.transform(X)
+print(X)
+# Then do a Classification tree
+tree_clf = DecisionTreeClassifier(max_depth=2)
+tree_clf.fit(X, y)
+print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
+#transfer to a decision tree graph
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/ride.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs043.html b/doc/pub/week44/html/._week44-bs043.html new file mode 100644 index 000000000..463976793 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs043.html @@ -0,0 +1,454 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Computing the Gini Factor

+ +

The above functions (gini, entropy and misclassification error) are +important components of the so-called CART algorithm. We will discuss +this algorithm below after we have discussed the information gain +algorithm ID3. +

+ +

In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc.

+ + + +
+
+
+
+
+
# Split a dataset based on an attribute and an attribute value
+def test_split(index, value, dataset):
+	left, right = list(), list()
+	for row in dataset:
+		if row[index] < value:
+			left.append(row)
+		else:
+			right.append(row)
+	return left, right
+ 
+# Calculate the Gini index for a split dataset
+def gini_index(groups, classes):
+	# count all samples at split point
+	n_instances = float(sum([len(group) for group in groups]))
+	# sum weighted Gini index for each group
+	gini = 0.0
+	for group in groups:
+		size = float(len(group))
+		# avoid divide by zero
+		if size == 0:
+			continue
+		score = 0.0
+		# score the group based on the score for each class
+		for class_val in classes:
+			p = [row[-1] for row in group].count(class_val) / size
+			score += p * p
+		# weight the group score by its relative size
+		gini += (1.0 - score) * (size / n_instances)
+	return gini
+
+# Select the best split point for a dataset
+def get_split(dataset):
+	class_values = list(set(row[-1] for row in dataset))
+	b_index, b_value, b_score, b_groups = 999, 999, 999, None
+	for index in range(len(dataset[0])-1):
+		for row in dataset:
+			groups = test_split(index, row[index], dataset)
+			gini = gini_index(groups, class_values)
+			print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
+			if gini < b_score:
+				b_index, b_value, b_score, b_groups = index, row[index], gini, groups
+	return {'index':b_index, 'value':b_value, 'groups':b_groups}
+ 
+dataset = [[0,0,0,0,0],
+            [0,0,0,1,1],
+            [1,0,0,0,1],
+            [2,1,0,0,1],
+            [2,2,1,0,1],
+            [2,2,1,1,0],
+            [1,2,1,1,1],
+            [0,1,0,0,0],
+            [0,2,1,0,1],
+            [2,1,1,0,1],
+            [0,1,1,1,1],
+            [1,1,0,1,1],
+            [1,0,1,0,1],
+            [2,1,0,1,0]]
+
+split = get_split(dataset)
+print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs044.html b/doc/pub/week44/html/._week44-bs044.html new file mode 100644 index 000000000..9534ceed9 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs044.html @@ -0,0 +1,393 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Entropy and the ID3 algorithm

+ +

The ID3 algorithm learns decision trees by constructing +them in a top down way, beginning with the question which attribute should be tested at the root of the tree? +

+ +
    +
  1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
  2. +
  3. The best attribute is selected and used as the test at the root node of the tree.
  4. +
  5. A descendant of the root node is then created for each possible value of this attribute.
  6. +
  7. Training examples are sorted to the appropriate descendant node.
  8. +
  9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
  10. +
  11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
  12. +
+

The ID3 algorithm selects which attribute to test at each node in the +tree. +

+ +

We would like to select the attribute that is most useful for classifying +examples. +

+ +

What is a good quantitative measure of the worth of an attribute?

+ +

Information gain measures how well a given attribute separates the +training examples according to their target classification. +

+ +

The ID3 algorithm uses this information gain measure to select among the candidate +attributes at each step while growing the tree. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs045.html b/doc/pub/week44/html/._week44-bs045.html new file mode 100644 index 000000000..f4eca1581 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs045.html @@ -0,0 +1,426 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Cancer Data again now with Decision Trees and other Methods

+ + +
+
+
+
+
+
import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs046.html b/doc/pub/week44/html/._week44-bs046.html new file mode 100644 index 000000000..b2f7d1e94 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs046.html @@ -0,0 +1,449 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Another example, the moons again

+ + +
+
+
+
+
+
from __future__ import division, print_function, unicode_literals
+
+# Common imports
+import numpy as np
+import os
+
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+
+Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
+
+deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
+deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
+deep_tree_clf1.fit(Xm, ym)
+deep_tree_clf2.fit(Xm, ym)
+
+
+def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if not iris:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    if plot_training:
+        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
+        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
+        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
+        plt.axis(axes)
+    if iris:
+        plt.xlabel("Petal length", fontsize=14)
+        plt.ylabel("Petal width", fontsize=14)
+    else:
+        plt.xlabel(r"$x_1$", fontsize=18)
+        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+    if legend:
+        plt.legend(loc="lower right", fontsize=14)
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("No restrictions", fontsize=16)
+plt.subplot(122)
+plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs047.html b/doc/pub/week44/html/._week44-bs047.html new file mode 100644 index 000000000..b8f350c52 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs047.html @@ -0,0 +1,405 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Playing around with regions

+ + +
+
+
+
+
+
np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+
+angle = np.pi/4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs048.html b/doc/pub/week44/html/._week44-bs048.html new file mode 100644 index 000000000..7125e3630 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs048.html @@ -0,0 +1,414 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Regression trees

+ + +
+
+
+
+
+
# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs049.html b/doc/pub/week44/html/._week44-bs049.html new file mode 100644 index 000000000..32b09fe16 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs049.html @@ -0,0 +1,470 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + +
+
+

 

 

 

+ + +

Final regressor code

+ + +
+
+
+
+
+
from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+    y_pred = tree_reg.predict(x1)
+    plt.axis(axes)
+    plt.xlabel("$x_1$", fontsize=18)
+    if ylabel:
+        plt.ylabel(ylabel, fontsize=18, rotation=0)
+    plt.plot(X, y, "b.")
+    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs050.html b/doc/pub/week44/html/._week44-bs050.html new file mode 100644 index 000000000..73ee729ef --- /dev/null +++ b/doc/pub/week44/html/._week44-bs050.html @@ -0,0 +1,372 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + +
+
+

 

 

 

+ + +

Pros and cons of trees, pros

+ +
    +
  • White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
  • +
  • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
  • +
  • No feature normalization needed
  • +
  • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
  • +
  • Can model nonlinear relationships
  • +
  • Can model interactions between the different descriptive features
  • +
  • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
  • +
+

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs051.html b/doc/pub/week44/html/._week44-bs051.html new file mode 100644 index 000000000..10b2b7a95 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs051.html @@ -0,0 +1,375 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Disadvantages

+ +
    +
  • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
  • +
  • If continuous features are used the tree may become quite large and hence less interpretable
  • +
  • Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
  • +
  • Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
  • +
  • Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
  • +
  • If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
  • +
  • Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
  • +
+

However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs052.html b/doc/pub/week44/html/._week44-bs052.html new file mode 100644 index 000000000..185c3315b --- /dev/null +++ b/doc/pub/week44/html/._week44-bs052.html @@ -0,0 +1,381 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

+ +

As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? +

+ +

This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct +forests and jungles of trees, homogeneous ones or heterogenous +ones. These methods are recognized by different names which we will +try to explain here. These are +

+ +
    +
  1. Voting classifiers
  2. +
  3. Bagging and Pasting
  4. +
  5. Random forests
  6. +
  7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
  8. +
+

We discuss these methods here.

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs053.html b/doc/pub/week44/html/._week44-bs053.html new file mode 100644 index 000000000..2ffa01b53 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs053.html @@ -0,0 +1,365 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

An Overview of Ensemble Methods

+ +

+
+

+
+

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs054.html b/doc/pub/week44/html/._week44-bs054.html new file mode 100644 index 000000000..12d0d51e3 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs054.html @@ -0,0 +1,372 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Bagging

+ +

The plain decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of \( n \) to \( p \) is moderately large. +

+ +

Bootstrap aggregation, or just bagging, is a +general-purpose procedure for reducing the variance of a statistical +learning method. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs055.html b/doc/pub/week44/html/._week44-bs055.html new file mode 100644 index 000000000..afd9657d8 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs055.html @@ -0,0 +1,381 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

More bagging

+ +

Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. +

+ +

However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all \( B \) possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all \( B \) trees. +

+ +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs056.html b/doc/pub/week44/html/._week44-bs056.html new file mode 100644 index 000000000..073f5adcc --- /dev/null +++ b/doc/pub/week44/html/._week44-bs056.html @@ -0,0 +1,391 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Simple Voting Example, head or tail

+ + +
+
+
+
+
+
heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs057.html b/doc/pub/week44/html/._week44-bs057.html new file mode 100644 index 000000000..495e778f9 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs057.html @@ -0,0 +1,420 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Using the Voting Classifier

+ + +
+
+
+
+
+
from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs058.html b/doc/pub/week44/html/._week44-bs058.html new file mode 100644 index 000000000..f37d2adc5 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs058.html @@ -0,0 +1,472 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +

Please, not the moons again! Voting and Bagging

+ + + +
+
+
+
+
+
from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+voting_clf.fit(X_train, y_train)
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs059.html b/doc/pub/week44/html/._week44-bs059.html new file mode 100644 index 000000000..0532c8602 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs059.html @@ -0,0 +1,474 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + +
+
+

 

 

 

+ + +

Bagging Examples

+ + + +
+
+
+
+
+
from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(random_state=42), n_estimators=500,
+    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if contour:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+    plt.axis(axes)
+    plt.xlabel(r"$x_1$", fontsize=18)
+    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+save_fig("baggingtree")
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/._week44-bs060.html b/doc/pub/week44/html/._week44-bs060.html new file mode 100644 index 000000000..ed29a2bcc --- /dev/null +++ b/doc/pub/week44/html/._week44-bs060.html @@ -0,0 +1,434 @@ + + + + + + + +Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees + + + + + + + + + + + + + + + + + + + +
+
+

 

 

 

+ + +

Making your own Bootstrap: Changing the Level of the Decision Tree

+ +

Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). +

+ + +
+
+
+
+
+
import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3) 
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+    model = DecisionTreeRegressor(max_depth=degree) 
+    y_pred = np.empty((y_test.shape[0], n_boostraps))
+    for i in range(n_boostraps):
+        x_, y_ = resample(X_train_scaled, y_train)
+        model.fit(x_, y_)
+        y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+    print('Polynomial degree:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+ 
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)
+print(mse_simpletree)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +

+ +

+ +
+ + + + +
+ +
+ + + diff --git a/doc/pub/week44/html/week44-reveal.html b/doc/pub/week44/html/week44-reveal.html index e1bc3ce9c..66ce7fa27 100644 --- a/doc/pub/week44/html/week44-reveal.html +++ b/doc/pub/week44/html/week44-reveal.html @@ -265,8 +265,10 @@ These will be discussed in more detail later. The \( k \)-means algorithm is a different categories, or clusters. We label each cluster by an integer

-$$ k\in\{1, \cdots, K \}$. +

 
+$$ k\in\{1, \cdots, K \}. $$ +

 

In the basic k-means algorithm each point is assigned to only one cluster \( k \), and these assignments are non-injective i.e. many-to-one. We @@ -380,7 +382,7 @@ $$

The \( k \)-means clustering algorithm goes as follows

    -

  1. For a given cluster assignment \( C \), and \( k \) cluster means \( \left{m_1, \cdots, m_k\right} \). We minimize the total cluster variance with respect to the cluster means \( \{m_k\} \) yielding the means of the currently assigned clusters.
  2. +

  3. For a given cluster assignment \( C \), and \( k \) cluster means \( \left\{m_1, \cdots, m_k\right\} \). We minimize the total cluster variance with respect to the cluster means \( \{m_k\} \) yielding the means of the currently assigned clusters.
  4. Given a current set of \( k \) means \( \{m_k\} \) the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is

     
    $$C(i) = \underset{1\leq k\leq K}{\mathrm{argmin}} ||\boldsymbol{x_i} - \boldsymbol{m_k}||^2$$

     

  5. diff --git a/doc/pub/week44/html/week44-solarized.html b/doc/pub/week44/html/week44-solarized.html index 6e88a471b..cb5980de9 100644 --- a/doc/pub/week44/html/week44-solarized.html +++ b/doc/pub/week44/html/week44-solarized.html @@ -345,7 +345,7 @@ These will be discussed in more detail later. The \( k \)-means algorithm is a different categories, or clusters. We label each cluster by an integer

    -$$ k\in\{1, \cdots, K \}$. +$$ k\in\{1, \cdots, K \}. $$

    In the basic k-means algorithm each point is assigned to only @@ -445,7 +445,7 @@ $$

    The \( k \)-means clustering algorithm goes as follows

      -
    1. For a given cluster assignment \( C \), and \( k \) cluster means \( \left{m_1, \cdots, m_k\right} \). We minimize the total cluster variance with respect to the cluster means \( \{m_k\} \) yielding the means of the currently assigned clusters.
    2. +
    3. For a given cluster assignment \( C \), and \( k \) cluster means \( \left\{m_1, \cdots, m_k\right\} \). We minimize the total cluster variance with respect to the cluster means \( \{m_k\} \) yielding the means of the currently assigned clusters.
    4. Given a current set of \( k \) means \( \{m_k\} \) the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is $$C(i) = \underset{1\leq k\leq K}{\mathrm{argmin}} ||\boldsymbol{x_i} - \boldsymbol{m_k}||^2$$
    5. Steps 1 and 2 are repeated until the assignments do not change.
    diff --git a/doc/pub/week44/html/week44.html b/doc/pub/week44/html/week44.html index 0a19a5c5c..f5d3a3a00 100644 --- a/doc/pub/week44/html/week44.html +++ b/doc/pub/week44/html/week44.html @@ -422,7 +422,7 @@ These will be discussed in more detail later. The \( k \)-means algorithm is a different categories, or clusters. We label each cluster by an integer

    -$$ k\in\{1, \cdots, K \}$. +$$ k\in\{1, \cdots, K \}. $$

    In the basic k-means algorithm each point is assigned to only @@ -522,7 +522,7 @@ $$

    The \( k \)-means clustering algorithm goes as follows

      -
    1. For a given cluster assignment \( C \), and \( k \) cluster means \( \left{m_1, \cdots, m_k\right} \). We minimize the total cluster variance with respect to the cluster means \( \{m_k\} \) yielding the means of the currently assigned clusters.
    2. +
    3. For a given cluster assignment \( C \), and \( k \) cluster means \( \left\{m_1, \cdots, m_k\right\} \). We minimize the total cluster variance with respect to the cluster means \( \{m_k\} \) yielding the means of the currently assigned clusters.
    4. Given a current set of \( k \) means \( \{m_k\} \) the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is $$C(i) = \underset{1\leq k\leq K}{\mathrm{argmin}} ||\boldsymbol{x_i} - \boldsymbol{m_k}||^2$$
    5. Steps 1 and 2 are repeated until the assignments do not change.
    diff --git a/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz b/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz index 415c0c59f..09995979a 100644 Binary files a/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz and b/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz differ diff --git a/doc/pub/week44/ipynb/week44.ipynb b/doc/pub/week44/ipynb/week44.ipynb index 4f6d3e187..fc778a559 100644 --- a/doc/pub/week44/ipynb/week44.ipynb +++ b/doc/pub/week44/ipynb/week44.ipynb @@ -2,8 +2,10 @@ "cells": [ { "cell_type": "markdown", - "id": "bf6a66bd", - "metadata": {}, + "id": "85e109c2", + "metadata": { + "editable": true + }, "source": [ "\n", @@ -12,8 +14,10 @@ }, { "cell_type": "markdown", - "id": "7af436e6", - "metadata": {}, + "id": "997ae52f", + "metadata": { + "editable": true + }, "source": [ "# Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees\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", @@ -25,8 +29,10 @@ }, { "cell_type": "markdown", - "id": "98ddd7e2", - "metadata": {}, + "id": "9f3ea2e4", + "metadata": { + "editable": true + }, "source": [ "## Overview of week 44\n", "\n", @@ -51,8 +57,10 @@ }, { "cell_type": "markdown", - "id": "70dec958", - "metadata": {}, + "id": "70b35bee", + "metadata": { + "editable": true + }, "source": [ "## Thursday, Principal Component Analysis\n", "\n", @@ -62,8 +70,10 @@ }, { "cell_type": "markdown", - "id": "99b145fd", - "metadata": {}, + "id": "4986992f", + "metadata": { + "editable": true + }, "source": [ "## Thursday: Clustering and Unsupervised Learning\n", "\n", @@ -80,8 +90,10 @@ }, { "cell_type": "markdown", - "id": "ac970c3d", - "metadata": {}, + "id": "cbd248fe", + "metadata": { + "editable": true + }, "source": [ "## Basic Idea of the $k$-means Clustering Algorithm\n", "\n", @@ -94,8 +106,10 @@ }, { "cell_type": "markdown", - "id": "b70e75a5", - "metadata": {}, + "id": "5b23b9fc", + "metadata": { + "editable": true + }, "source": [ "## The $k$-means Algorithm\n", "\n", @@ -105,18 +119,22 @@ }, { "cell_type": "markdown", - "id": "ecee5684", - "metadata": {}, + "id": "4d7f3d96", + "metadata": { + "editable": true + }, "source": [ "$$\n", - "k\\in\\{1, \\cdots, K \\}$.\n", + "k\\in\\{1, \\cdots, K \\}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "64b830ad", - "metadata": {}, + "id": "bc72513a", + "metadata": { + "editable": true + }, "source": [ "In the basic k-means algorithm each point is assigned to only\n", "one cluster $k$, and these assignments are *non-injective* i.e. many-to-one. We\n", @@ -135,8 +153,10 @@ }, { "cell_type": "markdown", - "id": "99c98635", - "metadata": {}, + "id": "387dce2f", + "metadata": { + "editable": true + }, "source": [ "## Basic Math of the $k$-means Algorithm\n", "\n", @@ -145,8 +165,10 @@ }, { "cell_type": "markdown", - "id": "785493cb", - "metadata": {}, + "id": "d61be5eb", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -160,8 +182,10 @@ }, { "cell_type": "markdown", - "id": "2a163123", - "metadata": {}, + "id": "106da55a", + "metadata": { + "editable": true + }, "source": [ "which we wish to group into $K < n$ clusters. For our dissimilarity measure we\n", "use the *squared Euclidean distance*" @@ -169,8 +193,10 @@ }, { "cell_type": "markdown", - "id": "7116fb2f", - "metadata": {}, + "id": "7f95f3d9", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -185,8 +211,10 @@ }, { "cell_type": "markdown", - "id": "fc62645d", - "metadata": {}, + "id": "c01e5195", + "metadata": { + "editable": true + }, "source": [ "## Within Cluster Point Scatter\n", "\n", @@ -197,8 +225,10 @@ }, { "cell_type": "markdown", - "id": "383635b6", - "metadata": {}, + "id": "5ecbd352", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -214,8 +244,10 @@ }, { "cell_type": "markdown", - "id": "e085595c", - "metadata": {}, + "id": "b6ce66f7", + "metadata": { + "editable": true + }, "source": [ "where $\\boldsymbol{\\overline{x_k}}$ is the mean vector associated with the $k$-th\n", "cluster, and $N_k = \\sum_{i=1}^nI(C(i) = k)$, where the $I()$ notation is\n", @@ -229,8 +261,10 @@ }, { "cell_type": "markdown", - "id": "1637663e", - "metadata": {}, + "id": "df4f5200", + "metadata": { + "editable": true + }, "source": [ "## More Details\n", "\n", @@ -239,8 +273,10 @@ }, { "cell_type": "markdown", - "id": "9c0e866b", - "metadata": {}, + "id": "a78f03ea", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -258,8 +294,10 @@ }, { "cell_type": "markdown", - "id": "06ad9c98", - "metadata": {}, + "id": "9300f66a", + "metadata": { + "editable": true + }, "source": [ "This is a quantity that is conserved throughout the $k$-means algorithm. It can\n", "be thought of as the total amount of information in the data, and it is composed\n", @@ -270,8 +308,10 @@ }, { "cell_type": "markdown", - "id": "1ab25d0c", - "metadata": {}, + "id": "573f059d", + "metadata": { + "editable": true + }, "source": [ "## Total Cluster Variance\n", "Given a cluster mean $\\boldsymbol{m_k}$ we define the **total cluster variance**" @@ -279,8 +319,10 @@ }, { "cell_type": "markdown", - "id": "0bbf889e", - "metadata": {}, + "id": "5cebf803", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -294,22 +336,26 @@ }, { "cell_type": "markdown", - "id": "92571f86", - "metadata": {}, + "id": "f181fbcb", + "metadata": { + "editable": true + }, "source": [ "Now we have all the pieces necessary to formally revisit the $k$-means algorithm." ] }, { "cell_type": "markdown", - "id": "ce2da1a4", - "metadata": {}, + "id": "ab0c8e0c", + "metadata": { + "editable": true + }, "source": [ "## The $k$-means Clustering Algorithm\n", "\n", "The $k$-means clustering algorithm goes as follows \n", "\n", - "1. For a given cluster assignment $C$, and $k$ cluster means $\\left{m_1, \\cdots, m_k\\right}$. We minimize the total cluster variance with respect to the cluster means $\\{m_k\\}$ yielding the means of the currently assigned clusters.\n", + "1. For a given cluster assignment $C$, and $k$ cluster means $\\left\\{m_1, \\cdots, m_k\\right\\}$. We minimize the total cluster variance with respect to the cluster means $\\{m_k\\}$ yielding the means of the currently assigned clusters.\n", "\n", "2. Given a current set of $k$ means $\\{m_k\\}$ the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is $$C(i) = \\underset{1\\leq k\\leq K}{\\mathrm{argmin}} ||\\boldsymbol{x_i} - \\boldsymbol{m_k}||^2$$\n", "\n", @@ -318,8 +364,10 @@ }, { "cell_type": "markdown", - "id": "bc6b373b", - "metadata": {}, + "id": "36766d46", + "metadata": { + "editable": true + }, "source": [ "## Summarizing\n", "\n", @@ -336,8 +384,10 @@ }, { "cell_type": "markdown", - "id": "918ffb62", - "metadata": {}, + "id": "48ecb4ef", + "metadata": { + "editable": true + }, "source": [ "## Writing our own Code, the Data Set\n", "\n", @@ -354,21 +404,12 @@ { "cell_type": "code", "execution_count": 1, - "id": "f3e96eb4", - "metadata": {}, - "outputs": [ - { - "ename": "ModuleNotFoundError", - "evalue": "No module named 'tensorflow'", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtime\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mtensorflow\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mtf\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mmatplotlib\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mimage\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmatplotlib\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpyplot\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'tensorflow'" - ] - } - ], + "id": "a99e4ba2", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "%matplotlib inline\n", "\n", @@ -385,8 +426,10 @@ }, { "cell_type": "markdown", - "id": "2c23e020", - "metadata": {}, + "id": "1d966708", + "metadata": { + "editable": true + }, "source": [ "Next we define functions, for ease of use later, to generate Gaussians and to\n", "set up our toy data set." @@ -395,22 +438,12 @@ { "cell_type": "code", "execution_count": 2, - "id": "6d00f953", - "metadata": {}, - "outputs": [ - { - "ename": "NameError", - "evalue": "name 'plt' is not defined", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 47\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 48\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 49\u001b[0;31m \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mgenerate_simple_clustering_dataset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;32m\u001b[0m in \u001b[0;36mgenerate_simple_clustering_dataset\u001b[0;34m(dim, n_points, plotting, return_data)\u001b[0m\n\u001b[1;32m 37\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 38\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mplotting\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 39\u001b[0;31m \u001b[0mfig\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0max\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msubplots\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 40\u001b[0m \u001b[0max\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mscatter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0malpha\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0.2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 41\u001b[0m \u001b[0max\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_title\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Toy Model Dataset'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mNameError\u001b[0m: name 'plt' is not defined" - ] - } - ], + "id": "4004465b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "def gaussian_points(dim=2, n_points=1000, mean_vector=np.array([0, 0]),\n", " sample_variance=1):\n", @@ -465,8 +498,10 @@ }, { "cell_type": "markdown", - "id": "a12ceb78", - "metadata": {}, + "id": "a1804507", + "metadata": { + "editable": true + }, "source": [ "## Implementing the $k$-means Algorithm\n", "\n", @@ -477,8 +512,11 @@ { "cell_type": "code", "execution_count": 3, - "id": "576200d6", - "metadata": {}, + "id": "feefc00a", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\n", @@ -519,8 +557,10 @@ }, { "cell_type": "markdown", - "id": "1df6f1a6", - "metadata": {}, + "id": "3273157d", + "metadata": { + "editable": true + }, "source": [ "## Plotting" ] @@ -528,8 +568,11 @@ { "cell_type": "code", "execution_count": 4, - "id": "2cb7e75b", - "metadata": {}, + "id": "9b794509", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "fig = plt.figure()\n", @@ -549,8 +592,10 @@ }, { "cell_type": "markdown", - "id": "5fa3b389", - "metadata": {}, + "id": "9ccd5ec4", + "metadata": { + "editable": true + }, "source": [ "So what do we have so far? We have 'picked' $k$ centroids at random from our\n", "data points. There are other ways of more intelligently choosing their\n", @@ -566,8 +611,10 @@ }, { "cell_type": "markdown", - "id": "6a0d93e3", - "metadata": {}, + "id": "1e9c9d27", + "metadata": { + "editable": true + }, "source": [ "## Continuing" ] @@ -575,8 +622,11 @@ { "cell_type": "code", "execution_count": 5, - "id": "7befecf7", - "metadata": {}, + "id": "17cb29a0", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\n", @@ -628,8 +678,10 @@ }, { "cell_type": "markdown", - "id": "6db65597", - "metadata": {}, + "id": "67291685", + "metadata": { + "editable": true + }, "source": [ "## Wrapping it up\n", "We now have a simple , un-optimized $k$-means\n", @@ -639,8 +691,11 @@ { "cell_type": "code", "execution_count": 6, - "id": "c7f59758", - "metadata": {}, + "id": "b2f485e2", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "fig = plt.figure()\n", @@ -661,8 +716,11 @@ { "cell_type": "code", "execution_count": 7, - "id": "6434c06d", - "metadata": {}, + "id": "8d664f08", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "def naive_kmeans(data, n_clusters=4, max_iterations=100, tolerance=1e-8):\n", @@ -737,8 +795,10 @@ }, { "cell_type": "markdown", - "id": "2e3a547a", - "metadata": {}, + "id": "958a7336", + "metadata": { + "editable": true + }, "source": [ "## Decision trees, overarching aims\n", "\n", @@ -766,8 +826,10 @@ }, { "cell_type": "markdown", - "id": "8026fa4f", - "metadata": {}, + "id": "ef336087", + "metadata": { + "editable": true + }, "source": [ "## Basics of a tree\n", "\n", @@ -784,8 +846,10 @@ }, { "cell_type": "markdown", - "id": "9e1373c9", - "metadata": {}, + "id": "aa5855be", + "metadata": { + "editable": true + }, "source": [ "## A Sketch of a Tree, Regression problem\n", "\n", @@ -794,8 +858,10 @@ }, { "cell_type": "markdown", - "id": "bbc6c594", - "metadata": {}, + "id": "0862af67", + "metadata": { + "editable": true + }, "source": [ "## A Sketch of a Tree, Classification problem\n", "\n", @@ -804,8 +870,10 @@ }, { "cell_type": "markdown", - "id": "30e044f6", - "metadata": {}, + "id": "a23ccf3a", + "metadata": { + "editable": true + }, "source": [ "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n", "\n", @@ -820,8 +888,10 @@ }, { "cell_type": "markdown", - "id": "14eb6577", - "metadata": {}, + "id": "20f7c33d", + "metadata": { + "editable": true + }, "source": [ "## General Features\n", "\n", @@ -841,8 +911,10 @@ }, { "cell_type": "markdown", - "id": "52d0f1f1", - "metadata": {}, + "id": "64f417e8", + "metadata": { + "editable": true + }, "source": [ "## How do we set it up?\n", "\n", @@ -862,8 +934,10 @@ }, { "cell_type": "markdown", - "id": "f4fcf249", - "metadata": {}, + "id": "7a07ba8d", + "metadata": { + "editable": true + }, "source": [ "## Decision trees and Regression" ] @@ -871,8 +945,11 @@ { "cell_type": "code", "execution_count": 8, - "id": "b81178c5", - "metadata": {}, + "id": "738cd0d6", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import numpy as np\n", @@ -967,8 +1044,10 @@ }, { "cell_type": "markdown", - "id": "f1407bd2", - "metadata": {}, + "id": "54c00feb", + "metadata": { + "editable": true + }, "source": [ "## Building a tree, regression\n", "\n", @@ -987,8 +1066,10 @@ }, { "cell_type": "markdown", - "id": "e159978f", - "metadata": {}, + "id": "3388a527", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sum_{j=1}^J\\sum_{i\\in R_j}(y_i-\\overline{y}_{R_j})^2,\n", @@ -997,8 +1078,10 @@ }, { "cell_type": "markdown", - "id": "ac02d4ca", - "metadata": {}, + "id": "c75bae38", + "metadata": { + "editable": true + }, "source": [ "where $\\overline{y}_{R_j}$ is the mean response for the training observations \n", "within box $j$." @@ -1006,8 +1089,10 @@ }, { "cell_type": "markdown", - "id": "d0fa609a", - "metadata": {}, + "id": "fb7ced6c", + "metadata": { + "editable": true + }, "source": [ "## A top-down approach, recursive binary splitting\n", "\n", @@ -1026,8 +1111,10 @@ }, { "cell_type": "markdown", - "id": "e823cca8", - "metadata": {}, + "id": "b141a34d", + "metadata": { + "editable": true + }, "source": [ "## Making a tree\n", "\n", @@ -1037,8 +1124,10 @@ }, { "cell_type": "markdown", - "id": "a8c7a43a", - "metadata": {}, + "id": "6655cb56", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\left\\{X\\vert x_j < s\\right\\},\n", @@ -1047,16 +1136,20 @@ }, { "cell_type": "markdown", - "id": "13fd8d8b", - "metadata": {}, + "id": "c78453e4", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "id": "fd034108", - "metadata": {}, + "id": "35e51ac6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\left\\{X\\vert x_j \\geq s\\right\\},\n", @@ -1065,16 +1158,20 @@ }, { "cell_type": "markdown", - "id": "c6913579", - "metadata": {}, + "id": "32772194", + "metadata": { + "editable": true + }, "source": [ "so that we obtain the lowest MSE, that is" ] }, { "cell_type": "markdown", - "id": "c9259557", - "metadata": {}, + "id": "1eccaa9d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sum_{i:x_i\\in R_j}(y_i-\\overline{y}_{R_1})^2+\\sum_{i:x_i\\in R_2}(y_i-\\overline{y}_{R_2})^2,\n", @@ -1083,8 +1180,10 @@ }, { "cell_type": "markdown", - "id": "292547d3", - "metadata": {}, + "id": "5d8bed8c", + "metadata": { + "editable": true + }, "source": [ "which we want to minimize by considering all predictors\n", "$x_1,x_2,\\dots,x_p$. We consider also all possible values of $s$ for\n", @@ -1114,8 +1213,10 @@ }, { "cell_type": "markdown", - "id": "01e8457e", - "metadata": {}, + "id": "170a4923", + "metadata": { + "editable": true + }, "source": [ "## Pruning the tree\n", "\n", @@ -1136,8 +1237,10 @@ }, { "cell_type": "markdown", - "id": "08d0bb4a", - "metadata": {}, + "id": "91d687cb", + "metadata": { + "editable": true + }, "source": [ "## Cost complexity pruning\n", "\n", @@ -1146,8 +1249,10 @@ }, { "cell_type": "markdown", - "id": "28bb2119", - "metadata": {}, + "id": "a688ea82", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sum_{m=1}^{\\overline{T}}\\sum_{i:x_i\\in R_m}(y_i-\\overline{y}_{R_m})^2+\\alpha\\overline{T},\n", @@ -1156,8 +1261,10 @@ }, { "cell_type": "markdown", - "id": "015793a4", - "metadata": {}, + "id": "39db6909", + "metadata": { + "editable": true + }, "source": [ "is as small as possible. Here $\\overline{T}$ is \n", "the number of terminal nodes of the tree $T$ , $R_m$ is the\n", @@ -1182,8 +1289,10 @@ }, { "cell_type": "markdown", - "id": "92c92e1f", - "metadata": {}, + "id": "148a433c", + "metadata": { + "editable": true + }, "source": [ "## Schematic Regression Procedure\n", "\n", @@ -1206,8 +1315,10 @@ }, { "cell_type": "markdown", - "id": "44631e32", - "metadata": {}, + "id": "d61e1a8d", + "metadata": { + "editable": true + }, "source": [ "## A Classification Tree\n", "\n", @@ -1227,8 +1338,10 @@ }, { "cell_type": "markdown", - "id": "ff27eba7", - "metadata": {}, + "id": "15bc3e13", + "metadata": { + "editable": true + }, "source": [ "## Growing a classification tree\n", "\n", @@ -1252,8 +1365,10 @@ }, { "cell_type": "markdown", - "id": "ed03abb4", - "metadata": {}, + "id": "1f67f409", + "metadata": { + "editable": true + }, "source": [ "## Classification tree, how to split nodes\n", "\n", @@ -1269,8 +1384,10 @@ }, { "cell_type": "markdown", - "id": "2c8d81e1", - "metadata": {}, + "id": "8784025f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i=k).\n", @@ -1279,8 +1396,10 @@ }, { "cell_type": "markdown", - "id": "3c3785a2", - "metadata": {}, + "id": "2c23874f", + "metadata": { + "editable": true + }, "source": [ "We let $p_{mk}$ represent the majority class of observations in region\n", "$m$. The three most common ways of splitting a node are given by\n", @@ -1290,8 +1409,10 @@ }, { "cell_type": "markdown", - "id": "b479e704", - "metadata": {}, + "id": "b0e95531", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n", @@ -1300,16 +1421,20 @@ }, { "cell_type": "markdown", - "id": "a7edcc9e", - "metadata": {}, + "id": "4417308c", + "metadata": { + "editable": true + }, "source": [ "* Gini index $g$" ] }, { "cell_type": "markdown", - "id": "9f60e695", - "metadata": {}, + "id": "88e2a431", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g = \\sum_{k=1}^K p_{mk}(1-p_{mk}).\n", @@ -1318,16 +1443,20 @@ }, { "cell_type": "markdown", - "id": "a5260cc5", - "metadata": {}, + "id": "55b50139", + "metadata": { + "editable": true + }, "source": [ "* Information entropy or just entropy $s$" ] }, { "cell_type": "markdown", - "id": "9c5a41b3", - "metadata": {}, + "id": "17967fe2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n", @@ -1336,8 +1465,10 @@ }, { "cell_type": "markdown", - "id": "7d290873", - "metadata": {}, + "id": "aff00f4d", + "metadata": { + "editable": true + }, "source": [ "## Visualizing the Tree, Classification" ] @@ -1345,8 +1476,11 @@ { "cell_type": "code", "execution_count": 9, - "id": "acf9d5e4", - "metadata": {}, + "id": "4a6eda9b", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import os\n", @@ -1386,8 +1520,10 @@ }, { "cell_type": "markdown", - "id": "ba61689c", - "metadata": {}, + "id": "e6d89821", + "metadata": { + "editable": true + }, "source": [ "## Visualizing the Tree, The Moons" ] @@ -1395,8 +1531,11 @@ { "cell_type": "code", "execution_count": 10, - "id": "52e2eeb3", - "metadata": {}, + "id": "bb651d2f", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Common imports\n", @@ -1427,8 +1566,10 @@ }, { "cell_type": "markdown", - "id": "ff909dae", - "metadata": {}, + "id": "d5ce345d", + "metadata": { + "editable": true + }, "source": [ "## Other ways of visualizing the trees\n", "\n", @@ -1438,8 +1579,11 @@ { "cell_type": "code", "execution_count": 11, - "id": "87ee9247", - "metadata": {}, + "id": "9bf8d6bd", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.datasets import load_iris\n", @@ -1453,8 +1597,10 @@ }, { "cell_type": "markdown", - "id": "a6f7e44c", - "metadata": {}, + "id": "2e881320", + "metadata": { + "editable": true + }, "source": [ "## Printing out as text\n", "\n", @@ -1465,8 +1611,11 @@ { "cell_type": "code", "execution_count": 12, - "id": "a7f81bcd", - "metadata": {}, + "id": "1bfc792f", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.datasets import load_iris\n", @@ -1481,8 +1630,10 @@ }, { "cell_type": "markdown", - "id": "e4f6ba35", - "metadata": {}, + "id": "a133b652", + "metadata": { + "editable": true + }, "source": [ "## Algorithms for Setting up Decision Trees\n", "\n", @@ -1499,8 +1650,10 @@ }, { "cell_type": "markdown", - "id": "4c79a12f", - "metadata": {}, + "id": "66402566", + "metadata": { + "editable": true + }, "source": [ "## The CART algorithm for Classification\n", "\n", @@ -1514,8 +1667,10 @@ }, { "cell_type": "markdown", - "id": "7825f2c9", - "metadata": {}, + "id": "25e477f5", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n", @@ -1524,8 +1679,10 @@ }, { "cell_type": "markdown", - "id": "0b432770", - "metadata": {}, + "id": "12aacdcb", + "metadata": { + "editable": true + }, "source": [ "where $G_{\\mathrm{left/right}}$ measures the impurity of the left/right subset and $m_{\\mathrm{left/right}}$\n", " is the number of instances in the left/right subset\n", @@ -1539,8 +1696,10 @@ }, { "cell_type": "markdown", - "id": "ce71bcb8", - "metadata": {}, + "id": "86507e7f", + "metadata": { + "editable": true + }, "source": [ "## The CART algorithm for Regression\n", "\n", @@ -1550,8 +1709,10 @@ }, { "cell_type": "markdown", - "id": "e54a3968", - "metadata": {}, + "id": "1b58216b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}\\mathrm{MSE}_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}\\mathrm{MSE}_{\\mathrm{right}}.\n", @@ -1560,16 +1721,20 @@ }, { "cell_type": "markdown", - "id": "ea62e615", - "metadata": {}, + "id": "894b1d8e", + "metadata": { + "editable": true + }, "source": [ "Here the MSE for a specific node is defined as" ] }, { "cell_type": "markdown", - "id": "8a20f4b4", - "metadata": {}, + "id": "d38635b2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n", @@ -1578,16 +1743,20 @@ }, { "cell_type": "markdown", - "id": "9be4c8a4", - "metadata": {}, + "id": "79111829", + "metadata": { + "editable": true + }, "source": [ "with" ] }, { "cell_type": "markdown", - "id": "c4f7f184", - "metadata": {}, + "id": "84738692", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n", @@ -1596,8 +1765,10 @@ }, { "cell_type": "markdown", - "id": "95d81e34", - "metadata": {}, + "id": "3d178493", + "metadata": { + "editable": true + }, "source": [ "the mean value of all observations in a specific node.\n", "\n", @@ -1607,8 +1778,10 @@ }, { "cell_type": "markdown", - "id": "e00e4c74", - "metadata": {}, + "id": "37bc952d", + "metadata": { + "editable": true + }, "source": [ "## Computing the Gini index\n", "\n", @@ -1649,8 +1822,10 @@ }, { "cell_type": "markdown", - "id": "6f87ddeb", - "metadata": {}, + "id": "f4a62ac9", + "metadata": { + "editable": true + }, "source": [ "## Simple Python Code to read in Data and perform Classification" ] @@ -1658,8 +1833,11 @@ { "cell_type": "code", "execution_count": 13, - "id": "9a2a4a21", - "metadata": {}, + "id": "4d122b4e", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Common imports\n", @@ -1733,8 +1911,10 @@ }, { "cell_type": "markdown", - "id": "167cae6a", - "metadata": {}, + "id": "29df02ef", + "metadata": { + "editable": true + }, "source": [ "## Computing the Gini Factor\n", "\n", @@ -1749,8 +1929,11 @@ { "cell_type": "code", "execution_count": 14, - "id": "fd4d3d1d", - "metadata": {}, + "id": "a8c89ffd", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Split a dataset based on an attribute and an attribute value\n", @@ -1817,8 +2000,10 @@ }, { "cell_type": "markdown", - "id": "e7637723", - "metadata": {}, + "id": "00e53a8f", + "metadata": { + "editable": true + }, "source": [ "## Entropy and the ID3 algorithm\n", "\n", @@ -1854,8 +2039,10 @@ }, { "cell_type": "markdown", - "id": "5fe05c6a", - "metadata": {}, + "id": "692ac7ef", + "metadata": { + "editable": true + }, "source": [ "## Cancer Data again now with Decision Trees and other Methods" ] @@ -1863,8 +2050,11 @@ { "cell_type": "code", "execution_count": 15, - "id": "d07cc03c", - "metadata": {}, + "id": "ccda8519", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", @@ -1912,8 +2102,10 @@ }, { "cell_type": "markdown", - "id": "ac909d39", - "metadata": {}, + "id": "62742fdf", + "metadata": { + "editable": true + }, "source": [ "## Another example, the moons again" ] @@ -1921,8 +2113,11 @@ { "cell_type": "code", "execution_count": 16, - "id": "4ec06694", - "metadata": {}, + "id": "e6d68cd4", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from __future__ import division, print_function, unicode_literals\n", @@ -1993,8 +2188,10 @@ }, { "cell_type": "markdown", - "id": "b6e84ca9", - "metadata": {}, + "id": "488fb04d", + "metadata": { + "editable": true + }, "source": [ "## Playing around with regions" ] @@ -2002,8 +2199,11 @@ { "cell_type": "code", "execution_count": 17, - "id": "3b8265d3", - "metadata": {}, + "id": "711b9e09", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "np.random.seed(6)\n", @@ -2030,8 +2230,10 @@ }, { "cell_type": "markdown", - "id": "4ac4391c", - "metadata": {}, + "id": "582d8e15", + "metadata": { + "editable": true + }, "source": [ "## Regression trees" ] @@ -2039,8 +2241,11 @@ { "cell_type": "code", "execution_count": 18, - "id": "0399291c", - "metadata": {}, + "id": "9df0fa1b", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Quadratic training set + noise\n", @@ -2054,8 +2259,11 @@ { "cell_type": "code", "execution_count": 19, - "id": "6273a4ca", - "metadata": {}, + "id": "7c10a0ff", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.tree import DecisionTreeRegressor\n", @@ -2066,8 +2274,10 @@ }, { "cell_type": "markdown", - "id": "500c38f2", - "metadata": {}, + "id": "d73ebec5", + "metadata": { + "editable": true + }, "source": [ "## Final regressor code" ] @@ -2075,8 +2285,11 @@ { "cell_type": "code", "execution_count": 20, - "id": "cff275f0", - "metadata": {}, + "id": "56113e01", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.tree import DecisionTreeRegressor\n", @@ -2122,8 +2335,11 @@ { "cell_type": "code", "execution_count": 21, - "id": "d00f1eec", - "metadata": {}, + "id": "9e6452cb", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "tree_reg1 = DecisionTreeRegressor(random_state=42)\n", @@ -2158,8 +2374,10 @@ }, { "cell_type": "markdown", - "id": "efe7595b", - "metadata": {}, + "id": "8eb7d5a6", + "metadata": { + "editable": true + }, "source": [ "## Pros and cons of trees, pros\n", "\n", @@ -2180,8 +2398,10 @@ }, { "cell_type": "markdown", - "id": "bd019bce", - "metadata": {}, + "id": "49e49c9c", + "metadata": { + "editable": true + }, "source": [ "## Disadvantages\n", "\n", @@ -2206,8 +2426,10 @@ }, { "cell_type": "markdown", - "id": "26879a96", - "metadata": {}, + "id": "008ff45b", + "metadata": { + "editable": true + }, "source": [ "## Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n", "\n", @@ -2235,8 +2457,10 @@ }, { "cell_type": "markdown", - "id": "c4186bbd", - "metadata": {}, + "id": "22684dfd", + "metadata": { + "editable": true + }, "source": [ "## An Overview of Ensemble Methods\n", "\n", @@ -2249,8 +2473,10 @@ }, { "cell_type": "markdown", - "id": "adf5117b", - "metadata": {}, + "id": "8992e26c", + "metadata": { + "editable": true + }, "source": [ "## Bagging\n", "\n", @@ -2269,8 +2495,10 @@ }, { "cell_type": "markdown", - "id": "7e7b7e57", - "metadata": {}, + "id": "672e8a35", + "metadata": { + "editable": true + }, "source": [ "## More bagging\n", "\n", @@ -2299,8 +2527,10 @@ }, { "cell_type": "markdown", - "id": "49a7dff2", - "metadata": {}, + "id": "08b98507", + "metadata": { + "editable": true + }, "source": [ "## Simple Voting Example, head or tail" ] @@ -2308,8 +2538,11 @@ { "cell_type": "code", "execution_count": 22, - "id": "0a443e4d", - "metadata": {}, + "id": "ab529435", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "heads_proba = 0.51\n", @@ -2329,8 +2562,10 @@ }, { "cell_type": "markdown", - "id": "a8ea734f", - "metadata": {}, + "id": "1a28586e", + "metadata": { + "editable": true + }, "source": [ "## Using the Voting Classifier" ] @@ -2338,8 +2573,11 @@ { "cell_type": "code", "execution_count": 23, - "id": "b292193c", - "metadata": {}, + "id": "225217c3", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", @@ -2389,8 +2627,10 @@ }, { "cell_type": "markdown", - "id": "dd8452bb", - "metadata": {}, + "id": "ba88d88c", + "metadata": { + "editable": true + }, "source": [ "## Please, not the moons again! Voting and Bagging" ] @@ -2398,8 +2638,11 @@ { "cell_type": "code", "execution_count": 24, - "id": "d8da9ef9", - "metadata": {}, + "id": "aedbb6f5", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", @@ -2425,8 +2668,11 @@ { "cell_type": "code", "execution_count": 25, - "id": "c6c0b366", - "metadata": {}, + "id": "b18bb537", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.metrics import accuracy_score\n", @@ -2440,8 +2686,11 @@ { "cell_type": "code", "execution_count": 26, - "id": "a7f6b0f8", - "metadata": {}, + "id": "9c3c4f43", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "log_clf = LogisticRegression(random_state=42)\n", @@ -2457,8 +2706,11 @@ { "cell_type": "code", "execution_count": 27, - "id": "b417ccb8", - "metadata": {}, + "id": "d301b683", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.metrics import accuracy_score\n", @@ -2471,8 +2723,10 @@ }, { "cell_type": "markdown", - "id": "3c34873d", - "metadata": {}, + "id": "1089619c", + "metadata": { + "editable": true + }, "source": [ "## Bagging Examples" ] @@ -2480,8 +2734,11 @@ { "cell_type": "code", "execution_count": 28, - "id": "7d9235a9", - "metadata": {}, + "id": "3ba4b280", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.ensemble import BaggingClassifier\n", @@ -2497,8 +2754,11 @@ { "cell_type": "code", "execution_count": 29, - "id": "fa17aa74", - "metadata": {}, + "id": "2f4e3b91", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.metrics import accuracy_score\n", @@ -2508,8 +2768,11 @@ { "cell_type": "code", "execution_count": 30, - "id": "8f65f7db", - "metadata": {}, + "id": "13cdeb37", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "tree_clf = DecisionTreeClassifier(random_state=42)\n", @@ -2521,8 +2784,11 @@ { "cell_type": "code", "execution_count": 31, - "id": "dd292ec6", - "metadata": {}, + "id": "99298dae", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from matplotlib.colors import ListedColormap\n", @@ -2556,8 +2822,10 @@ }, { "cell_type": "markdown", - "id": "b8aa3665", - "metadata": {}, + "id": "1aadc7ff", + "metadata": { + "editable": true + }, "source": [ "## Making your own Bootstrap: Changing the Level of the Decision Tree\n", "\n", @@ -2568,8 +2836,11 @@ { "cell_type": "code", "execution_count": 32, - "id": "d15e0b7c", - "metadata": {}, + "id": "9d5626b3", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\n", @@ -2633,25 +2904,7 @@ ] } ], - "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" - } - }, + "metadata": {}, "nbformat": 4, "nbformat_minor": 5 } diff --git a/doc/src/week43/make.sh b/doc/src/week43/make.sh index 4722a0918..a4c3f133a 100755 --- a/doc/src/week43/make.sh +++ b/doc/src/week43/make.sh @@ -44,7 +44,7 @@ system doconce split_html $html.html --method=space10 # Bootstrap style html=${name}-bs system doconce format html $name --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=$html $opt -system doconce split_html $html.html --method=split --pagination --nav_button=bottom +#system doconce split_html $html.html --method=split --pagination --nav_button=bottom # IPython notebook system doconce format ipynb $name $opt diff --git a/doc/src/week43/week43-bs.html b/doc/src/week43/week43-bs.html deleted file mode 100644 index 20e7af09c..000000000 --- a/doc/src/week43/week43-bs.html +++ /dev/null @@ -1,3444 +0,0 @@ - - - - - - - -Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis - - - - - - - - - - - - - - - - - - - -
-
-

 

 

 

- -
-
-

Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -
-
-
-

Nov 2, 2021

-
-
- - -
- - -

Plans for week 43

- -
    -
  • Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks
  • - -
  • Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
  • - -
- - - - - - - -

Reading Recommendations

- -
    -
  • Goodfellow et al, chapter 10 on Recurrent NNs, chapters 11 and 12 on various practicalities around deep learning are also recommended.
  • -
  • Aurelien Geron, chapter 14 on RNNs.
  • -
- -

Summary on Deep Learning Methods

- -

We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).

- -

The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images.

- - -

CNNs in brief

- -

In summary:

- -
    -
  • 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)
  • -
  • There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
  • -
  • Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
  • -
  • Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
  • -
  • Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
  • -
-

For more material on convolutional networks, we strongly recommend -the course -IN5400 – Machine Learning for Image Analysis -and the slides of CS231 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. -

- -

However, both standard feed forwards networks and CNNs perform well on data with unknown length.

- -

This is where recurrent nueral networks (RNNs) come to our rescue.

- - -

Recurrent neural networks: Overarching view

- -

Till now our focus has been, including convolutional neural networks -as well, on feedforward neural networks. The output or the activations -flow only in one direction, from the input layer to the output layer. -

- -

A recurrent neural network (RNN) looks very much like a feedforward -neural network, except that it also has connections pointing -backward. -

- -

RNNs are used to analyze time series data such as stock prices, and -tell you when to buy or sell. In autonomous driving systems, they can -anticipate car trajectories and help avoid accidents. More generally, -they can work on sequences of arbitrary lengths, rather than on -fixed-sized inputs like all the nets we have discussed so far. For -example, they can take sentences, documents, or audio samples as -input, making them extremely useful for natural language processing -systems such as automatic translation and speech-to-text. -

- - -

Set up of an RNN

- -

More to text to be added

- - -

A simple example

- - - -
-
-
-
-
-
# Start importing packages
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-import tensorflow as tf
-from tensorflow.keras import datasets, layers, models
-from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Model, Sequential 
-from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
-from tensorflow.keras import optimizers     
-from tensorflow.keras import regularizers           
-from tensorflow.keras.utils import to_categorical 
-
-
-
-# convert into dataset matrix
-def convertToMatrix(data, step):
- X, Y =[], []
- for i in range(len(data)-step):
-  d=i+step  
-  X.append(data[i:d,])
-  Y.append(data[d,])
- return np.array(X), np.array(Y)
-
-step = 4
-N = 1000    
-Tp = 800    
-
-t=np.arange(0,N)
-x=np.sin(0.02*t)+2*np.random.rand(N)
-df = pd.DataFrame(x)
-df.head()
-
-plt.plot(df)
-plt.show()
-
-values=df.values
-train,test = values[0:Tp,:], values[Tp:N,:]
-
-# add step elements into train and test
-test = np.append(test,np.repeat(test[-1,],step))
-train = np.append(train,np.repeat(train[-1,],step))
- 
-trainX,trainY =convertToMatrix(train,step)
-testX,testY =convertToMatrix(test,step)
-trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
-testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
-
-model = Sequential()
-model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu"))
-model.add(Dense(8, activation="relu")) 
-model.add(Dense(1))
-model.compile(loss='mean_squared_error', optimizer='rmsprop')
-model.summary()
-
-model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)
-trainPredict = model.predict(trainX)
-testPredict= model.predict(testX)
-predicted=np.concatenate((trainPredict,testPredict),axis=0)
-
-trainScore = model.evaluate(trainX, trainY, verbose=0)
-print(trainScore)
-
-index = df.index.values
-plt.plot(index,df)
-plt.plot(index,predicted)
-plt.axvline(df.index[Tp], c="r")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

An extrapolation example

- -

The following code provides an example of how recurrent neural -networks can be used to extrapolate to unknown values of physics data -sets. Specifically, the data sets used in this program come from -a quantum mechanical many-body calculation of energies as functions of the number of particles. -

- - - -
-
-
-
-
-
# For matrices and calculations
-import numpy as np
-# For machine learning (backend for keras)
-import tensorflow as tf
-# User-friendly machine learning library
-# Front end for TensorFlow
-import tensorflow.keras
-# Different methods from Keras needed to create an RNN
-# This is not necessary but it shortened function calls 
-# that need to be used in the code.
-from tensorflow.keras import datasets, layers, models
-from tensorflow.keras.layers import Input
-from tensorflow.keras import regularizers
-from tensorflow.keras.models import Model, Sequential
-from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-from timeit import default_timer as timer
-# For plotting
-import matplotlib.pyplot as plt
-
-
-# The data set
-datatype='VaryDimension'
-X_tot = np.arange(2, 42, 2)
-y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
-	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
-	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Formatting the Data

- -

The way the recurrent neural networks are trained in this program -differs from how machine learning algorithms are usually trained. -Typically a machine learning algorithm is trained by learning the -relationship between the x data and the y data. In this program, the -recurrent neural network will be trained to recognize the relationship -in a sequence of y values. This is type of data formatting is -typically used time series forcasting, but it can also be used in any -extrapolation (time series forecasting is just a specific type of -extrapolation along the time axis). This method of data formatting -does not use the x data and assumes that the y data are evenly spaced. -

- -

For a standard machine learning algorithm, the training data has the -form of (x,y) so the machine learning algorithm learns to assiciate a -y value with a given x value. This is useful when the test data has x -values within the same range as the training data. However, for this -application, the x values of the test data are outside of the x values -of the training data and the traditional method of training a machine -learning algorithm does not work as well. For this reason, the -recurrent neural network is trained on sequences of y values of the -form ((y1, y2), y3), so that the network is concerned with learning -the pattern of the y data and not the relation between the x and y -data. As long as the pattern of y data outside of the training region -stays relatively stable compared to what was inside the training -region, this method of training can produce accurate extrapolations to -y values far removed from the training data set. -

- - - - - - - - - - -
-
-
-
-
-
# FORMAT_DATA
-def format_data(data, length_of_sequence = 2):  
-    """
-        Inputs:
-            data(a numpy array): the data that will be the inputs to the recurrent neural
-                network
-            length_of_sequence (an int): the number of elements in one iteration of the
-                sequence patter.  For a function approximator use length_of_sequence = 2.
-        Returns:
-            rnn_input (a 3D numpy array): the input data for the recurrent neural network.  Its
-                dimensions are length of data - length of sequence, length of sequence, 
-                dimnsion of data
-            rnn_output (a numpy array): the training data for the neural network
-        Formats data to be used in a recurrent neural network.
-    """
-
-    X, Y = [], []
-    for i in range(len(data)-length_of_sequence):
-        # Get the next length_of_sequence elements
-        a = data[i:i+length_of_sequence]
-        # Get the element that immediately follows that
-        b = data[i+length_of_sequence]
-        # Reshape so that each data point is contained in its own array
-        a = np.reshape (a, (len(a), 1))
-        X.append(a)
-        Y.append(b)
-    rnn_input = np.array(X)
-    rnn_output = np.array(Y)
-
-    return rnn_input, rnn_output
-
-
-# ## Defining the Recurrent Neural Network Using Keras
-# 
-# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.
-
-def rnn(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with one hidden layer and returns the model.
-    """
-    # Number of neurons in the input and output layers
-    in_out_neurons = 1
-    # Number of neurons in the hidden layer
-    hidden_neurons = 200
-    # Define the input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons))  
-    # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to 
-    # the network immediately after the input layer
-    rnn = SimpleRNN(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN")(inp)
-    # Define the output layer as a dense neural network layer (standard neural network layer)
-    #and add it to the network immediately after the hidden layer.
-    dens = Dense(in_out_neurons,name="dense")(rnn)
-    # Create the machine learning model starting with the input layer and ending with the 
-    # output layer
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the machine learning model using the mean squared error function as the loss 
-    # function and an Adams optimizer.
-    model.compile(loss="mean_squared_error", optimizer="adam")  
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Predicting New Points With A Trained Recurrent Neural Network

- - - -
-
-
-
-
-
def test_rnn (x1, y_test, plot_min, plot_max):
-    """
-        Inputs:
-            x1 (a list or numpy array): The complete x component of the data set
-            y_test (a list or numpy array): The complete y component of the data set
-            plot_min (an int or float): the smallest x value used in the training data
-            plot_max (an int or float): the largest x valye used in the training data
-        Returns:
-            None.
-        Uses a trained recurrent neural network model to predict future points in the 
-        series.  Computes the MSE of the predicted data set from the true data set, saves
-        the predicted data set to a csv file, and plots the predicted and true data sets w
-        while also displaying the data range used for training.
-    """
-    # Add the training data as the first dim points in the predicted data array as these
-    # are known values.
-    y_pred = y_test[:dim].tolist()
-    # Generate the first input to the trained recurrent neural network using the last two 
-    # points of the training data.  Based on how the network was trained this means that it
-    # will predict the first point in the data set after the training data.  All of the 
-    # brackets are necessary for Tensorflow.
-    next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])
-    # Save the very last point in the training data set.  This will be used later.
-    last = [y_test[dim-1]]
-
-    # Iterate until the complete data set is created.
-    for i in range (dim, len(y_test)):
-        # Predict the next point in the data set using the previous two points.
-        next = model.predict(next_input)
-        # Append just the number of the predicted data set
-        y_pred.append(next[0][0])
-        # Create the input that will be used to predict the next data point in the data set.
-        next_input = np.array([[last, next[0]]], dtype=np.float64)
-        last = next
-
-    # Print the mean squared error between the known data set and the predicted data set.
-    print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())
-    # Save the predicted data set as a csv file for later use
-    name = datatype + 'Predicted'+str(dim)+'.csv'
-    np.savetxt(name, y_pred, delimiter=',')
-    # Plot the known data set and the predicted data set.  The red box represents the region that was used
-    # for the training data.
-    fig, ax = plt.subplots()
-    ax.plot(x1, y_test, label="true", linewidth=3)
-    ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4)
-    ax.legend()
-    # Created a red region to represent the points used in the training data.
-    ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')
-    plt.show()
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-model = rnn(length_of_sequences = rnn_input.shape[1])
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Other Things to Try

- -

Changing the size of the recurrent neural network and its parameters -can drastically change the results you get from the model. The below -code takes the simple recurrent neural network from above and adds a -second hidden layer, changes the number of neurons in the hidden -layer, and explicitly declares the activation function of the hidden -layers to be a sigmoid function. The loss function and optimizer can -also be changed but are kept the same as the above network. These -parameters can be tuned to provide the optimal result from the -network. For some ideas on how to improve the performance of a -recurrent neural network. -

- - - -
-
-
-
-
-
def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with two hidden layers and returns the model.
-    """
-    # Number of neurons in the input and output layers
-    in_out_neurons = 1
-    # Number of neurons in the hidden layer, increased from the first network
-    hidden_neurons = 500
-    # Define the input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons))  
-    # Create two hidden layers instead of one hidden layer.  Explicitly set the activation
-    # function to be the sigmoid function (the default value is hyperbolic tangent)
-    rnn1 = SimpleRNN(hidden_neurons, 
-                    return_sequences=True,  # This needs to be True if another hidden layer is to follow
-                    stateful = stateful, activation = 'sigmoid',
-                    name="RNN1")(inp)
-    rnn2 = SimpleRNN(hidden_neurons, 
-                    return_sequences=False, activation = 'sigmoid',
-                    stateful = stateful,
-                    name="RNN2")(rnn1)
-    # Define the output layer as a dense neural network layer (standard neural network layer)
-    #and add it to the network immediately after the hidden layer.
-    dens = Dense(in_out_neurons,name="dense")(rnn2)
-    # Create the machine learning model starting with the input layer and ending with the 
-    # output layer
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the machine learning model using the mean squared error function as the loss 
-    # function and an Adams optimizer.
-    model.compile(loss="mean_squared_error", optimizer="adam")  
-    return model
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-model = rnn_2layers(length_of_sequences = 2)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Other Types of Recurrent Neural Networks

- -

Besides a simple recurrent neural network layer, there are two other -commonly used types of recurrent neural network layers: Long Short -Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short -introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b -and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b. -

- -

The first network created below is similar to the previous network, -but it replaces the SimpleRNN layers with LSTM layers. The second -network below has two hidden layers made up of GRUs, which are -preceeded by two dense (feeddorward) neural network layers. These -dense layers "preprocess" the data before it reaches the recurrent -layers. This architecture has been shown to improve the performance -of recurrent neural networks (see the link above and also -https://arxiv.org/pdf/1807.02857.pdf. -

- - - -
-
-
-
-
-
def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.
-    """
-    # Number of neurons on the input/output layer and the number of neurons in the hidden layer
-    in_out_neurons = 1
-    hidden_neurons = 250
-    # Input Layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons)) 
-    # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)
-    rnn= LSTM(hidden_neurons, 
-                    return_sequences=True,
-                    stateful = stateful,
-                    name="RNN", use_bias=True, activation='tanh')(inp)
-    rnn1 = LSTM(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN1", use_bias=True, activation='tanh')(rnn)
-    # Output layer
-    dens = Dense(in_out_neurons,name="dense")(rnn1)
-    # Define the midel
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the model
-    model.compile(loss='mean_squared_error', optimizer='adam')  
-    # Return the model
-    return model
-
-def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with four hidden layers (two dense followed by
-        two GRU layers) and returns the model.
-    """    
-    # Number of neurons on the input/output layers and hidden layers
-    in_out_neurons = 1
-    hidden_neurons = 250
-    # Input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons)) 
-    # Hidden Dense (feedforward) layers
-    dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)
-    dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)
-    # Hidden GRU layers
-    rnn1 = GRU(hidden_neurons, 
-                    return_sequences=True,
-                    stateful = stateful,
-                    name="RNN1", use_bias=True)(dnn1)
-    rnn = GRU(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN", use_bias=True)(rnn1)
-    # Output layer
-    dens = Dense(in_out_neurons,name="dense")(rnn)
-    # Define the model
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the mdoel
-    model.compile(loss='mean_squared_error', optimizer='adam')  
-    # Return the model
-    return model
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-# Change the method name to reflect which network you want to use
-model = dnn2_gru2(length_of_sequences = 2)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)
-# 
-# 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.
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-# Reshape the data for Keras specifications
-X_train = X_train.reshape((dim, 1))
-y_train = y_train.reshape((dim, 1))
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-# Set the sequence length to 1 for regular data formatting 
-model = rnn(length_of_sequences = 1)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(X_train, y_train, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict the remaining data points
-X_pred = X_tot[dim:]
-X_pred = X_pred.reshape((len(X_pred), 1))
-y_model = model.predict(X_pred)
-y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))
-
-# Plot the known data set and the predicted data set.  The red box represents the region that was used
-# for the training data.
-fig, ax = plt.subplots()
-ax.plot(X_tot, y_tot, label="true", linewidth=3)
-ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4)
-ax.legend()
-# Created a red region to represent the points used in the training data.
-ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')
-plt.show()
-
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Generative Models

- -

Generative models describe a class of statistical models that are a contrast -to discriminative models. Informally we say that generative models can -generate new data instances while discriminative models discriminate between -different kinds of data instances. A generative model could generate new photos -of animals that look like 'real' animals while a discriminative model could tell -a dog from a cat. More formally, given a data set \( x \) and a set of labels / -targets \( y \). Generative models capture the joint probability \( p(x, y) \), or -just \( p(x) \) if there are no labels, while discriminative models capture the -conditional probability \( p(y | x) \). Discriminative models generally try to draw -boundaries in the data space (often high dimensional), while generative models -try to model how data is placed throughout the space. -

- -

Note: this material is thanks to Linus Ekstrøm.

- - -

Generative Adversarial Networks

- -

Generative Adversarial Networks are a type of unsupervised machine learning -algorithm proposed by Goodfellow et. al -in 2014 (short and good article). -

- -

The simplest formulation of -the model is based on a game theoretic approach, zero sum game, where we pit -two neural networks against one another. We define two rival networks, one -generator \( g \), and one discriminator \( d \). The generator directly produces -samples -

-$$ -\begin{equation} - x = g(z; \theta^{(g)}) -\label{_auto1} -\end{equation} -$$ - - - -

Discriminator

-

The discriminator attempts to distinguish between samples drawn from the -training data and samples drawn from the generator. In other words, it tries to -tell the difference between the fake data produced by \( g \) and the actual data -samples we want to do prediction on. The discriminator outputs a probability -value given by -

- -$$ -\begin{equation} - d(x; \theta^{(d)}) -\label{_auto2} -\end{equation} -$$ - -

indicating the probability that \( x \) is a real training example rather than a -fake sample the generator has generated. The simplest way to formulate the -learning process in a generative adversarial network is a zero-sum game, in -which a function -

- -$$ -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) -\label{_auto3} -\end{equation} -$$ - -

determines the reward for the discriminator, while the generator gets the -conjugate reward -

- -$$ -\begin{equation} - -v(\theta^{(g)}, \theta^{(d)}) -\label{_auto4} -\end{equation} -$$ - - - -

Learning Process

- -

During learning both of the networks maximize their own reward function, so that -the generator gets better and better at tricking the discriminator, while the -discriminator gets better and better at telling the difference between the fake -and real data. The generator and discriminator alternate on which one trains at -one time (i.e. for one epoch). In other words, we keep the generator constant -and train the discriminator, then we keep the discriminator constant to train -the generator and repeat. It is this back and forth dynamic which lets GANs -tackle otherwise intractable generative problems. As the generator improves with - training, the discriminator's performance gets worse because it cannot easily - tell the difference between real and fake. If the generator ends up succeeding - perfectly, the the discriminator will do no better than random guessing i.e. - 50\%. This progression in the training poses a problem for the convergence - criteria for GANs. The discriminator feedback gets less meaningful over time, - if we continue training after this point then the generator is effectively - training on junk data which can undo the learning up to that point. Therefore, - we stop training when the discriminator starts outputting \( 1/2 \) everywhere. -

- - -

More about the Learning Process

- -

At convergence we have

- -$$ -\begin{equation} - g^* = \underset{g}{\mathrm{argmin}}\hspace{2pt} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\label{_auto5} -\end{equation} -$$ - -

The default choice for \( v \) is

-$$ -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x) - + \mathbb{E}_{x\sim p_\mathrm{model}} - \log (1 - d(x)) -\label{_auto6} -\end{equation} -$$ - -

The main motivation for the design of GANs is that the learning process requires -neither approximate inference (variational autoencoders for example) nor -approximation of a partition function. In the case where -

-$$ -\begin{equation} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\label{_auto7} -\end{equation} -$$ - -

is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is -asymptotically consistent -( Seth Lloyd on QuGANs ). -

- - -

Additional References

-

This is in -general not the case and it is possible to get situations where the training -process never converges because the generator and discriminator chase one -another around in the parameter space indefinitely. A much deeper discussion on -the currently open research problem of GAN convergence is available -here. To -anyone interested in learning more about GANs it is a highly recommended read. -Direct quote: "In this best-performing formulation, the generator aims to -increase the log probability that the discriminator makes a mistake, rather than -aiming to decrease the log probability that the discriminator makes the correct -prediction." Another interesting read -

- - -

Writing Our First Generative Adversarial Network

-

Let us now move on to actually implementing a GAN in tensorflow. We will study -the performance of our GAN on the MNIST dataset. This code is based on and -adapted from the -google tutorial -

- -

First we import our libraries

- - - -
-
-
-
-
-
import os
-import time
-import numpy as np
-import tensorflow as tf
-import matplotlib.pyplot as plt
-from tensorflow.keras import layers
-from tensorflow.keras.utils import plot_model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define our hyperparameters and import our data the usual way

- - - -
-
-
-
-
-
BUFFER_SIZE = 60000
-BATCH_SIZE = 256
-EPOCHS = 30
-
-data = tf.keras.datasets.mnist.load_data()
-(train_images, train_labels), (test_images, test_labels) = data
-train_images = np.reshape(train_images, (train_images.shape[0],
-                                         28,
-                                         28,
-                                         1)).astype('float32')
-
-# we normalize between -1 and 1
-train_images = (train_images - 127.5) / 127.5
-training_dataset = tf.data.Dataset.from_tensor_slices(
-                      train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

MNIST and GANs

- -

Let's have a quick look

- - - -
-
-
-
-
-
plt.imshow(train_images[0], cmap='Greys')
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we define our two models. This is where the 'magic' happens. There are a -huge amount of possible formulations for both models. A lot of engineering and -trial and error can be done here to try to produce better performing models. For -more advanced GANs this is by far the step where you can 'make or break' a -model. -

- -

We start with the generator. As stated in the introductory text the generator -\( g \) upsamples from a random sample to the shape of what we want to predict. In -our case we are trying to predict MNIST images (\( 28\times 28 \) pixels). -

- - - -
-
-
-
-
-
def generator_model():
-    """
-    The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to
-    produce an image from a random seed. We start with a Dense layer taking this
-    random sample as an input and subsequently upsample through multiple
-    convolutional layers.
-    """
-
-    # we define our model
-    model = tf.keras.Sequential()
-
-
-    # adding our input layer. Dense means that every neuron is connected and
-    # the input shape is the shape of our random noise. The units need to match
-    # in some sense the upsampling strides to reach our desired output shape.
-    # we are using 100 random numbers as our seed
-    model.add(layers.Dense(units=7*7*BATCH_SIZE,
-                           use_bias=False,
-                           input_shape=(100, )))
-    # we normalize the output form the Dense layer
-    model.add(layers.BatchNormalization())
-    # and add an activation function to our 'layer'. LeakyReLU avoids vanishing
-    # gradient problem
-    model.add(layers.LeakyReLU())
-    model.add(layers.Reshape((7, 7, BATCH_SIZE)))
-    assert model.output_shape == (None, 7, 7, BATCH_SIZE)
-    # even though we just added four keras layers we think of everything above
-    # as 'one' layer
-
-    # next we add our upscaling convolutional layers
-    model.add(layers.Conv2DTranspose(filters=128,
-                                     kernel_size=(5, 5),
-                                     strides=(1, 1),
-                                     padding='same',
-                                     use_bias=False))
-    model.add(layers.BatchNormalization())
-    model.add(layers.LeakyReLU())
-    assert model.output_shape == (None, 7, 7, 128)
-
-    model.add(layers.Conv2DTranspose(filters=64,
-                                     kernel_size=(5, 5),
-                                     strides=(2, 2),
-                                     padding='same',
-                                     use_bias=False))
-    model.add(layers.BatchNormalization())
-    model.add(layers.LeakyReLU())
-    assert model.output_shape == (None, 14, 14, 64)
-
-    model.add(layers.Conv2DTranspose(filters=1,
-                                     kernel_size=(5, 5),
-                                     strides=(2, 2),
-                                     padding='same',
-                                     use_bias=False,
-                                     activation='tanh'))
-    assert model.output_shape == (None, 28, 28, 1)
-
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

And there we have our 'simple' generator model. Now we move on to defining our -discriminator model \( d \), which is a convolutional neural network based image -classifier. -

- - - -
-
-
-
-
-
def discriminator_model():
-    """
-    The discriminator is a convolutional neural network based image classifier
-    """
-
-    # we define our model
-    model = tf.keras.Sequential()
-    model.add(layers.Conv2D(filters=64,
-                            kernel_size=(5, 5),
-                            strides=(2, 2),
-                            padding='same',
-                            input_shape=[28, 28, 1]))
-    model.add(layers.LeakyReLU())
-    # adding a dropout layer as you do in conv-nets
-    model.add(layers.Dropout(0.3))
-
-
-    model.add(layers.Conv2D(filters=128,
-                            kernel_size=(5, 5),
-                            strides=(2, 2),
-                            padding='same'))
-    model.add(layers.LeakyReLU())
-    # adding a dropout layer as you do in conv-nets
-    model.add(layers.Dropout(0.3))
-
-    model.add(layers.Flatten())
-    model.add(layers.Dense(1))
-
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Other Models

-

Let us take a look at our models. Note: double click images for bigger view.

- - - -
-
-
-
-
-
generator = generator_model()
-plot_model(generator, show_shapes=True, rankdir='LR')
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
discriminator = discriminator_model()
-plot_model(discriminator, show_shapes=True, rankdir='LR')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we need a few helper objects we will use in training

- - - -
-
-
-
-
-
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
-generator_optimizer = tf.keras.optimizers.Adam(1e-4)
-discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

The first object, cross_entropy is our loss function and the two others are -our optimizers. Notice we use the same learning rate for both \( g \) and \( d \). This -is because they need to improve their accuracy at approximately equal speeds to -get convergence (not necessarily exactly equal). Now we define our loss -functions -

- - - -
-
-
-
-
-
def generator_loss(fake_output):
-    loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
-    return loss
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
def discriminator_loss(real_output, fake_output):
-    real_loss = cross_entropy(tf.ones_like(real_output), real_output)
-    fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)
-    total_loss = real_loss + fake_loss
-
-    return total_loss
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define a kind of seed to help us compare the learning process over -multiple training epochs. -

- - - -
-
-
-
-
-
noise_dimension = 100
-n_examples_to_generate = 16
-seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Training Step

- -

Now we have everything we need to define our training step, which we will apply -for every step in our training loop. Notice the @tf.function flag signifying -that the function is tensorflow 'compiled'. Removing this flag doubles the -computation time. -

- - - -
-
-
-
-
-
@tf.function
-def train_step(images):
-    noise = tf.random.normal([BATCH_SIZE, noise_dimension])
-
-    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
-        generated_images = generator(noise, training=True)
-
-        real_output = discriminator(images, training=True)
-        fake_output = discriminator(generated_images, training=True)
-
-        gen_loss = generator_loss(fake_output)
-        disc_loss = discriminator_loss(real_output, fake_output)
-
-    gradients_of_generator = gen_tape.gradient(gen_loss,
-                                            generator.trainable_variables)
-    gradients_of_discriminator = disc_tape.gradient(disc_loss,
-                                            discriminator.trainable_variables)
-    generator_optimizer.apply_gradients(zip(gradients_of_generator,
-                                            generator.trainable_variables))
-    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,
-                                            discriminator.trainable_variables))
-
-    return gen_loss, disc_loss
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define a helper function to produce an output over our training epochs -to see the predictive progression of our generator model. Note: I am including -this code here, but comment it out in the training loop. -

- - -
-
-
-
-
-
def generate_and_save_images(model, epoch, test_input):
-    # we're making inferences here
-    predictions = model(test_input, training=False)
-
-    fig = plt.figure(figsize=(4, 4))
-
-    for i in range(predictions.shape[0]):
-        plt.subplot(4, 4, i+1)
-        plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
-        plt.axis('off')
-
-    plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')
-    plt.close()
-    #plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Checkpoints

-

Setting up checkpoints to periodically save our model during training so that -everything is not lost even if the program were to somehow terminate while -training. -

- - - -
-
-
-
-
-
# Setting up checkpoints to save model during training
-checkpoint_dir = './training_checkpoints'
-checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')
-checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
-                            discriminator_optimizer=discriminator_optimizer,
-                            generator=generator,
-                            discriminator=discriminator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we define our training loop

- - - -
-
-
-
-
-
def train(dataset, epochs):
-    generator_loss_list = []
-    discriminator_loss_list = []
-
-    for epoch in range(epochs):
-        start = time.time()
-
-        for image_batch in dataset:
-            gen_loss, disc_loss = train_step(image_batch)
-            generator_loss_list.append(gen_loss.numpy())
-            discriminator_loss_list.append(disc_loss.numpy())
-
-        #generate_and_save_images(generator, epoch + 1, seed_images)
-
-        if (epoch + 1) % 15 == 0:
-            checkpoint.save(file_prefix=checkpoint_prefix)
-
-        print(f'Time for epoch {epoch} is {time.time() - start}')
-
-    #generate_and_save_images(generator, epochs, seed_images)
-
-    loss_file = './data/lossfile.txt'
-    with open(loss_file, 'w') as outfile:
-        outfile.write(str(generator_loss_list))
-        outfile.write('\n')
-        outfile.write('\n')
-        outfile.write(str(discriminator_loss_list))
-        outfile.write('\n')
-        outfile.write('\n')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

To train simply call this function. Warning: this might take a long time so -there is a folder of a pretrained network already included in the repository. -

- - - -
-
-
-
-
-
train(train_dataset, EPOCHS)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

And here is the result of training our model for 100 epochs

- - -

- -

Now to avoid having to train and everything, which will take a while depending -on your computer setup we now load in the model which produced the above gif. -

- - - -
-
-
-
-
-
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
-restored_generator = checkpoint.generator
-restored_discriminator = checkpoint.discriminator
-
-print(restored_generator)
-print(restored_discriminator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Exploring the Latent Space

- -

We have successfully loaded in our latest model. Let us now play around a bit -and see what kind of things we can learn about this model. Our generator takes -an array of 100 numbers. One idea can be to try to systematically change our -input. Let us try and see what we get -

- - - -
-
-
-
-
-
def generate_latent_points(number=100, scale_means=1, scale_stds=1):
-    latent_dim = 100
-    means = scale_means * tf.linspace(-1, 1, num=latent_dim)
-    stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)
-    latent_space_value_range = tf.random.normal([number, latent_dim],
-                                                means,
-                                                stds,
-                                                dtype=tf.float64)
-
-    return latent_space_value_range
-
-def generate_images(latent_points):
-    # notice we set training to false because we are making inferences
-    generated_images = restored_generator.predict(latent_points)
-
-    return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
def plot_result(generated_images, number=100):
-    # obviously this assumes sqrt number is an int
-    fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),
-                            figsize=(10, 10))
-
-    for i in range(int(np.sqrt(number))):
-        for j in range(int(np.sqrt(number))):
-            axs[i, j].imshow(generated_images[i*j], cmap='Greys')
-            axs[i, j].axis('off')
-
-    plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
generated_images = generate_images(generate_latent_points())
-plot_result(generated_images)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Getting Results

-

We see that the generator generates images that look like MNIST -numbers: \( 1, 4, 7, 9 \). Let's try to tweak it a bit more to see if we are able -to generate a similar plot where we generate every MNIST number. Let us now try -to 'move' a bit around in the latent space. Note: decrease the plot number if -these following cells take too long to run on your computer. -

- - - -
-
-
-
-
-
plot_number = 225
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=5,
-                                                          scale_stds=1))
-plot_result(generated_images, number=plot_number)
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=-5,
-                                                          scale_stds=1))
-plot_result(generated_images, number=plot_number)
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=1,
-                                                          scale_stds=5))
-plot_result(generated_images, number=plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Again, we have found something interesting. Moving around using our means -takes us from digit to digit, while moving around using our standard -deviations seem to increase the number of different digits! In the last image -above, we can barely make out every MNIST digit. Let us make on last plot using -this information by upping the standard deviation of our Gaussian noises. -

- - - -
-
-
-
-
-
plot_number = 400
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=1,
-                                                          scale_stds=10))
-plot_result(generated_images, number=plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

A pretty cool result! We see that our generator indeed has learned a -distribution which qualitatively looks a whole lot like the MNIST dataset. -

- - -

Interpolating Between MNIST Digits

-

Another interesting way to explore the latent space of our generator model is by -interpolating between the MNIST digits. This section is largely based on -this excellent blogpost -by Jason Brownlee. -

- -

So let us start by defining a function to interpolate between two points in the -latent space. -

- - - -
-
-
-
-
-
def interpolation(point_1, point_2, n_steps=10):
-    ratios = np.linspace(0, 1, num=n_steps)
-    vectors = []
-    for i, ratio in enumerate(ratios):
-        vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))
-
-    return tf.stack(vectors)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we have all we need to do our interpolation analysis.

- - - -
-
-
-
-
-
plot_number = 100
-latent_points = generate_latent_points(number=plot_number)
-results = None
-for i in range(0, 2*np.sqrt(plot_number), 2):
-    interpolated = interpolation(latent_points[i], latent_points[i+1])
-    generated_images = generate_images(interpolated)
-
-    if results is None:
-        results = generated_images
-    else:
-        results = tf.stack((results, generated_images))
-
-plot_results(results, plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Basic ideas of the Principal Component Analysis (PCA)

- -

The principal component analysis deals with the problem of fitting a -low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than -the total dimension \( D \) of the problem at hand (our data -set). Mathematically it can be formulated as a statistical problem or -a geometric problem. In our discussion of the theorem for the -classical PCA, we will stay with a statistical approach. -Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable. -

- -

We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition)

-
    -
  • Each data point is determined by \( p \) extrinsic (measurement) variables
  • -
  • We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?
  • -
  • If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
  • -
-

A good read is for example Vidal, Ma and Sastry.

- - -

Introducing the Covariance and Correlation functions

- -

Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities -

- -

Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as -

-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ - \end{bmatrix}, -$$ - -

where for example

-$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -$$ - -

With this definition and recalling that the variance is defined as

-$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ - -

we can rewrite the covariance matrix as

-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ - - - -

More on the covariance

-

The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function -

- -$$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. -$$ - -

The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as -

- -$$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ - \end{bmatrix}, -$$ - -

In the above example this is the function we constructed using pandas.

- - -

Reminding ourselves about Linear Regression

-

In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression -we defined the design/feature matrix \( \boldsymbol{X} \) as -

- -$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ - -

with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -

-$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ - -

with a given vector

-$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ - - - -

Simple Example

-

With these definitions, we can now rewrite our \( 2\times 2 \) -correlation/covariance matrix in terms of a moe general design/feature -matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) -covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) -

- -$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\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}]\\ -\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}]\\ -\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}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\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}]\\ -\end{bmatrix}, -$$ - - - -

The Correlation Matrix

- -

and the correlation matrix

-$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -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}]\\ -\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}]\\ -\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}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\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\\ -\end{bmatrix}, -$$ - - - -

Numpy Functionality

- -

The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) -

- -$$ -\boldsymbol{W}^T = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -$$ - -

which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. -

- - - -
-
-
-
-
-
# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Correlation Matrix again

- -

The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -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). -

- - - -
-
-
-
-
-
import numpy as np
-n = 100
-# define two vectors                                                                                           
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors                                                                                   
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. -

- -

The above procedure with numpy can be made more compact if we use pandas.

- - -

Using Pandas

- -

We whow here how we can set up the correlation matrix using pandas, as done in this simple code

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

And then the Franke Function

- -

We expand this model to the Franke function discussed above.

- - - -
-
-
-
-
-
# Common imports
-import numpy as np
-import pandas as pd
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree \( n \)). We would however not include the intercept -and wee can simply -drop these elements and construct a correlation -matrix without them by centering our matrix elements by subtracting the mean of each column. -

- - -

Lnks with the Design Matrix

- -

We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as

-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. -$$ - -

To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)

-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ -\end{bmatrix}. -$$ - - - -

Computing the Expectation Values

- -

If we then compute the expectation value

-$$ -\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -$$ - -

which is just

-$$ -\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] \\ - \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ - \end{bmatrix}, -$$ - -

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} \).

- -

It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).

- - -

Towards the PCA theorem

- -

We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as

-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. -$$ - -

Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). -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} \). -

- -

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}] \).

- -

That is we have

-$$ -\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}, -$$ - -

since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have

-$$ -\boldsymbol{S}\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}, -$$ - -

and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that

- -$$ -\boldsymbol{S}_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}_i. -$$ - - - -

More on the PCA Theorem

- -

In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). -

- -

The eigenvalues tell us then how much we need to stretch the -corresponding eigenvectors. Dimensions with large eigenvalues have -thus large variations (large variance) and define therefore useful -dimensions. The data points are more spread out in the direction of -these eigenvectors. Smaller eigenvalues mean on the other hand that -the corresponding eigenvectors are shrunk accordingly and the data -points are tightly bunched together and there is not much variation in -these specific directions. Hopefully then we could leave it out -dimensions where the eigenvalues are very small. If \( p \) is very large, -we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) -features/predictors. -

- - -

The Algorithm before theorem

- -

Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here.

-
    -
  • 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.
  • -
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ - -
    -
  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • -
  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}^T\overline{\boldsymbol{X}}] \).
  • -
  • 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}] \).
  • -
  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • -
  • 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.
  • -
- -

Writing our own PCA code

- -

We will use a simple example first with two-dimensional data -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): -

-$$ -\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ -2 & 2 -\end{bmatrix} -$$ - -

Note that the mean refers to each column of data. -We will generate \( n = 10000 \) points \( X = \{ x_1, \ldots, x_N \} \) from -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. -

- - -

Implementing it

-

The following Python code aids in setting up the data and writing out the design matrix. -Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). -

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-n = 10000
-mean = (-1, 2)
-cov = [[4, 2], [2, 2]]
-X = np.random.multivariate_normal(mean, cov, n)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we are going to implement the PCA algorithm. We will break it down into various substeps.

- - -

First Step

- -

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

-$$ -\mu_n = \frac{1}{n} \sum_{i=1}^n x_i -$$ - -

and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form

-$$ -\bar{x}_i = x_i - \mu_n. -$$ - -

When you are done with these steps, print out \( \mu_n \) to verify it is -close to \( \mu \) and plot your mean centered data to verify it is -centered at the origin! -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. -

- - -
-
-
-
-
-
df = pd.DataFrame(X)
-# Pandas does the centering for us
-df = df -df.mean()
-# we center it ourselves
-X_centered = X - X.mean(axis=0)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Scaling

-

Alternatively, we could use the functions we discussed -earlier for scaling the data set. That is, we could have used the -StandardScaler function in Scikit-Learn, a function which ensures -that for each feature/predictor we study the mean value is zero and -the variance is one (every column in the design/feature matrix). You -would then not get the same results, since we divide by the -variance. The diagonal covariance matrix elements will then be one, -while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our -specific case. -

- - -

Centered Data

- -

Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation

-$$ -\begin{equation*} -\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) -\end{equation*} -$$ - -

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 \). -We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows -

- - -
-
-
-
-
-
print(df.cov())
-print(np.cov(X_centered.T))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

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. -Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. -

- - -
-
-
-
-
-
# extract the relevant columns from the centered design matrix of dim n x 2
-x = X_centered[:,0]
-y = X_centered[:,1]
-Cov = np.zeros((2,2))
-Cov[0,1] = np.sum(x.T@y)/(n-1.0)
-Cov[0,0] = np.sum(x.T@x)/(n-1.0)
-Cov[1,1] = np.sum(y.T@y)/(n-1.0)
-Cov[1,0]= Cov[0,1]
-print("Centered covariance using own code")
-print(Cov)
-plt.plot(x, y, 'x')
-plt.axis('equal')
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Exploring

- -

Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. -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. -

- - -

Diagonalize the sample covariance matrix to obtain the principal components

- -

Now we are ready to solve for the principal components! To do so we -diagonalize the sample covariance matrix \( \Sigma \). We can use the -function np.linalg.eig to do so. It will return the eigenvalues and -eigenvectors of \( \Sigma \). Once we have these we can perform the -following tasks: -

- -
    -
  • We compute the percentage of the total variance captured by the first principal component
  • -
  • We plot the mean centered data and lines along the first and second principal components
  • -
  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • -
  • Finally, we approximate the data as
  • -
-$$ -\begin{equation*} -x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 -\end{equation*} -$$ - -

where \( v_0 \) is the first principal component.

- - -

Collecting all Steps

- -

Collecting all these steps we can write our own PCA function and -compare this with the functionality included in Scikit-Learn. -

- -

The code here outlines some of the elements we could include in the -analysis. Feel free to extend upon this in order to address the above -questions. -

- - - -
-
-
-
-
-
# diagonalize and obtain eigenvalues, not necessarily sorted
-EigValues, EigVectors = np.linalg.eig(Cov)
-# sort eigenvectors and eigenvalues
-#permute = EigValues.argsort()
-#EigValues = EigValues[permute]
-#EigVectors = EigVectors[:,permute]
-print("Eigenvalues of Covariance matrix")
-for i in range(2):
-    print(EigValues[i])
-FirstEigvector = EigVectors[:,0]
-SecondEigvector = EigVectors[:,1]
-print("First eigenvector")
-print(FirstEigvector)
-print("Second eigenvector")
-print(SecondEigvector)
-#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2Dsl = pca.fit_transform(X)
-print("Eigenvector of largest eigenvalue")
-print(pca.components_.T[:, 0])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

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?

- - -

Classical PCA Theorem

- -

We assume now that we have a design matrix \( \boldsymbol{X} \) which has been -centered as discussed above. For the sake of simplicity we skip the -overline symbol. The matrix is defined in terms of the various column -vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension -\( \boldsymbol{x}\in {\mathbb{R}}^{n} \). -

- -

The PCA theorem states that minimizing the above reconstruction error -corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which -diagonalizes the empirical covariance(correlation) matrix. The optimal -low-dimensional encoding of the data is then given by a set of vectors -\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the -orthogonal projection of the data onto the columns spanned by the -eigenvectors of the covariance(correlations matrix). -

- - -

The PCA Theorem

- -

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

- -

We are almost there, we have obtained a relation between minimizing -the reconstruction error and the variance and the covariance -matrix. Minimizing the error is equivalent to maximizing the variance -of the projected data. -

- -

We could trivially maximize the variance of the projection (and -thereby minimize the error in the reconstruction function) by letting -the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we -want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by -\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a -Lagrange multiplier we can then in turn maximize -

- -$$ -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). -$$ - -

Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain

- -$$ -\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, -$$ - -

meaning that

-$$ -\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. -$$ - -

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

-$$ -\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. -$$ - -

If we want to maximize the variance (minimize the construction error) -we simply pick the eigenvector of the covariance matrix with the -largest eigenvalue. This establishes the link between the minimization -of the reconstruction function \( J \) in terms of an orthogonal matrix -and the maximization of the variance and thereby the covariance of our -observations encoded in the design/feature matrix \( \boldsymbol{X} \). -

- -

The proof -for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be -established by applying the above arguments and using the fact that -our basis of eigenvectors is orthogonal, see Murphy chapter -12.2. The -discussion in chapter 12.2 of Murphy's text has also a nice link with -the Singular Value Decomposition theorem. For categorical data, see -chapter 12.4 and discussion therein. -

- -

For more details, see for example Vidal, Ma and Sastry, chapter 2.

- - - - -

For a detailed demonstration of the geometric interpretation, see Vidal, Ma and Sastry, section 2.1.2.

- -

Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. -

- -

The following Python code uses NumPy’s svd() function to obtain all the principal components of the -training set, then extracts the first two principal components. First we center the data using either pandas or our own code -

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-from IPython.display import display
-np.random.seed(100)
-# setting up a 10 x 5 vanilla matrix 
-rows = 10
-cols = 5
-X = np.random.randn(rows,cols)
-df = pd.DataFrame(X)
-# Pandas does the centering for us
-df = df -df.mean()
-display(df)
-
-# we center it ourselves
-X_centered = X - X.mean(axis=0)
-# Then check the difference between pandas and our own set up
-print(X_centered-df)
-#Now we do an SVD
-U, s, V = np.linalg.svd(X_centered)
-c1 = V.T[:, 0]
-c2 = V.T[:, 1]
-W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-print(X2D)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. -

- -

Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

- - -
-
-
-
-
-
W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

PCA and scikit-learn

- -

Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -

- - -
-
-
-
-
-
#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D = pca.fit_transform(X)
-print(X2D)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -

- - -
-
-
-
-
-
pca.components_.T[:, 0]
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Another very useful piece of information is the explained variance ratio of each principal component, -available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -

- - -

Back to the Cancer Data

-

We can now repeat the above but applied to real data, in this case our breast cancer data. -Here we compute performance scores on the training data using logistic regression. -

- - -
-
-
-
-
-
import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-
-logreg = LogisticRegression()
-logreg.fit(X_train, y_train)
-print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
-# We scale the data
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-# Then perform again a log reg fit
-logreg.fit(X_train_scaled, y_train)
-print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
-#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D_train = pca.fit_transform(X_train_scaled)
-# and finally compute the log reg fit and the score on the training data	
-logreg.fit(X2D_train,y_train)
-print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that our training data after the PCA decomposition has a performance similar to the non-scaled data.

- -

Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95% of the training set’s variance: -

- - -
-
-
-
-
-
pca = PCA()
-pca.fit(X)
-cumsum = np.cumsum(pca.explained_variance_ratio_)
-d = np.argmax(cumsum >= 0.95) + 1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

- - -
-
-
-
-
-
pca = PCA(n_components=0.95)
-X_reduced = pca.fit_transform(X)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Incremental PCA

- -

One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). -

-

Randomized PCA

- -

Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -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 -previous algorithms when \( d \) is much smaller than \( n \). -

-

Kernel PCA

- -

The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

- - -
-
-
-
-
-
from sklearn.decomposition import KernelPCA
-rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
-X_reduced = rbf_pca.fit_transform(X)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -

Other techniques

- -

There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.

- -

Here are some of the most popular:

-
    -
  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • -
  • 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.
  • -
  • 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).
  • -
  • 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.
  • -
- -
- - - - -
- © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week43/week43-reveal.html b/doc/src/week43/week43-reveal.html deleted file mode 100644 index b980ae5d4..000000000 --- a/doc/src/week43/week43-reveal.html +++ /dev/null @@ -1,3604 +0,0 @@ - - - - - - - - -Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- - - - - - - - - - - -
- -
-

Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -
-
-
-

Nov 2, 2021

-
-
- - -
- © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
-
- -
-

Plans for week 43

- -
    -

  • Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks
  • - -

    -

  • Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
  • - -

    -

-

-

- - - -
- -
-

Reading Recommendations

- -
    -

  • Goodfellow et al, chapter 10 on Recurrent NNs, chapters 11 and 12 on various practicalities around deep learning are also recommended.
  • -

  • Aurelien Geron, chapter 14 on RNNs.
  • -
-
- -
-

Summary on Deep Learning Methods

- -

We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).

- -

The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images.

-
- -
-

CNNs in brief

- -

In summary:

- -
    -

  • 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)
  • -

  • There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
  • -

  • Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
  • -

  • Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
  • -

  • Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
  • -
-

-

For more material on convolutional networks, we strongly recommend -the course -IN5400 – Machine Learning for Image Analysis -and the slides of CS231 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. -

- -

However, both standard feed forwards networks and CNNs perform well on data with unknown length.

- -

This is where recurrent nueral networks (RNNs) come to our rescue.

-
- -
-

Recurrent neural networks: Overarching view

- -

Till now our focus has been, including convolutional neural networks -as well, on feedforward neural networks. The output or the activations -flow only in one direction, from the input layer to the output layer. -

- -

A recurrent neural network (RNN) looks very much like a feedforward -neural network, except that it also has connections pointing -backward. -

- -

RNNs are used to analyze time series data such as stock prices, and -tell you when to buy or sell. In autonomous driving systems, they can -anticipate car trajectories and help avoid accidents. More generally, -they can work on sequences of arbitrary lengths, rather than on -fixed-sized inputs like all the nets we have discussed so far. For -example, they can take sentences, documents, or audio samples as -input, making them extremely useful for natural language processing -systems such as automatic translation and speech-to-text. -

-
- -
-

Set up of an RNN

- -

More to text to be added

-
- -
-

A simple example

- - - -
-
-
-
-
-
# Start importing packages
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-import tensorflow as tf
-from tensorflow.keras import datasets, layers, models
-from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Model, Sequential 
-from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
-from tensorflow.keras import optimizers     
-from tensorflow.keras import regularizers           
-from tensorflow.keras.utils import to_categorical 
-
-
-
-# convert into dataset matrix
-def convertToMatrix(data, step):
- X, Y =[], []
- for i in range(len(data)-step):
-  d=i+step  
-  X.append(data[i:d,])
-  Y.append(data[d,])
- return np.array(X), np.array(Y)
-
-step = 4
-N = 1000    
-Tp = 800    
-
-t=np.arange(0,N)
-x=np.sin(0.02*t)+2*np.random.rand(N)
-df = pd.DataFrame(x)
-df.head()
-
-plt.plot(df)
-plt.show()
-
-values=df.values
-train,test = values[0:Tp,:], values[Tp:N,:]
-
-# add step elements into train and test
-test = np.append(test,np.repeat(test[-1,],step))
-train = np.append(train,np.repeat(train[-1,],step))
- 
-trainX,trainY =convertToMatrix(train,step)
-testX,testY =convertToMatrix(test,step)
-trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
-testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
-
-model = Sequential()
-model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu"))
-model.add(Dense(8, activation="relu")) 
-model.add(Dense(1))
-model.compile(loss='mean_squared_error', optimizer='rmsprop')
-model.summary()
-
-model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)
-trainPredict = model.predict(trainX)
-testPredict= model.predict(testX)
-predicted=np.concatenate((trainPredict,testPredict),axis=0)
-
-trainScore = model.evaluate(trainX, trainY, verbose=0)
-print(trainScore)
-
-index = df.index.values
-plt.plot(index,df)
-plt.plot(index,predicted)
-plt.axvline(df.index[Tp], c="r")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

An extrapolation example

- -

The following code provides an example of how recurrent neural -networks can be used to extrapolate to unknown values of physics data -sets. Specifically, the data sets used in this program come from -a quantum mechanical many-body calculation of energies as functions of the number of particles. -

- - - -
-
-
-
-
-
# For matrices and calculations
-import numpy as np
-# For machine learning (backend for keras)
-import tensorflow as tf
-# User-friendly machine learning library
-# Front end for TensorFlow
-import tensorflow.keras
-# Different methods from Keras needed to create an RNN
-# This is not necessary but it shortened function calls 
-# that need to be used in the code.
-from tensorflow.keras import datasets, layers, models
-from tensorflow.keras.layers import Input
-from tensorflow.keras import regularizers
-from tensorflow.keras.models import Model, Sequential
-from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-from timeit import default_timer as timer
-# For plotting
-import matplotlib.pyplot as plt
-
-
-# The data set
-datatype='VaryDimension'
-X_tot = np.arange(2, 42, 2)
-y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
-	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
-	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Formatting the Data

- -

The way the recurrent neural networks are trained in this program -differs from how machine learning algorithms are usually trained. -Typically a machine learning algorithm is trained by learning the -relationship between the x data and the y data. In this program, the -recurrent neural network will be trained to recognize the relationship -in a sequence of y values. This is type of data formatting is -typically used time series forcasting, but it can also be used in any -extrapolation (time series forecasting is just a specific type of -extrapolation along the time axis). This method of data formatting -does not use the x data and assumes that the y data are evenly spaced. -

- -

For a standard machine learning algorithm, the training data has the -form of (x,y) so the machine learning algorithm learns to assiciate a -y value with a given x value. This is useful when the test data has x -values within the same range as the training data. However, for this -application, the x values of the test data are outside of the x values -of the training data and the traditional method of training a machine -learning algorithm does not work as well. For this reason, the -recurrent neural network is trained on sequences of y values of the -form ((y1, y2), y3), so that the network is concerned with learning -the pattern of the y data and not the relation between the x and y -data. As long as the pattern of y data outside of the training region -stays relatively stable compared to what was inside the training -region, this method of training can produce accurate extrapolations to -y values far removed from the training data set. -

- - - - - - - - - - -
-
-
-
-
-
# FORMAT_DATA
-def format_data(data, length_of_sequence = 2):  
-    """
-        Inputs:
-            data(a numpy array): the data that will be the inputs to the recurrent neural
-                network
-            length_of_sequence (an int): the number of elements in one iteration of the
-                sequence patter.  For a function approximator use length_of_sequence = 2.
-        Returns:
-            rnn_input (a 3D numpy array): the input data for the recurrent neural network.  Its
-                dimensions are length of data - length of sequence, length of sequence, 
-                dimnsion of data
-            rnn_output (a numpy array): the training data for the neural network
-        Formats data to be used in a recurrent neural network.
-    """
-
-    X, Y = [], []
-    for i in range(len(data)-length_of_sequence):
-        # Get the next length_of_sequence elements
-        a = data[i:i+length_of_sequence]
-        # Get the element that immediately follows that
-        b = data[i+length_of_sequence]
-        # Reshape so that each data point is contained in its own array
-        a = np.reshape (a, (len(a), 1))
-        X.append(a)
-        Y.append(b)
-    rnn_input = np.array(X)
-    rnn_output = np.array(Y)
-
-    return rnn_input, rnn_output
-
-
-# ## Defining the Recurrent Neural Network Using Keras
-# 
-# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.
-
-def rnn(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with one hidden layer and returns the model.
-    """
-    # Number of neurons in the input and output layers
-    in_out_neurons = 1
-    # Number of neurons in the hidden layer
-    hidden_neurons = 200
-    # Define the input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons))  
-    # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to 
-    # the network immediately after the input layer
-    rnn = SimpleRNN(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN")(inp)
-    # Define the output layer as a dense neural network layer (standard neural network layer)
-    #and add it to the network immediately after the hidden layer.
-    dens = Dense(in_out_neurons,name="dense")(rnn)
-    # Create the machine learning model starting with the input layer and ending with the 
-    # output layer
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the machine learning model using the mean squared error function as the loss 
-    # function and an Adams optimizer.
-    model.compile(loss="mean_squared_error", optimizer="adam")  
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Predicting New Points With A Trained Recurrent Neural Network

- - - -
-
-
-
-
-
def test_rnn (x1, y_test, plot_min, plot_max):
-    """
-        Inputs:
-            x1 (a list or numpy array): The complete x component of the data set
-            y_test (a list or numpy array): The complete y component of the data set
-            plot_min (an int or float): the smallest x value used in the training data
-            plot_max (an int or float): the largest x valye used in the training data
-        Returns:
-            None.
-        Uses a trained recurrent neural network model to predict future points in the 
-        series.  Computes the MSE of the predicted data set from the true data set, saves
-        the predicted data set to a csv file, and plots the predicted and true data sets w
-        while also displaying the data range used for training.
-    """
-    # Add the training data as the first dim points in the predicted data array as these
-    # are known values.
-    y_pred = y_test[:dim].tolist()
-    # Generate the first input to the trained recurrent neural network using the last two 
-    # points of the training data.  Based on how the network was trained this means that it
-    # will predict the first point in the data set after the training data.  All of the 
-    # brackets are necessary for Tensorflow.
-    next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])
-    # Save the very last point in the training data set.  This will be used later.
-    last = [y_test[dim-1]]
-
-    # Iterate until the complete data set is created.
-    for i in range (dim, len(y_test)):
-        # Predict the next point in the data set using the previous two points.
-        next = model.predict(next_input)
-        # Append just the number of the predicted data set
-        y_pred.append(next[0][0])
-        # Create the input that will be used to predict the next data point in the data set.
-        next_input = np.array([[last, next[0]]], dtype=np.float64)
-        last = next
-
-    # Print the mean squared error between the known data set and the predicted data set.
-    print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())
-    # Save the predicted data set as a csv file for later use
-    name = datatype + 'Predicted'+str(dim)+'.csv'
-    np.savetxt(name, y_pred, delimiter=',')
-    # Plot the known data set and the predicted data set.  The red box represents the region that was used
-    # for the training data.
-    fig, ax = plt.subplots()
-    ax.plot(x1, y_test, label="true", linewidth=3)
-    ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4)
-    ax.legend()
-    # Created a red region to represent the points used in the training data.
-    ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')
-    plt.show()
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-model = rnn(length_of_sequences = rnn_input.shape[1])
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Other Things to Try

- -

Changing the size of the recurrent neural network and its parameters -can drastically change the results you get from the model. The below -code takes the simple recurrent neural network from above and adds a -second hidden layer, changes the number of neurons in the hidden -layer, and explicitly declares the activation function of the hidden -layers to be a sigmoid function. The loss function and optimizer can -also be changed but are kept the same as the above network. These -parameters can be tuned to provide the optimal result from the -network. For some ideas on how to improve the performance of a -recurrent neural network. -

- - - -
-
-
-
-
-
def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with two hidden layers and returns the model.
-    """
-    # Number of neurons in the input and output layers
-    in_out_neurons = 1
-    # Number of neurons in the hidden layer, increased from the first network
-    hidden_neurons = 500
-    # Define the input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons))  
-    # Create two hidden layers instead of one hidden layer.  Explicitly set the activation
-    # function to be the sigmoid function (the default value is hyperbolic tangent)
-    rnn1 = SimpleRNN(hidden_neurons, 
-                    return_sequences=True,  # This needs to be True if another hidden layer is to follow
-                    stateful = stateful, activation = 'sigmoid',
-                    name="RNN1")(inp)
-    rnn2 = SimpleRNN(hidden_neurons, 
-                    return_sequences=False, activation = 'sigmoid',
-                    stateful = stateful,
-                    name="RNN2")(rnn1)
-    # Define the output layer as a dense neural network layer (standard neural network layer)
-    #and add it to the network immediately after the hidden layer.
-    dens = Dense(in_out_neurons,name="dense")(rnn2)
-    # Create the machine learning model starting with the input layer and ending with the 
-    # output layer
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the machine learning model using the mean squared error function as the loss 
-    # function and an Adams optimizer.
-    model.compile(loss="mean_squared_error", optimizer="adam")  
-    return model
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-model = rnn_2layers(length_of_sequences = 2)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Other Types of Recurrent Neural Networks

- -

Besides a simple recurrent neural network layer, there are two other -commonly used types of recurrent neural network layers: Long Short -Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short -introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b -and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b. -

- -

The first network created below is similar to the previous network, -but it replaces the SimpleRNN layers with LSTM layers. The second -network below has two hidden layers made up of GRUs, which are -preceeded by two dense (feeddorward) neural network layers. These -dense layers "preprocess" the data before it reaches the recurrent -layers. This architecture has been shown to improve the performance -of recurrent neural networks (see the link above and also -https://arxiv.org/pdf/1807.02857.pdf. -

- - - -
-
-
-
-
-
def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.
-    """
-    # Number of neurons on the input/output layer and the number of neurons in the hidden layer
-    in_out_neurons = 1
-    hidden_neurons = 250
-    # Input Layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons)) 
-    # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)
-    rnn= LSTM(hidden_neurons, 
-                    return_sequences=True,
-                    stateful = stateful,
-                    name="RNN", use_bias=True, activation='tanh')(inp)
-    rnn1 = LSTM(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN1", use_bias=True, activation='tanh')(rnn)
-    # Output layer
-    dens = Dense(in_out_neurons,name="dense")(rnn1)
-    # Define the midel
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the model
-    model.compile(loss='mean_squared_error', optimizer='adam')  
-    # Return the model
-    return model
-
-def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with four hidden layers (two dense followed by
-        two GRU layers) and returns the model.
-    """    
-    # Number of neurons on the input/output layers and hidden layers
-    in_out_neurons = 1
-    hidden_neurons = 250
-    # Input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons)) 
-    # Hidden Dense (feedforward) layers
-    dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)
-    dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)
-    # Hidden GRU layers
-    rnn1 = GRU(hidden_neurons, 
-                    return_sequences=True,
-                    stateful = stateful,
-                    name="RNN1", use_bias=True)(dnn1)
-    rnn = GRU(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN", use_bias=True)(rnn1)
-    # Output layer
-    dens = Dense(in_out_neurons,name="dense")(rnn)
-    # Define the model
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the mdoel
-    model.compile(loss='mean_squared_error', optimizer='adam')  
-    # Return the model
-    return model
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-# Change the method name to reflect which network you want to use
-model = dnn2_gru2(length_of_sequences = 2)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)
-# 
-# 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.
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-# Reshape the data for Keras specifications
-X_train = X_train.reshape((dim, 1))
-y_train = y_train.reshape((dim, 1))
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-# Set the sequence length to 1 for regular data formatting 
-model = rnn(length_of_sequences = 1)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(X_train, y_train, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict the remaining data points
-X_pred = X_tot[dim:]
-X_pred = X_pred.reshape((len(X_pred), 1))
-y_model = model.predict(X_pred)
-y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))
-
-# Plot the known data set and the predicted data set.  The red box represents the region that was used
-# for the training data.
-fig, ax = plt.subplots()
-ax.plot(X_tot, y_tot, label="true", linewidth=3)
-ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4)
-ax.legend()
-# Created a red region to represent the points used in the training data.
-ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')
-plt.show()
-
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Generative Models

- -

Generative models describe a class of statistical models that are a contrast -to discriminative models. Informally we say that generative models can -generate new data instances while discriminative models discriminate between -different kinds of data instances. A generative model could generate new photos -of animals that look like 'real' animals while a discriminative model could tell -a dog from a cat. More formally, given a data set \( x \) and a set of labels / -targets \( y \). Generative models capture the joint probability \( p(x, y) \), or -just \( p(x) \) if there are no labels, while discriminative models capture the -conditional probability \( p(y | x) \). Discriminative models generally try to draw -boundaries in the data space (often high dimensional), while generative models -try to model how data is placed throughout the space. -

- -

Note: this material is thanks to Linus Ekstrøm.

-
- -
-

Generative Adversarial Networks

- -

Generative Adversarial Networks are a type of unsupervised machine learning -algorithm proposed by Goodfellow et. al -in 2014 (short and good article). -

- -

The simplest formulation of -the model is based on a game theoretic approach, zero sum game, where we pit -two neural networks against one another. We define two rival networks, one -generator \( g \), and one discriminator \( d \). The generator directly produces -samples -

-

 
-$$ -\begin{equation} - x = g(z; \theta^{(g)}) -\tag{1} -\end{equation} -$$ -

 
-

- -
-

Discriminator

-

The discriminator attempts to distinguish between samples drawn from the -training data and samples drawn from the generator. In other words, it tries to -tell the difference between the fake data produced by \( g \) and the actual data -samples we want to do prediction on. The discriminator outputs a probability -value given by -

- -

 
-$$ -\begin{equation} - d(x; \theta^{(d)}) -\tag{2} -\end{equation} -$$ -

 
- -

indicating the probability that \( x \) is a real training example rather than a -fake sample the generator has generated. The simplest way to formulate the -learning process in a generative adversarial network is a zero-sum game, in -which a function -

- -

 
-$$ -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) -\tag{3} -\end{equation} -$$ -

 
- -

determines the reward for the discriminator, while the generator gets the -conjugate reward -

- -

 
-$$ -\begin{equation} - -v(\theta^{(g)}, \theta^{(d)}) -\tag{4} -\end{equation} -$$ -

 
-

- -
-

Learning Process

- -

During learning both of the networks maximize their own reward function, so that -the generator gets better and better at tricking the discriminator, while the -discriminator gets better and better at telling the difference between the fake -and real data. The generator and discriminator alternate on which one trains at -one time (i.e. for one epoch). In other words, we keep the generator constant -and train the discriminator, then we keep the discriminator constant to train -the generator and repeat. It is this back and forth dynamic which lets GANs -tackle otherwise intractable generative problems. As the generator improves with - training, the discriminator's performance gets worse because it cannot easily - tell the difference between real and fake. If the generator ends up succeeding - perfectly, the the discriminator will do no better than random guessing i.e. - 50\%. This progression in the training poses a problem for the convergence - criteria for GANs. The discriminator feedback gets less meaningful over time, - if we continue training after this point then the generator is effectively - training on junk data which can undo the learning up to that point. Therefore, - we stop training when the discriminator starts outputting \( 1/2 \) everywhere. -

-
- -
-

More about the Learning Process

- -

At convergence we have

- -

 
-$$ -\begin{equation} - g^* = \underset{g}{\mathrm{argmin}}\hspace{2pt} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\tag{5} -\end{equation} -$$ -

 
- -

The default choice for \( v \) is

-

 
-$$ -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x) - + \mathbb{E}_{x\sim p_\mathrm{model}} - \log (1 - d(x)) -\tag{6} -\end{equation} -$$ -

 
- -

The main motivation for the design of GANs is that the learning process requires -neither approximate inference (variational autoencoders for example) nor -approximation of a partition function. In the case where -

-

 
-$$ -\begin{equation} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\tag{7} -\end{equation} -$$ -

 
- -

is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is -asymptotically consistent -( Seth Lloyd on QuGANs ). -

-
- -
-

Additional References

-

This is in -general not the case and it is possible to get situations where the training -process never converges because the generator and discriminator chase one -another around in the parameter space indefinitely. A much deeper discussion on -the currently open research problem of GAN convergence is available -here. To -anyone interested in learning more about GANs it is a highly recommended read. -Direct quote: "In this best-performing formulation, the generator aims to -increase the log probability that the discriminator makes a mistake, rather than -aiming to decrease the log probability that the discriminator makes the correct -prediction." Another interesting read -

-
- -
-

Writing Our First Generative Adversarial Network

-

Let us now move on to actually implementing a GAN in tensorflow. We will study -the performance of our GAN on the MNIST dataset. This code is based on and -adapted from the -google tutorial -

- -

First we import our libraries

- - - -
-
-
-
-
-
import os
-import time
-import numpy as np
-import tensorflow as tf
-import matplotlib.pyplot as plt
-from tensorflow.keras import layers
-from tensorflow.keras.utils import plot_model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define our hyperparameters and import our data the usual way

- - - -
-
-
-
-
-
BUFFER_SIZE = 60000
-BATCH_SIZE = 256
-EPOCHS = 30
-
-data = tf.keras.datasets.mnist.load_data()
-(train_images, train_labels), (test_images, test_labels) = data
-train_images = np.reshape(train_images, (train_images.shape[0],
-                                         28,
-                                         28,
-                                         1)).astype('float32')
-
-# we normalize between -1 and 1
-train_images = (train_images - 127.5) / 127.5
-training_dataset = tf.data.Dataset.from_tensor_slices(
-                      train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

MNIST and GANs

- -

Let's have a quick look

- - - -
-
-
-
-
-
plt.imshow(train_images[0], cmap='Greys')
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we define our two models. This is where the 'magic' happens. There are a -huge amount of possible formulations for both models. A lot of engineering and -trial and error can be done here to try to produce better performing models. For -more advanced GANs this is by far the step where you can 'make or break' a -model. -

- -

We start with the generator. As stated in the introductory text the generator -\( g \) upsamples from a random sample to the shape of what we want to predict. In -our case we are trying to predict MNIST images (\( 28\times 28 \) pixels). -

- - - -
-
-
-
-
-
def generator_model():
-    """
-    The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to
-    produce an image from a random seed. We start with a Dense layer taking this
-    random sample as an input and subsequently upsample through multiple
-    convolutional layers.
-    """
-
-    # we define our model
-    model = tf.keras.Sequential()
-
-
-    # adding our input layer. Dense means that every neuron is connected and
-    # the input shape is the shape of our random noise. The units need to match
-    # in some sense the upsampling strides to reach our desired output shape.
-    # we are using 100 random numbers as our seed
-    model.add(layers.Dense(units=7*7*BATCH_SIZE,
-                           use_bias=False,
-                           input_shape=(100, )))
-    # we normalize the output form the Dense layer
-    model.add(layers.BatchNormalization())
-    # and add an activation function to our 'layer'. LeakyReLU avoids vanishing
-    # gradient problem
-    model.add(layers.LeakyReLU())
-    model.add(layers.Reshape((7, 7, BATCH_SIZE)))
-    assert model.output_shape == (None, 7, 7, BATCH_SIZE)
-    # even though we just added four keras layers we think of everything above
-    # as 'one' layer
-
-    # next we add our upscaling convolutional layers
-    model.add(layers.Conv2DTranspose(filters=128,
-                                     kernel_size=(5, 5),
-                                     strides=(1, 1),
-                                     padding='same',
-                                     use_bias=False))
-    model.add(layers.BatchNormalization())
-    model.add(layers.LeakyReLU())
-    assert model.output_shape == (None, 7, 7, 128)
-
-    model.add(layers.Conv2DTranspose(filters=64,
-                                     kernel_size=(5, 5),
-                                     strides=(2, 2),
-                                     padding='same',
-                                     use_bias=False))
-    model.add(layers.BatchNormalization())
-    model.add(layers.LeakyReLU())
-    assert model.output_shape == (None, 14, 14, 64)
-
-    model.add(layers.Conv2DTranspose(filters=1,
-                                     kernel_size=(5, 5),
-                                     strides=(2, 2),
-                                     padding='same',
-                                     use_bias=False,
-                                     activation='tanh'))
-    assert model.output_shape == (None, 28, 28, 1)
-
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

And there we have our 'simple' generator model. Now we move on to defining our -discriminator model \( d \), which is a convolutional neural network based image -classifier. -

- - - -
-
-
-
-
-
def discriminator_model():
-    """
-    The discriminator is a convolutional neural network based image classifier
-    """
-
-    # we define our model
-    model = tf.keras.Sequential()
-    model.add(layers.Conv2D(filters=64,
-                            kernel_size=(5, 5),
-                            strides=(2, 2),
-                            padding='same',
-                            input_shape=[28, 28, 1]))
-    model.add(layers.LeakyReLU())
-    # adding a dropout layer as you do in conv-nets
-    model.add(layers.Dropout(0.3))
-
-
-    model.add(layers.Conv2D(filters=128,
-                            kernel_size=(5, 5),
-                            strides=(2, 2),
-                            padding='same'))
-    model.add(layers.LeakyReLU())
-    # adding a dropout layer as you do in conv-nets
-    model.add(layers.Dropout(0.3))
-
-    model.add(layers.Flatten())
-    model.add(layers.Dense(1))
-
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Other Models

-

Let us take a look at our models. Note: double click images for bigger view.

- - - -
-
-
-
-
-
generator = generator_model()
-plot_model(generator, show_shapes=True, rankdir='LR')
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
discriminator = discriminator_model()
-plot_model(discriminator, show_shapes=True, rankdir='LR')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we need a few helper objects we will use in training

- - - -
-
-
-
-
-
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
-generator_optimizer = tf.keras.optimizers.Adam(1e-4)
-discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

The first object, cross_entropy is our loss function and the two others are -our optimizers. Notice we use the same learning rate for both \( g \) and \( d \). This -is because they need to improve their accuracy at approximately equal speeds to -get convergence (not necessarily exactly equal). Now we define our loss -functions -

- - - -
-
-
-
-
-
def generator_loss(fake_output):
-    loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
-    return loss
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
def discriminator_loss(real_output, fake_output):
-    real_loss = cross_entropy(tf.ones_like(real_output), real_output)
-    fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)
-    total_loss = real_loss + fake_loss
-
-    return total_loss
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define a kind of seed to help us compare the learning process over -multiple training epochs. -

- - - -
-
-
-
-
-
noise_dimension = 100
-n_examples_to_generate = 16
-seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Training Step

- -

Now we have everything we need to define our training step, which we will apply -for every step in our training loop. Notice the @tf.function flag signifying -that the function is tensorflow 'compiled'. Removing this flag doubles the -computation time. -

- - - -
-
-
-
-
-
@tf.function
-def train_step(images):
-    noise = tf.random.normal([BATCH_SIZE, noise_dimension])
-
-    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
-        generated_images = generator(noise, training=True)
-
-        real_output = discriminator(images, training=True)
-        fake_output = discriminator(generated_images, training=True)
-
-        gen_loss = generator_loss(fake_output)
-        disc_loss = discriminator_loss(real_output, fake_output)
-
-    gradients_of_generator = gen_tape.gradient(gen_loss,
-                                            generator.trainable_variables)
-    gradients_of_discriminator = disc_tape.gradient(disc_loss,
-                                            discriminator.trainable_variables)
-    generator_optimizer.apply_gradients(zip(gradients_of_generator,
-                                            generator.trainable_variables))
-    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,
-                                            discriminator.trainable_variables))
-
-    return gen_loss, disc_loss
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define a helper function to produce an output over our training epochs -to see the predictive progression of our generator model. Note: I am including -this code here, but comment it out in the training loop. -

- - -
-
-
-
-
-
def generate_and_save_images(model, epoch, test_input):
-    # we're making inferences here
-    predictions = model(test_input, training=False)
-
-    fig = plt.figure(figsize=(4, 4))
-
-    for i in range(predictions.shape[0]):
-        plt.subplot(4, 4, i+1)
-        plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
-        plt.axis('off')
-
-    plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')
-    plt.close()
-    #plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Checkpoints

-

Setting up checkpoints to periodically save our model during training so that -everything is not lost even if the program were to somehow terminate while -training. -

- - - -
-
-
-
-
-
# Setting up checkpoints to save model during training
-checkpoint_dir = './training_checkpoints'
-checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')
-checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
-                            discriminator_optimizer=discriminator_optimizer,
-                            generator=generator,
-                            discriminator=discriminator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we define our training loop

- - - -
-
-
-
-
-
def train(dataset, epochs):
-    generator_loss_list = []
-    discriminator_loss_list = []
-
-    for epoch in range(epochs):
-        start = time.time()
-
-        for image_batch in dataset:
-            gen_loss, disc_loss = train_step(image_batch)
-            generator_loss_list.append(gen_loss.numpy())
-            discriminator_loss_list.append(disc_loss.numpy())
-
-        #generate_and_save_images(generator, epoch + 1, seed_images)
-
-        if (epoch + 1) % 15 == 0:
-            checkpoint.save(file_prefix=checkpoint_prefix)
-
-        print(f'Time for epoch {epoch} is {time.time() - start}')
-
-    #generate_and_save_images(generator, epochs, seed_images)
-
-    loss_file = './data/lossfile.txt'
-    with open(loss_file, 'w') as outfile:
-        outfile.write(str(generator_loss_list))
-        outfile.write('\n')
-        outfile.write('\n')
-        outfile.write(str(discriminator_loss_list))
-        outfile.write('\n')
-        outfile.write('\n')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

To train simply call this function. Warning: this might take a long time so -there is a folder of a pretrained network already included in the repository. -

- - - -
-
-
-
-
-
train(train_dataset, EPOCHS)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

And here is the result of training our model for 100 epochs

- - -

- -

Now to avoid having to train and everything, which will take a while depending -on your computer setup we now load in the model which produced the above gif. -

- - - -
-
-
-
-
-
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
-restored_generator = checkpoint.generator
-restored_discriminator = checkpoint.discriminator
-
-print(restored_generator)
-print(restored_discriminator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Exploring the Latent Space

- -

We have successfully loaded in our latest model. Let us now play around a bit -and see what kind of things we can learn about this model. Our generator takes -an array of 100 numbers. One idea can be to try to systematically change our -input. Let us try and see what we get -

- - - -
-
-
-
-
-
def generate_latent_points(number=100, scale_means=1, scale_stds=1):
-    latent_dim = 100
-    means = scale_means * tf.linspace(-1, 1, num=latent_dim)
-    stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)
-    latent_space_value_range = tf.random.normal([number, latent_dim],
-                                                means,
-                                                stds,
-                                                dtype=tf.float64)
-
-    return latent_space_value_range
-
-def generate_images(latent_points):
-    # notice we set training to false because we are making inferences
-    generated_images = restored_generator.predict(latent_points)
-
-    return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
def plot_result(generated_images, number=100):
-    # obviously this assumes sqrt number is an int
-    fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),
-                            figsize=(10, 10))
-
-    for i in range(int(np.sqrt(number))):
-        for j in range(int(np.sqrt(number))):
-            axs[i, j].imshow(generated_images[i*j], cmap='Greys')
-            axs[i, j].axis('off')
-
-    plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
generated_images = generate_images(generate_latent_points())
-plot_result(generated_images)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Getting Results

-

We see that the generator generates images that look like MNIST -numbers: \( 1, 4, 7, 9 \). Let's try to tweak it a bit more to see if we are able -to generate a similar plot where we generate every MNIST number. Let us now try -to 'move' a bit around in the latent space. Note: decrease the plot number if -these following cells take too long to run on your computer. -

- - - -
-
-
-
-
-
plot_number = 225
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=5,
-                                                          scale_stds=1))
-plot_result(generated_images, number=plot_number)
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=-5,
-                                                          scale_stds=1))
-plot_result(generated_images, number=plot_number)
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=1,
-                                                          scale_stds=5))
-plot_result(generated_images, number=plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Again, we have found something interesting. Moving around using our means -takes us from digit to digit, while moving around using our standard -deviations seem to increase the number of different digits! In the last image -above, we can barely make out every MNIST digit. Let us make on last plot using -this information by upping the standard deviation of our Gaussian noises. -

- - - -
-
-
-
-
-
plot_number = 400
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=1,
-                                                          scale_stds=10))
-plot_result(generated_images, number=plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

A pretty cool result! We see that our generator indeed has learned a -distribution which qualitatively looks a whole lot like the MNIST dataset. -

-
- -
-

Interpolating Between MNIST Digits

-

Another interesting way to explore the latent space of our generator model is by -interpolating between the MNIST digits. This section is largely based on -this excellent blogpost -by Jason Brownlee. -

- -

So let us start by defining a function to interpolate between two points in the -latent space. -

- - - -
-
-
-
-
-
def interpolation(point_1, point_2, n_steps=10):
-    ratios = np.linspace(0, 1, num=n_steps)
-    vectors = []
-    for i, ratio in enumerate(ratios):
-        vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))
-
-    return tf.stack(vectors)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we have all we need to do our interpolation analysis.

- - - -
-
-
-
-
-
plot_number = 100
-latent_points = generate_latent_points(number=plot_number)
-results = None
-for i in range(0, 2*np.sqrt(plot_number), 2):
-    interpolated = interpolation(latent_points[i], latent_points[i+1])
-    generated_images = generate_images(interpolated)
-
-    if results is None:
-        results = generated_images
-    else:
-        results = tf.stack((results, generated_images))
-
-plot_results(results, plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Basic ideas of the Principal Component Analysis (PCA)

- -

The principal component analysis deals with the problem of fitting a -low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than -the total dimension \( D \) of the problem at hand (our data -set). Mathematically it can be formulated as a statistical problem or -a geometric problem. In our discussion of the theorem for the -classical PCA, we will stay with a statistical approach. -Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable. -

- -

We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition)

-
    -

  • Each data point is determined by \( p \) extrinsic (measurement) variables
  • -

  • We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?
  • -

  • If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
  • -
-

-

A good read is for example Vidal, Ma and Sastry.

-
- -
-

Introducing the Covariance and Correlation functions

- -

Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities -

- -

Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as -

-

 
-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ - \end{bmatrix}, -$$ -

 
- -

where for example

-

 
-$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -$$ -

 
- -

With this definition and recalling that the variance is defined as

-

 
-$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ -

 
- -

we can rewrite the covariance matrix as

-

 
-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ -

 
-

- -
-

More on the covariance

-

The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function -

- -

 
-$$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. -$$ -

 
- -

The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as -

- -

 
-$$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ - \end{bmatrix}, -$$ -

 
- -

In the above example this is the function we constructed using pandas.

-
- -
-

Reminding ourselves about Linear Regression

-

In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression -we defined the design/feature matrix \( \boldsymbol{X} \) as -

- -

 
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ -

 
- -

with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -

-

 
-$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ -

 
- -

with a given vector

-

 
-$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ -

 
-

- -
-

Simple Example

-

With these definitions, we can now rewrite our \( 2\times 2 \) -correlation/covariance matrix in terms of a moe general design/feature -matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) -covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) -

- -

 
-$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\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}]\\ -\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}]\\ -\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}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\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}]\\ -\end{bmatrix}, -$$ -

 
-

- -
-

The Correlation Matrix

- -

and the correlation matrix

-

 
-$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -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}]\\ -\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}]\\ -\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}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\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\\ -\end{bmatrix}, -$$ -

 
-

- -
-

Numpy Functionality

- -

The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) -

- -

 
-$$ -\boldsymbol{W}^T = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -$$ -

 
- -

which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. -

- - - -
-
-
-
-
-
# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Correlation Matrix again

- -

The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -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). -

- - - -
-
-
-
-
-
import numpy as np
-n = 100
-# define two vectors                                                                                           
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors                                                                                   
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. -

- -

The above procedure with numpy can be made more compact if we use pandas.

-
- -
-

Using Pandas

- -

We whow here how we can set up the correlation matrix using pandas, as done in this simple code

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

And then the Franke Function

- -

We expand this model to the Franke function discussed above.

- - - -
-
-
-
-
-
# Common imports
-import numpy as np
-import pandas as pd
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree \( n \)). We would however not include the intercept -and wee can simply -drop these elements and construct a correlation -matrix without them by centering our matrix elements by subtracting the mean of each column. -

-
- -
-

Lnks with the Design Matrix

- -

We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as

-

 
-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. -$$ -

 
- -

To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)

-

 
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ -\end{bmatrix}. -$$ -

 
-

- -
-

Computing the Expectation Values

- -

If we then compute the expectation value

-

 
-$$ -\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -$$ -

 
- -

which is just

-

 
-$$ -\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] \\ - \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ - \end{bmatrix}, -$$ -

 
- -

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} \).

- -

It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).

-
- -
-

Towards the PCA theorem

- -

We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as

-

 
-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. -$$ -

 
- -

Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). -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} \). -

- -

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}] \).

- -

That is we have

-

 
-$$ -\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}, -$$ -

 
- -

since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have

-

 
-$$ -\boldsymbol{S}\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}, -$$ -

 
- -

and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that

- -

 
-$$ -\boldsymbol{S}_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}_i. -$$ -

 
-

- -
-

More on the PCA Theorem

- -

In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). -

- -

The eigenvalues tell us then how much we need to stretch the -corresponding eigenvectors. Dimensions with large eigenvalues have -thus large variations (large variance) and define therefore useful -dimensions. The data points are more spread out in the direction of -these eigenvectors. Smaller eigenvalues mean on the other hand that -the corresponding eigenvectors are shrunk accordingly and the data -points are tightly bunched together and there is not much variation in -these specific directions. Hopefully then we could leave it out -dimensions where the eigenvalues are very small. If \( p \) is very large, -we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) -features/predictors. -

-
- -
-

The Algorithm before theorem

- -

Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here.

-
    -

  • 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.
  • -
-

-

 
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ -

 
- -

    -

  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • -

  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}^T\overline{\boldsymbol{X}}] \).
  • -

  • 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}] \).
  • -

  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • -

  • 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.
  • -
-
- -
-

Writing our own PCA code

- -

We will use a simple example first with two-dimensional data -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): -

-

 
-$$ -\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ -2 & 2 -\end{bmatrix} -$$ -

 
- -

Note that the mean refers to each column of data. -We will generate \( n = 10000 \) points \( X = \{ x_1, \ldots, x_N \} \) from -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. -

-
- -
-

Implementing it

-

The following Python code aids in setting up the data and writing out the design matrix. -Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). -

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-n = 10000
-mean = (-1, 2)
-cov = [[4, 2], [2, 2]]
-X = np.random.multivariate_normal(mean, cov, n)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we are going to implement the PCA algorithm. We will break it down into various substeps.

-
- -
-

First Step

- -

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

-

 
-$$ -\mu_n = \frac{1}{n} \sum_{i=1}^n x_i -$$ -

 
- -

and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form

-

 
-$$ -\bar{x}_i = x_i - \mu_n. -$$ -

 
- -

When you are done with these steps, print out \( \mu_n \) to verify it is -close to \( \mu \) and plot your mean centered data to verify it is -centered at the origin! -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. -

- - -
-
-
-
-
-
df = pd.DataFrame(X)
-# Pandas does the centering for us
-df = df -df.mean()
-# we center it ourselves
-X_centered = X - X.mean(axis=0)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Scaling

-

Alternatively, we could use the functions we discussed -earlier for scaling the data set. That is, we could have used the -StandardScaler function in Scikit-Learn, a function which ensures -that for each feature/predictor we study the mean value is zero and -the variance is one (every column in the design/feature matrix). You -would then not get the same results, since we divide by the -variance. The diagonal covariance matrix elements will then be one, -while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our -specific case. -

-
- -
-

Centered Data

- -

Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation

-

 
-$$ -\begin{equation*} -\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) -\end{equation*} -$$ -

 
- -

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 \). -We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows -

- - -
-
-
-
-
-
print(df.cov())
-print(np.cov(X_centered.T))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

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. -Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. -

- - -
-
-
-
-
-
# extract the relevant columns from the centered design matrix of dim n x 2
-x = X_centered[:,0]
-y = X_centered[:,1]
-Cov = np.zeros((2,2))
-Cov[0,1] = np.sum(x.T@y)/(n-1.0)
-Cov[0,0] = np.sum(x.T@x)/(n-1.0)
-Cov[1,1] = np.sum(y.T@y)/(n-1.0)
-Cov[1,0]= Cov[0,1]
-print("Centered covariance using own code")
-print(Cov)
-plt.plot(x, y, 'x')
-plt.axis('equal')
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Exploring

- -

Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. -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. -

-
- -
-

Diagonalize the sample covariance matrix to obtain the principal components

- -

Now we are ready to solve for the principal components! To do so we -diagonalize the sample covariance matrix \( \Sigma \). We can use the -function np.linalg.eig to do so. It will return the eigenvalues and -eigenvectors of \( \Sigma \). Once we have these we can perform the -following tasks: -

- -
    -

  • We compute the percentage of the total variance captured by the first principal component
  • -

  • We plot the mean centered data and lines along the first and second principal components
  • -

  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • -

  • Finally, we approximate the data as
  • -
-

-

 
-$$ -\begin{equation*} -x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 -\end{equation*} -$$ -

 
- -

where \( v_0 \) is the first principal component.

-
- -
-

Collecting all Steps

- -

Collecting all these steps we can write our own PCA function and -compare this with the functionality included in Scikit-Learn. -

- -

The code here outlines some of the elements we could include in the -analysis. Feel free to extend upon this in order to address the above -questions. -

- - - -
-
-
-
-
-
# diagonalize and obtain eigenvalues, not necessarily sorted
-EigValues, EigVectors = np.linalg.eig(Cov)
-# sort eigenvectors and eigenvalues
-#permute = EigValues.argsort()
-#EigValues = EigValues[permute]
-#EigVectors = EigVectors[:,permute]
-print("Eigenvalues of Covariance matrix")
-for i in range(2):
-    print(EigValues[i])
-FirstEigvector = EigVectors[:,0]
-SecondEigvector = EigVectors[:,1]
-print("First eigenvector")
-print(FirstEigvector)
-print("Second eigenvector")
-print(SecondEigvector)
-#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2Dsl = pca.fit_transform(X)
-print("Eigenvector of largest eigenvalue")
-print(pca.components_.T[:, 0])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

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?

-
- -
-

Classical PCA Theorem

- -

We assume now that we have a design matrix \( \boldsymbol{X} \) which has been -centered as discussed above. For the sake of simplicity we skip the -overline symbol. The matrix is defined in terms of the various column -vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension -\( \boldsymbol{x}\in {\mathbb{R}}^{n} \). -

- -

The PCA theorem states that minimizing the above reconstruction error -corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which -diagonalizes the empirical covariance(correlation) matrix. The optimal -low-dimensional encoding of the data is then given by a set of vectors -\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the -orthogonal projection of the data onto the columns spanned by the -eigenvectors of the covariance(correlations matrix). -

-
- -
-

The PCA Theorem

- -

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

- -

We are almost there, we have obtained a relation between minimizing -the reconstruction error and the variance and the covariance -matrix. Minimizing the error is equivalent to maximizing the variance -of the projected data. -

- -

We could trivially maximize the variance of the projection (and -thereby minimize the error in the reconstruction function) by letting -the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we -want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by -\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a -Lagrange multiplier we can then in turn maximize -

- -

 
-$$ -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). -$$ -

 
- -

Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain

- -

 
-$$ -\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, -$$ -

 
- -

meaning that

-

 
-$$ -\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. -$$ -

 
- -

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

-

 
-$$ -\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. -$$ -

 
- -

If we want to maximize the variance (minimize the construction error) -we simply pick the eigenvector of the covariance matrix with the -largest eigenvalue. This establishes the link between the minimization -of the reconstruction function \( J \) in terms of an orthogonal matrix -and the maximization of the variance and thereby the covariance of our -observations encoded in the design/feature matrix \( \boldsymbol{X} \). -

- -

The proof -for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be -established by applying the above arguments and using the fact that -our basis of eigenvectors is orthogonal, see Murphy chapter -12.2. The -discussion in chapter 12.2 of Murphy's text has also a nice link with -the Singular Value Decomposition theorem. For categorical data, see -chapter 12.4 and discussion therein. -

- -

For more details, see for example Vidal, Ma and Sastry, chapter 2.

-
- -
- - -

For a detailed demonstration of the geometric interpretation, see Vidal, Ma and Sastry, section 2.1.2.

- -

Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. -

- -

The following Python code uses NumPy’s svd() function to obtain all the principal components of the -training set, then extracts the first two principal components. First we center the data using either pandas or our own code -

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-from IPython.display import display
-np.random.seed(100)
-# setting up a 10 x 5 vanilla matrix 
-rows = 10
-cols = 5
-X = np.random.randn(rows,cols)
-df = pd.DataFrame(X)
-# Pandas does the centering for us
-df = df -df.mean()
-display(df)
-
-# we center it ourselves
-X_centered = X - X.mean(axis=0)
-# Then check the difference between pandas and our own set up
-print(X_centered-df)
-#Now we do an SVD
-U, s, V = np.linalg.svd(X_centered)
-c1 = V.T[:, 0]
-c2 = V.T[:, 1]
-W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-print(X2D)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. -

- -

Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

- - -
-
-
-
-
-
W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

PCA and scikit-learn

- -

Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -

- - -
-
-
-
-
-
#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D = pca.fit_transform(X)
-print(X2D)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -

- - -
-
-
-
-
-
pca.components_.T[:, 0]
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Another very useful piece of information is the explained variance ratio of each principal component, -available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -

-
- -
-

Back to the Cancer Data

-

We can now repeat the above but applied to real data, in this case our breast cancer data. -Here we compute performance scores on the training data using logistic regression. -

- - -
-
-
-
-
-
import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-
-logreg = LogisticRegression()
-logreg.fit(X_train, y_train)
-print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
-# We scale the data
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-# Then perform again a log reg fit
-logreg.fit(X_train_scaled, y_train)
-print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
-#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D_train = pca.fit_transform(X_train_scaled)
-# and finally compute the log reg fit and the score on the training data	
-logreg.fit(X2D_train,y_train)
-print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that our training data after the PCA decomposition has a performance similar to the non-scaled data.

- -

Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95% of the training set’s variance: -

- - -
-
-
-
-
-
pca = PCA()
-pca.fit(X)
-cumsum = np.cumsum(pca.explained_variance_ratio_)
-d = np.argmax(cumsum >= 0.95) + 1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

- - -
-
-
-
-
-
pca = PCA(n_components=0.95)
-X_reduced = pca.fit_transform(X)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Incremental PCA

- -

One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). -

-

Randomized PCA

- -

Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -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 -previous algorithms when \( d \) is much smaller than \( n \). -

-

Kernel PCA

- -

The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

- - -
-
-
-
-
-
from sklearn.decomposition import KernelPCA
-rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
-X_reduced = rbf_pca.fit_transform(X)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-

Other techniques

- -

There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.

- -

Here are some of the most popular:

-
    -

  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • -

  • 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.
  • -

  • 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).
  • -

  • 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.
  • -
-
- - - -
-
- - - - - - - - - - - - - diff --git a/doc/src/week43/week43-solarized.html b/doc/src/week43/week43-solarized.html deleted file mode 100644 index 730ceb964..000000000 --- a/doc/src/week43/week43-solarized.html +++ /dev/null @@ -1,3374 +0,0 @@ - - - - - - - -Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis - - - - - - - - - - - - - - - - - - -
-

Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -
-
-
-

Nov 2, 2021

-
-
- -









-

Plans for week 43

- -
    -
  • Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks
  • - -
  • Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
  • - -
- - - - - - -









-

Reading Recommendations

- -
    -
  • Goodfellow et al, chapter 10 on Recurrent NNs, chapters 11 and 12 on various practicalities around deep learning are also recommended.
  • -
  • Aurelien Geron, chapter 14 on RNNs.
  • -
-









-

Summary on Deep Learning Methods

- -

We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).

- -

The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images.

- -









-

CNNs in brief

- -

In summary:

- -
    -
  • 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)
  • -
  • There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
  • -
  • Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
  • -
  • Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
  • -
  • Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
  • -
-

For more material on convolutional networks, we strongly recommend -the course -IN5400 – Machine Learning for Image Analysis -and the slides of CS231 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. -

- -

However, both standard feed forwards networks and CNNs perform well on data with unknown length.

- -

This is where recurrent nueral networks (RNNs) come to our rescue.

- -









-

Recurrent neural networks: Overarching view

- -

Till now our focus has been, including convolutional neural networks -as well, on feedforward neural networks. The output or the activations -flow only in one direction, from the input layer to the output layer. -

- -

A recurrent neural network (RNN) looks very much like a feedforward -neural network, except that it also has connections pointing -backward. -

- -

RNNs are used to analyze time series data such as stock prices, and -tell you when to buy or sell. In autonomous driving systems, they can -anticipate car trajectories and help avoid accidents. More generally, -they can work on sequences of arbitrary lengths, rather than on -fixed-sized inputs like all the nets we have discussed so far. For -example, they can take sentences, documents, or audio samples as -input, making them extremely useful for natural language processing -systems such as automatic translation and speech-to-text. -

- -









-

Set up of an RNN

- -

More to text to be added

- -









-

A simple example

- - - -
-
-
-
-
-
# Start importing packages
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-import tensorflow as tf
-from tensorflow.keras import datasets, layers, models
-from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Model, Sequential 
-from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
-from tensorflow.keras import optimizers     
-from tensorflow.keras import regularizers           
-from tensorflow.keras.utils import to_categorical 
-
-
-
-# convert into dataset matrix
-def convertToMatrix(data, step):
- X, Y =[], []
- for i in range(len(data)-step):
-  d=i+step  
-  X.append(data[i:d,])
-  Y.append(data[d,])
- return np.array(X), np.array(Y)
-
-step = 4
-N = 1000    
-Tp = 800    
-
-t=np.arange(0,N)
-x=np.sin(0.02*t)+2*np.random.rand(N)
-df = pd.DataFrame(x)
-df.head()
-
-plt.plot(df)
-plt.show()
-
-values=df.values
-train,test = values[0:Tp,:], values[Tp:N,:]
-
-# add step elements into train and test
-test = np.append(test,np.repeat(test[-1,],step))
-train = np.append(train,np.repeat(train[-1,],step))
- 
-trainX,trainY =convertToMatrix(train,step)
-testX,testY =convertToMatrix(test,step)
-trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
-testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
-
-model = Sequential()
-model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu"))
-model.add(Dense(8, activation="relu")) 
-model.add(Dense(1))
-model.compile(loss='mean_squared_error', optimizer='rmsprop')
-model.summary()
-
-model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)
-trainPredict = model.predict(trainX)
-testPredict= model.predict(testX)
-predicted=np.concatenate((trainPredict,testPredict),axis=0)
-
-trainScore = model.evaluate(trainX, trainY, verbose=0)
-print(trainScore)
-
-index = df.index.values
-plt.plot(index,df)
-plt.plot(index,predicted)
-plt.axvline(df.index[Tp], c="r")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

An extrapolation example

- -

The following code provides an example of how recurrent neural -networks can be used to extrapolate to unknown values of physics data -sets. Specifically, the data sets used in this program come from -a quantum mechanical many-body calculation of energies as functions of the number of particles. -

- - - -
-
-
-
-
-
# For matrices and calculations
-import numpy as np
-# For machine learning (backend for keras)
-import tensorflow as tf
-# User-friendly machine learning library
-# Front end for TensorFlow
-import tensorflow.keras
-# Different methods from Keras needed to create an RNN
-# This is not necessary but it shortened function calls 
-# that need to be used in the code.
-from tensorflow.keras import datasets, layers, models
-from tensorflow.keras.layers import Input
-from tensorflow.keras import regularizers
-from tensorflow.keras.models import Model, Sequential
-from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-from timeit import default_timer as timer
-# For plotting
-import matplotlib.pyplot as plt
-
-
-# The data set
-datatype='VaryDimension'
-X_tot = np.arange(2, 42, 2)
-y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
-	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
-	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Formatting the Data

- -

The way the recurrent neural networks are trained in this program -differs from how machine learning algorithms are usually trained. -Typically a machine learning algorithm is trained by learning the -relationship between the x data and the y data. In this program, the -recurrent neural network will be trained to recognize the relationship -in a sequence of y values. This is type of data formatting is -typically used time series forcasting, but it can also be used in any -extrapolation (time series forecasting is just a specific type of -extrapolation along the time axis). This method of data formatting -does not use the x data and assumes that the y data are evenly spaced. -

- -

For a standard machine learning algorithm, the training data has the -form of (x,y) so the machine learning algorithm learns to assiciate a -y value with a given x value. This is useful when the test data has x -values within the same range as the training data. However, for this -application, the x values of the test data are outside of the x values -of the training data and the traditional method of training a machine -learning algorithm does not work as well. For this reason, the -recurrent neural network is trained on sequences of y values of the -form ((y1, y2), y3), so that the network is concerned with learning -the pattern of the y data and not the relation between the x and y -data. As long as the pattern of y data outside of the training region -stays relatively stable compared to what was inside the training -region, this method of training can produce accurate extrapolations to -y values far removed from the training data set. -

- - - - - - - - - - -
-
-
-
-
-
# FORMAT_DATA
-def format_data(data, length_of_sequence = 2):  
-    """
-        Inputs:
-            data(a numpy array): the data that will be the inputs to the recurrent neural
-                network
-            length_of_sequence (an int): the number of elements in one iteration of the
-                sequence patter.  For a function approximator use length_of_sequence = 2.
-        Returns:
-            rnn_input (a 3D numpy array): the input data for the recurrent neural network.  Its
-                dimensions are length of data - length of sequence, length of sequence, 
-                dimnsion of data
-            rnn_output (a numpy array): the training data for the neural network
-        Formats data to be used in a recurrent neural network.
-    """
-
-    X, Y = [], []
-    for i in range(len(data)-length_of_sequence):
-        # Get the next length_of_sequence elements
-        a = data[i:i+length_of_sequence]
-        # Get the element that immediately follows that
-        b = data[i+length_of_sequence]
-        # Reshape so that each data point is contained in its own array
-        a = np.reshape (a, (len(a), 1))
-        X.append(a)
-        Y.append(b)
-    rnn_input = np.array(X)
-    rnn_output = np.array(Y)
-
-    return rnn_input, rnn_output
-
-
-# ## Defining the Recurrent Neural Network Using Keras
-# 
-# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.
-
-def rnn(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with one hidden layer and returns the model.
-    """
-    # Number of neurons in the input and output layers
-    in_out_neurons = 1
-    # Number of neurons in the hidden layer
-    hidden_neurons = 200
-    # Define the input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons))  
-    # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to 
-    # the network immediately after the input layer
-    rnn = SimpleRNN(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN")(inp)
-    # Define the output layer as a dense neural network layer (standard neural network layer)
-    #and add it to the network immediately after the hidden layer.
-    dens = Dense(in_out_neurons,name="dense")(rnn)
-    # Create the machine learning model starting with the input layer and ending with the 
-    # output layer
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the machine learning model using the mean squared error function as the loss 
-    # function and an Adams optimizer.
-    model.compile(loss="mean_squared_error", optimizer="adam")  
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Predicting New Points With A Trained Recurrent Neural Network

- - - -
-
-
-
-
-
def test_rnn (x1, y_test, plot_min, plot_max):
-    """
-        Inputs:
-            x1 (a list or numpy array): The complete x component of the data set
-            y_test (a list or numpy array): The complete y component of the data set
-            plot_min (an int or float): the smallest x value used in the training data
-            plot_max (an int or float): the largest x valye used in the training data
-        Returns:
-            None.
-        Uses a trained recurrent neural network model to predict future points in the 
-        series.  Computes the MSE of the predicted data set from the true data set, saves
-        the predicted data set to a csv file, and plots the predicted and true data sets w
-        while also displaying the data range used for training.
-    """
-    # Add the training data as the first dim points in the predicted data array as these
-    # are known values.
-    y_pred = y_test[:dim].tolist()
-    # Generate the first input to the trained recurrent neural network using the last two 
-    # points of the training data.  Based on how the network was trained this means that it
-    # will predict the first point in the data set after the training data.  All of the 
-    # brackets are necessary for Tensorflow.
-    next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])
-    # Save the very last point in the training data set.  This will be used later.
-    last = [y_test[dim-1]]
-
-    # Iterate until the complete data set is created.
-    for i in range (dim, len(y_test)):
-        # Predict the next point in the data set using the previous two points.
-        next = model.predict(next_input)
-        # Append just the number of the predicted data set
-        y_pred.append(next[0][0])
-        # Create the input that will be used to predict the next data point in the data set.
-        next_input = np.array([[last, next[0]]], dtype=np.float64)
-        last = next
-
-    # Print the mean squared error between the known data set and the predicted data set.
-    print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())
-    # Save the predicted data set as a csv file for later use
-    name = datatype + 'Predicted'+str(dim)+'.csv'
-    np.savetxt(name, y_pred, delimiter=',')
-    # Plot the known data set and the predicted data set.  The red box represents the region that was used
-    # for the training data.
-    fig, ax = plt.subplots()
-    ax.plot(x1, y_test, label="true", linewidth=3)
-    ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4)
-    ax.legend()
-    # Created a red region to represent the points used in the training data.
-    ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')
-    plt.show()
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-model = rnn(length_of_sequences = rnn_input.shape[1])
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Other Things to Try

- -

Changing the size of the recurrent neural network and its parameters -can drastically change the results you get from the model. The below -code takes the simple recurrent neural network from above and adds a -second hidden layer, changes the number of neurons in the hidden -layer, and explicitly declares the activation function of the hidden -layers to be a sigmoid function. The loss function and optimizer can -also be changed but are kept the same as the above network. These -parameters can be tuned to provide the optimal result from the -network. For some ideas on how to improve the performance of a -recurrent neural network. -

- - - -
-
-
-
-
-
def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with two hidden layers and returns the model.
-    """
-    # Number of neurons in the input and output layers
-    in_out_neurons = 1
-    # Number of neurons in the hidden layer, increased from the first network
-    hidden_neurons = 500
-    # Define the input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons))  
-    # Create two hidden layers instead of one hidden layer.  Explicitly set the activation
-    # function to be the sigmoid function (the default value is hyperbolic tangent)
-    rnn1 = SimpleRNN(hidden_neurons, 
-                    return_sequences=True,  # This needs to be True if another hidden layer is to follow
-                    stateful = stateful, activation = 'sigmoid',
-                    name="RNN1")(inp)
-    rnn2 = SimpleRNN(hidden_neurons, 
-                    return_sequences=False, activation = 'sigmoid',
-                    stateful = stateful,
-                    name="RNN2")(rnn1)
-    # Define the output layer as a dense neural network layer (standard neural network layer)
-    #and add it to the network immediately after the hidden layer.
-    dens = Dense(in_out_neurons,name="dense")(rnn2)
-    # Create the machine learning model starting with the input layer and ending with the 
-    # output layer
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the machine learning model using the mean squared error function as the loss 
-    # function and an Adams optimizer.
-    model.compile(loss="mean_squared_error", optimizer="adam")  
-    return model
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-model = rnn_2layers(length_of_sequences = 2)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Other Types of Recurrent Neural Networks

- -

Besides a simple recurrent neural network layer, there are two other -commonly used types of recurrent neural network layers: Long Short -Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short -introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b -and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b. -

- -

The first network created below is similar to the previous network, -but it replaces the SimpleRNN layers with LSTM layers. The second -network below has two hidden layers made up of GRUs, which are -preceeded by two dense (feeddorward) neural network layers. These -dense layers "preprocess" the data before it reaches the recurrent -layers. This architecture has been shown to improve the performance -of recurrent neural networks (see the link above and also -https://arxiv.org/pdf/1807.02857.pdf. -

- - - -
-
-
-
-
-
def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.
-    """
-    # Number of neurons on the input/output layer and the number of neurons in the hidden layer
-    in_out_neurons = 1
-    hidden_neurons = 250
-    # Input Layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons)) 
-    # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)
-    rnn= LSTM(hidden_neurons, 
-                    return_sequences=True,
-                    stateful = stateful,
-                    name="RNN", use_bias=True, activation='tanh')(inp)
-    rnn1 = LSTM(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN1", use_bias=True, activation='tanh')(rnn)
-    # Output layer
-    dens = Dense(in_out_neurons,name="dense")(rnn1)
-    # Define the midel
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the model
-    model.compile(loss='mean_squared_error', optimizer='adam')  
-    # Return the model
-    return model
-
-def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with four hidden layers (two dense followed by
-        two GRU layers) and returns the model.
-    """    
-    # Number of neurons on the input/output layers and hidden layers
-    in_out_neurons = 1
-    hidden_neurons = 250
-    # Input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons)) 
-    # Hidden Dense (feedforward) layers
-    dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)
-    dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)
-    # Hidden GRU layers
-    rnn1 = GRU(hidden_neurons, 
-                    return_sequences=True,
-                    stateful = stateful,
-                    name="RNN1", use_bias=True)(dnn1)
-    rnn = GRU(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN", use_bias=True)(rnn1)
-    # Output layer
-    dens = Dense(in_out_neurons,name="dense")(rnn)
-    # Define the model
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the mdoel
-    model.compile(loss='mean_squared_error', optimizer='adam')  
-    # Return the model
-    return model
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-# Change the method name to reflect which network you want to use
-model = dnn2_gru2(length_of_sequences = 2)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)
-# 
-# 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.
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-# Reshape the data for Keras specifications
-X_train = X_train.reshape((dim, 1))
-y_train = y_train.reshape((dim, 1))
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-# Set the sequence length to 1 for regular data formatting 
-model = rnn(length_of_sequences = 1)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(X_train, y_train, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict the remaining data points
-X_pred = X_tot[dim:]
-X_pred = X_pred.reshape((len(X_pred), 1))
-y_model = model.predict(X_pred)
-y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))
-
-# Plot the known data set and the predicted data set.  The red box represents the region that was used
-# for the training data.
-fig, ax = plt.subplots()
-ax.plot(X_tot, y_tot, label="true", linewidth=3)
-ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4)
-ax.legend()
-# Created a red region to represent the points used in the training data.
-ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')
-plt.show()
-
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Generative Models

- -

Generative models describe a class of statistical models that are a contrast -to discriminative models. Informally we say that generative models can -generate new data instances while discriminative models discriminate between -different kinds of data instances. A generative model could generate new photos -of animals that look like 'real' animals while a discriminative model could tell -a dog from a cat. More formally, given a data set \( x \) and a set of labels / -targets \( y \). Generative models capture the joint probability \( p(x, y) \), or -just \( p(x) \) if there are no labels, while discriminative models capture the -conditional probability \( p(y | x) \). Discriminative models generally try to draw -boundaries in the data space (often high dimensional), while generative models -try to model how data is placed throughout the space. -

- -

Note: this material is thanks to Linus Ekstrøm.

- -









-

Generative Adversarial Networks

- -

Generative Adversarial Networks are a type of unsupervised machine learning -algorithm proposed by Goodfellow et. al -in 2014 (short and good article). -

- -

The simplest formulation of -the model is based on a game theoretic approach, zero sum game, where we pit -two neural networks against one another. We define two rival networks, one -generator \( g \), and one discriminator \( d \). The generator directly produces -samples -

-$$ -\begin{equation} - x = g(z; \theta^{(g)}) -\label{_auto1} -\end{equation} -$$ - - -









-

Discriminator

-

The discriminator attempts to distinguish between samples drawn from the -training data and samples drawn from the generator. In other words, it tries to -tell the difference between the fake data produced by \( g \) and the actual data -samples we want to do prediction on. The discriminator outputs a probability -value given by -

- -$$ -\begin{equation} - d(x; \theta^{(d)}) -\label{_auto2} -\end{equation} -$$ - -

indicating the probability that \( x \) is a real training example rather than a -fake sample the generator has generated. The simplest way to formulate the -learning process in a generative adversarial network is a zero-sum game, in -which a function -

- -$$ -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) -\label{_auto3} -\end{equation} -$$ - -

determines the reward for the discriminator, while the generator gets the -conjugate reward -

- -$$ -\begin{equation} - -v(\theta^{(g)}, \theta^{(d)}) -\label{_auto4} -\end{equation} -$$ - - -









-

Learning Process

- -

During learning both of the networks maximize their own reward function, so that -the generator gets better and better at tricking the discriminator, while the -discriminator gets better and better at telling the difference between the fake -and real data. The generator and discriminator alternate on which one trains at -one time (i.e. for one epoch). In other words, we keep the generator constant -and train the discriminator, then we keep the discriminator constant to train -the generator and repeat. It is this back and forth dynamic which lets GANs -tackle otherwise intractable generative problems. As the generator improves with - training, the discriminator's performance gets worse because it cannot easily - tell the difference between real and fake. If the generator ends up succeeding - perfectly, the the discriminator will do no better than random guessing i.e. - 50\%. This progression in the training poses a problem for the convergence - criteria for GANs. The discriminator feedback gets less meaningful over time, - if we continue training after this point then the generator is effectively - training on junk data which can undo the learning up to that point. Therefore, - we stop training when the discriminator starts outputting \( 1/2 \) everywhere. -

- -









-

More about the Learning Process

- -

At convergence we have

- -$$ -\begin{equation} - g^* = \underset{g}{\mathrm{argmin}}\hspace{2pt} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\label{_auto5} -\end{equation} -$$ - -

The default choice for \( v \) is

-$$ -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x) - + \mathbb{E}_{x\sim p_\mathrm{model}} - \log (1 - d(x)) -\label{_auto6} -\end{equation} -$$ - -

The main motivation for the design of GANs is that the learning process requires -neither approximate inference (variational autoencoders for example) nor -approximation of a partition function. In the case where -

-$$ -\begin{equation} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\label{_auto7} -\end{equation} -$$ - -

is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is -asymptotically consistent -( Seth Lloyd on QuGANs ). -

- -









-

Additional References

-

This is in -general not the case and it is possible to get situations where the training -process never converges because the generator and discriminator chase one -another around in the parameter space indefinitely. A much deeper discussion on -the currently open research problem of GAN convergence is available -here. To -anyone interested in learning more about GANs it is a highly recommended read. -Direct quote: "In this best-performing formulation, the generator aims to -increase the log probability that the discriminator makes a mistake, rather than -aiming to decrease the log probability that the discriminator makes the correct -prediction." Another interesting read -

- -









-

Writing Our First Generative Adversarial Network

-

Let us now move on to actually implementing a GAN in tensorflow. We will study -the performance of our GAN on the MNIST dataset. This code is based on and -adapted from the -google tutorial -

- -

First we import our libraries

- - - -
-
-
-
-
-
import os
-import time
-import numpy as np
-import tensorflow as tf
-import matplotlib.pyplot as plt
-from tensorflow.keras import layers
-from tensorflow.keras.utils import plot_model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define our hyperparameters and import our data the usual way

- - - -
-
-
-
-
-
BUFFER_SIZE = 60000
-BATCH_SIZE = 256
-EPOCHS = 30
-
-data = tf.keras.datasets.mnist.load_data()
-(train_images, train_labels), (test_images, test_labels) = data
-train_images = np.reshape(train_images, (train_images.shape[0],
-                                         28,
-                                         28,
-                                         1)).astype('float32')
-
-# we normalize between -1 and 1
-train_images = (train_images - 127.5) / 127.5
-training_dataset = tf.data.Dataset.from_tensor_slices(
-                      train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

MNIST and GANs

- -

Let's have a quick look

- - - -
-
-
-
-
-
plt.imshow(train_images[0], cmap='Greys')
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we define our two models. This is where the 'magic' happens. There are a -huge amount of possible formulations for both models. A lot of engineering and -trial and error can be done here to try to produce better performing models. For -more advanced GANs this is by far the step where you can 'make or break' a -model. -

- -

We start with the generator. As stated in the introductory text the generator -\( g \) upsamples from a random sample to the shape of what we want to predict. In -our case we are trying to predict MNIST images (\( 28\times 28 \) pixels). -

- - - -
-
-
-
-
-
def generator_model():
-    """
-    The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to
-    produce an image from a random seed. We start with a Dense layer taking this
-    random sample as an input and subsequently upsample through multiple
-    convolutional layers.
-    """
-
-    # we define our model
-    model = tf.keras.Sequential()
-
-
-    # adding our input layer. Dense means that every neuron is connected and
-    # the input shape is the shape of our random noise. The units need to match
-    # in some sense the upsampling strides to reach our desired output shape.
-    # we are using 100 random numbers as our seed
-    model.add(layers.Dense(units=7*7*BATCH_SIZE,
-                           use_bias=False,
-                           input_shape=(100, )))
-    # we normalize the output form the Dense layer
-    model.add(layers.BatchNormalization())
-    # and add an activation function to our 'layer'. LeakyReLU avoids vanishing
-    # gradient problem
-    model.add(layers.LeakyReLU())
-    model.add(layers.Reshape((7, 7, BATCH_SIZE)))
-    assert model.output_shape == (None, 7, 7, BATCH_SIZE)
-    # even though we just added four keras layers we think of everything above
-    # as 'one' layer
-
-    # next we add our upscaling convolutional layers
-    model.add(layers.Conv2DTranspose(filters=128,
-                                     kernel_size=(5, 5),
-                                     strides=(1, 1),
-                                     padding='same',
-                                     use_bias=False))
-    model.add(layers.BatchNormalization())
-    model.add(layers.LeakyReLU())
-    assert model.output_shape == (None, 7, 7, 128)
-
-    model.add(layers.Conv2DTranspose(filters=64,
-                                     kernel_size=(5, 5),
-                                     strides=(2, 2),
-                                     padding='same',
-                                     use_bias=False))
-    model.add(layers.BatchNormalization())
-    model.add(layers.LeakyReLU())
-    assert model.output_shape == (None, 14, 14, 64)
-
-    model.add(layers.Conv2DTranspose(filters=1,
-                                     kernel_size=(5, 5),
-                                     strides=(2, 2),
-                                     padding='same',
-                                     use_bias=False,
-                                     activation='tanh'))
-    assert model.output_shape == (None, 28, 28, 1)
-
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

And there we have our 'simple' generator model. Now we move on to defining our -discriminator model \( d \), which is a convolutional neural network based image -classifier. -

- - - -
-
-
-
-
-
def discriminator_model():
-    """
-    The discriminator is a convolutional neural network based image classifier
-    """
-
-    # we define our model
-    model = tf.keras.Sequential()
-    model.add(layers.Conv2D(filters=64,
-                            kernel_size=(5, 5),
-                            strides=(2, 2),
-                            padding='same',
-                            input_shape=[28, 28, 1]))
-    model.add(layers.LeakyReLU())
-    # adding a dropout layer as you do in conv-nets
-    model.add(layers.Dropout(0.3))
-
-
-    model.add(layers.Conv2D(filters=128,
-                            kernel_size=(5, 5),
-                            strides=(2, 2),
-                            padding='same'))
-    model.add(layers.LeakyReLU())
-    # adding a dropout layer as you do in conv-nets
-    model.add(layers.Dropout(0.3))
-
-    model.add(layers.Flatten())
-    model.add(layers.Dense(1))
-
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Other Models

-

Let us take a look at our models. Note: double click images for bigger view.

- - - -
-
-
-
-
-
generator = generator_model()
-plot_model(generator, show_shapes=True, rankdir='LR')
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
discriminator = discriminator_model()
-plot_model(discriminator, show_shapes=True, rankdir='LR')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we need a few helper objects we will use in training

- - - -
-
-
-
-
-
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
-generator_optimizer = tf.keras.optimizers.Adam(1e-4)
-discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

The first object, cross_entropy is our loss function and the two others are -our optimizers. Notice we use the same learning rate for both \( g \) and \( d \). This -is because they need to improve their accuracy at approximately equal speeds to -get convergence (not necessarily exactly equal). Now we define our loss -functions -

- - - -
-
-
-
-
-
def generator_loss(fake_output):
-    loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
-    return loss
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
def discriminator_loss(real_output, fake_output):
-    real_loss = cross_entropy(tf.ones_like(real_output), real_output)
-    fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)
-    total_loss = real_loss + fake_loss
-
-    return total_loss
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define a kind of seed to help us compare the learning process over -multiple training epochs. -

- - - -
-
-
-
-
-
noise_dimension = 100
-n_examples_to_generate = 16
-seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Training Step

- -

Now we have everything we need to define our training step, which we will apply -for every step in our training loop. Notice the @tf.function flag signifying -that the function is tensorflow 'compiled'. Removing this flag doubles the -computation time. -

- - - -
-
-
-
-
-
@tf.function
-def train_step(images):
-    noise = tf.random.normal([BATCH_SIZE, noise_dimension])
-
-    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
-        generated_images = generator(noise, training=True)
-
-        real_output = discriminator(images, training=True)
-        fake_output = discriminator(generated_images, training=True)
-
-        gen_loss = generator_loss(fake_output)
-        disc_loss = discriminator_loss(real_output, fake_output)
-
-    gradients_of_generator = gen_tape.gradient(gen_loss,
-                                            generator.trainable_variables)
-    gradients_of_discriminator = disc_tape.gradient(disc_loss,
-                                            discriminator.trainable_variables)
-    generator_optimizer.apply_gradients(zip(gradients_of_generator,
-                                            generator.trainable_variables))
-    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,
-                                            discriminator.trainable_variables))
-
-    return gen_loss, disc_loss
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define a helper function to produce an output over our training epochs -to see the predictive progression of our generator model. Note: I am including -this code here, but comment it out in the training loop. -

- - -
-
-
-
-
-
def generate_and_save_images(model, epoch, test_input):
-    # we're making inferences here
-    predictions = model(test_input, training=False)
-
-    fig = plt.figure(figsize=(4, 4))
-
-    for i in range(predictions.shape[0]):
-        plt.subplot(4, 4, i+1)
-        plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
-        plt.axis('off')
-
-    plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')
-    plt.close()
-    #plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Checkpoints

-

Setting up checkpoints to periodically save our model during training so that -everything is not lost even if the program were to somehow terminate while -training. -

- - - -
-
-
-
-
-
# Setting up checkpoints to save model during training
-checkpoint_dir = './training_checkpoints'
-checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')
-checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
-                            discriminator_optimizer=discriminator_optimizer,
-                            generator=generator,
-                            discriminator=discriminator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we define our training loop

- - - -
-
-
-
-
-
def train(dataset, epochs):
-    generator_loss_list = []
-    discriminator_loss_list = []
-
-    for epoch in range(epochs):
-        start = time.time()
-
-        for image_batch in dataset:
-            gen_loss, disc_loss = train_step(image_batch)
-            generator_loss_list.append(gen_loss.numpy())
-            discriminator_loss_list.append(disc_loss.numpy())
-
-        #generate_and_save_images(generator, epoch + 1, seed_images)
-
-        if (epoch + 1) % 15 == 0:
-            checkpoint.save(file_prefix=checkpoint_prefix)
-
-        print(f'Time for epoch {epoch} is {time.time() - start}')
-
-    #generate_and_save_images(generator, epochs, seed_images)
-
-    loss_file = './data/lossfile.txt'
-    with open(loss_file, 'w') as outfile:
-        outfile.write(str(generator_loss_list))
-        outfile.write('\n')
-        outfile.write('\n')
-        outfile.write(str(discriminator_loss_list))
-        outfile.write('\n')
-        outfile.write('\n')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

To train simply call this function. Warning: this might take a long time so -there is a folder of a pretrained network already included in the repository. -

- - - -
-
-
-
-
-
train(train_dataset, EPOCHS)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

And here is the result of training our model for 100 epochs

- - -

- -

Now to avoid having to train and everything, which will take a while depending -on your computer setup we now load in the model which produced the above gif. -

- - - -
-
-
-
-
-
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
-restored_generator = checkpoint.generator
-restored_discriminator = checkpoint.discriminator
-
-print(restored_generator)
-print(restored_discriminator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Exploring the Latent Space

- -

We have successfully loaded in our latest model. Let us now play around a bit -and see what kind of things we can learn about this model. Our generator takes -an array of 100 numbers. One idea can be to try to systematically change our -input. Let us try and see what we get -

- - - -
-
-
-
-
-
def generate_latent_points(number=100, scale_means=1, scale_stds=1):
-    latent_dim = 100
-    means = scale_means * tf.linspace(-1, 1, num=latent_dim)
-    stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)
-    latent_space_value_range = tf.random.normal([number, latent_dim],
-                                                means,
-                                                stds,
-                                                dtype=tf.float64)
-
-    return latent_space_value_range
-
-def generate_images(latent_points):
-    # notice we set training to false because we are making inferences
-    generated_images = restored_generator.predict(latent_points)
-
-    return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
def plot_result(generated_images, number=100):
-    # obviously this assumes sqrt number is an int
-    fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),
-                            figsize=(10, 10))
-
-    for i in range(int(np.sqrt(number))):
-        for j in range(int(np.sqrt(number))):
-            axs[i, j].imshow(generated_images[i*j], cmap='Greys')
-            axs[i, j].axis('off')
-
-    plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
generated_images = generate_images(generate_latent_points())
-plot_result(generated_images)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Getting Results

-

We see that the generator generates images that look like MNIST -numbers: \( 1, 4, 7, 9 \). Let's try to tweak it a bit more to see if we are able -to generate a similar plot where we generate every MNIST number. Let us now try -to 'move' a bit around in the latent space. Note: decrease the plot number if -these following cells take too long to run on your computer. -

- - - -
-
-
-
-
-
plot_number = 225
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=5,
-                                                          scale_stds=1))
-plot_result(generated_images, number=plot_number)
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=-5,
-                                                          scale_stds=1))
-plot_result(generated_images, number=plot_number)
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=1,
-                                                          scale_stds=5))
-plot_result(generated_images, number=plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Again, we have found something interesting. Moving around using our means -takes us from digit to digit, while moving around using our standard -deviations seem to increase the number of different digits! In the last image -above, we can barely make out every MNIST digit. Let us make on last plot using -this information by upping the standard deviation of our Gaussian noises. -

- - - -
-
-
-
-
-
plot_number = 400
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=1,
-                                                          scale_stds=10))
-plot_result(generated_images, number=plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

A pretty cool result! We see that our generator indeed has learned a -distribution which qualitatively looks a whole lot like the MNIST dataset. -

- -









-

Interpolating Between MNIST Digits

-

Another interesting way to explore the latent space of our generator model is by -interpolating between the MNIST digits. This section is largely based on -this excellent blogpost -by Jason Brownlee. -

- -

So let us start by defining a function to interpolate between two points in the -latent space. -

- - - -
-
-
-
-
-
def interpolation(point_1, point_2, n_steps=10):
-    ratios = np.linspace(0, 1, num=n_steps)
-    vectors = []
-    for i, ratio in enumerate(ratios):
-        vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))
-
-    return tf.stack(vectors)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we have all we need to do our interpolation analysis.

- - - -
-
-
-
-
-
plot_number = 100
-latent_points = generate_latent_points(number=plot_number)
-results = None
-for i in range(0, 2*np.sqrt(plot_number), 2):
-    interpolated = interpolation(latent_points[i], latent_points[i+1])
-    generated_images = generate_images(interpolated)
-
-    if results is None:
-        results = generated_images
-    else:
-        results = tf.stack((results, generated_images))
-
-plot_results(results, plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Basic ideas of the Principal Component Analysis (PCA)

- -

The principal component analysis deals with the problem of fitting a -low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than -the total dimension \( D \) of the problem at hand (our data -set). Mathematically it can be formulated as a statistical problem or -a geometric problem. In our discussion of the theorem for the -classical PCA, we will stay with a statistical approach. -Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable. -

- -

We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition)

-
    -
  • Each data point is determined by \( p \) extrinsic (measurement) variables
  • -
  • We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?
  • -
  • If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
  • -
-

A good read is for example Vidal, Ma and Sastry.

- -









-

Introducing the Covariance and Correlation functions

- -

Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities -

- -

Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as -

-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ - \end{bmatrix}, -$$ - -

where for example

-$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -$$ - -

With this definition and recalling that the variance is defined as

-$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ - -

we can rewrite the covariance matrix as

-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ - - -









-

More on the covariance

-

The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function -

- -$$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. -$$ - -

The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as -

- -$$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ - \end{bmatrix}, -$$ - -

In the above example this is the function we constructed using pandas.

- -









-

Reminding ourselves about Linear Regression

-

In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression -we defined the design/feature matrix \( \boldsymbol{X} \) as -

- -$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ - -

with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -

-$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ - -

with a given vector

-$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ - - -









-

Simple Example

-

With these definitions, we can now rewrite our \( 2\times 2 \) -correlation/covariance matrix in terms of a moe general design/feature -matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) -covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) -

- -$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\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}]\\ -\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}]\\ -\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}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\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}]\\ -\end{bmatrix}, -$$ - - -









-

The Correlation Matrix

- -

and the correlation matrix

-$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -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}]\\ -\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}]\\ -\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}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\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\\ -\end{bmatrix}, -$$ - - -









-

Numpy Functionality

- -

The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) -

- -$$ -\boldsymbol{W}^T = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -$$ - -

which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. -

- - - -
-
-
-
-
-
# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Correlation Matrix again

- -

The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -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). -

- - - -
-
-
-
-
-
import numpy as np
-n = 100
-# define two vectors                                                                                           
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors                                                                                   
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. -

- -

The above procedure with numpy can be made more compact if we use pandas.

- -









-

Using Pandas

- -

We whow here how we can set up the correlation matrix using pandas, as done in this simple code

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

And then the Franke Function

- -

We expand this model to the Franke function discussed above.

- - - -
-
-
-
-
-
# Common imports
-import numpy as np
-import pandas as pd
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree \( n \)). We would however not include the intercept -and wee can simply -drop these elements and construct a correlation -matrix without them by centering our matrix elements by subtracting the mean of each column. -

- -









-

Lnks with the Design Matrix

- -

We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as

-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. -$$ - -

To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)

-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ -\end{bmatrix}. -$$ - - -









-

Computing the Expectation Values

- -

If we then compute the expectation value

-$$ -\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -$$ - -

which is just

-$$ -\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] \\ - \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ - \end{bmatrix}, -$$ - -

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} \).

- -

It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).

- -









-

Towards the PCA theorem

- -

We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as

-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. -$$ - -

Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). -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} \). -

- -

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}] \).

- -

That is we have

-$$ -\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}, -$$ - -

since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have

-$$ -\boldsymbol{S}\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}, -$$ - -

and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that

- -$$ -\boldsymbol{S}_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}_i. -$$ - - -









-

More on the PCA Theorem

- -

In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). -

- -

The eigenvalues tell us then how much we need to stretch the -corresponding eigenvectors. Dimensions with large eigenvalues have -thus large variations (large variance) and define therefore useful -dimensions. The data points are more spread out in the direction of -these eigenvectors. Smaller eigenvalues mean on the other hand that -the corresponding eigenvectors are shrunk accordingly and the data -points are tightly bunched together and there is not much variation in -these specific directions. Hopefully then we could leave it out -dimensions where the eigenvalues are very small. If \( p \) is very large, -we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) -features/predictors. -

- -









-

The Algorithm before theorem

- -

Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here.

-
    -
  • 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.
  • -
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ - -
    -
  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • -
  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}^T\overline{\boldsymbol{X}}] \).
  • -
  • 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}] \).
  • -
  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • -
  • 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.
  • -
-









-

Writing our own PCA code

- -

We will use a simple example first with two-dimensional data -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): -

-$$ -\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ -2 & 2 -\end{bmatrix} -$$ - -

Note that the mean refers to each column of data. -We will generate \( n = 10000 \) points \( X = \{ x_1, \ldots, x_N \} \) from -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. -

- -









-

Implementing it

-

The following Python code aids in setting up the data and writing out the design matrix. -Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). -

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-n = 10000
-mean = (-1, 2)
-cov = [[4, 2], [2, 2]]
-X = np.random.multivariate_normal(mean, cov, n)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we are going to implement the PCA algorithm. We will break it down into various substeps.

- -









-

First Step

- -

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

-$$ -\mu_n = \frac{1}{n} \sum_{i=1}^n x_i -$$ - -

and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form

-$$ -\bar{x}_i = x_i - \mu_n. -$$ - -

When you are done with these steps, print out \( \mu_n \) to verify it is -close to \( \mu \) and plot your mean centered data to verify it is -centered at the origin! -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. -

- - -
-
-
-
-
-
df = pd.DataFrame(X)
-# Pandas does the centering for us
-df = df -df.mean()
-# we center it ourselves
-X_centered = X - X.mean(axis=0)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Scaling

-

Alternatively, we could use the functions we discussed -earlier for scaling the data set. That is, we could have used the -StandardScaler function in Scikit-Learn, a function which ensures -that for each feature/predictor we study the mean value is zero and -the variance is one (every column in the design/feature matrix). You -would then not get the same results, since we divide by the -variance. The diagonal covariance matrix elements will then be one, -while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our -specific case. -

- -









-

Centered Data

- -

Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation

-$$ -\begin{equation*} -\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) -\end{equation*} -$$ - -

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 \). -We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows -

- - -
-
-
-
-
-
print(df.cov())
-print(np.cov(X_centered.T))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

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. -Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. -

- - -
-
-
-
-
-
# extract the relevant columns from the centered design matrix of dim n x 2
-x = X_centered[:,0]
-y = X_centered[:,1]
-Cov = np.zeros((2,2))
-Cov[0,1] = np.sum(x.T@y)/(n-1.0)
-Cov[0,0] = np.sum(x.T@x)/(n-1.0)
-Cov[1,1] = np.sum(y.T@y)/(n-1.0)
-Cov[1,0]= Cov[0,1]
-print("Centered covariance using own code")
-print(Cov)
-plt.plot(x, y, 'x')
-plt.axis('equal')
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Exploring

- -

Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. -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. -

- -









-

Diagonalize the sample covariance matrix to obtain the principal components

- -

Now we are ready to solve for the principal components! To do so we -diagonalize the sample covariance matrix \( \Sigma \). We can use the -function np.linalg.eig to do so. It will return the eigenvalues and -eigenvectors of \( \Sigma \). Once we have these we can perform the -following tasks: -

- -
    -
  • We compute the percentage of the total variance captured by the first principal component
  • -
  • We plot the mean centered data and lines along the first and second principal components
  • -
  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • -
  • Finally, we approximate the data as
  • -
-$$ -\begin{equation*} -x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 -\end{equation*} -$$ - -

where \( v_0 \) is the first principal component.

- -









-

Collecting all Steps

- -

Collecting all these steps we can write our own PCA function and -compare this with the functionality included in Scikit-Learn. -

- -

The code here outlines some of the elements we could include in the -analysis. Feel free to extend upon this in order to address the above -questions. -

- - - -
-
-
-
-
-
# diagonalize and obtain eigenvalues, not necessarily sorted
-EigValues, EigVectors = np.linalg.eig(Cov)
-# sort eigenvectors and eigenvalues
-#permute = EigValues.argsort()
-#EigValues = EigValues[permute]
-#EigVectors = EigVectors[:,permute]
-print("Eigenvalues of Covariance matrix")
-for i in range(2):
-    print(EigValues[i])
-FirstEigvector = EigVectors[:,0]
-SecondEigvector = EigVectors[:,1]
-print("First eigenvector")
-print(FirstEigvector)
-print("Second eigenvector")
-print(SecondEigvector)
-#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2Dsl = pca.fit_transform(X)
-print("Eigenvector of largest eigenvalue")
-print(pca.components_.T[:, 0])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

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?

- -









-

Classical PCA Theorem

- -

We assume now that we have a design matrix \( \boldsymbol{X} \) which has been -centered as discussed above. For the sake of simplicity we skip the -overline symbol. The matrix is defined in terms of the various column -vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension -\( \boldsymbol{x}\in {\mathbb{R}}^{n} \). -

- -

The PCA theorem states that minimizing the above reconstruction error -corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which -diagonalizes the empirical covariance(correlation) matrix. The optimal -low-dimensional encoding of the data is then given by a set of vectors -\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the -orthogonal projection of the data onto the columns spanned by the -eigenvectors of the covariance(correlations matrix). -

- -









-

The PCA Theorem

- -

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

- -

We are almost there, we have obtained a relation between minimizing -the reconstruction error and the variance and the covariance -matrix. Minimizing the error is equivalent to maximizing the variance -of the projected data. -

- -

We could trivially maximize the variance of the projection (and -thereby minimize the error in the reconstruction function) by letting -the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we -want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by -\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a -Lagrange multiplier we can then in turn maximize -

- -$$ -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). -$$ - -

Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain

- -$$ -\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, -$$ - -

meaning that

-$$ -\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. -$$ - -

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

-$$ -\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. -$$ - -

If we want to maximize the variance (minimize the construction error) -we simply pick the eigenvector of the covariance matrix with the -largest eigenvalue. This establishes the link between the minimization -of the reconstruction function \( J \) in terms of an orthogonal matrix -and the maximization of the variance and thereby the covariance of our -observations encoded in the design/feature matrix \( \boldsymbol{X} \). -

- -

The proof -for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be -established by applying the above arguments and using the fact that -our basis of eigenvectors is orthogonal, see Murphy chapter -12.2. The -discussion in chapter 12.2 of Murphy's text has also a nice link with -the Singular Value Decomposition theorem. For categorical data, see -chapter 12.4 and discussion therein. -

- -

For more details, see for example Vidal, Ma and Sastry, chapter 2.

- -









- - -

For a detailed demonstration of the geometric interpretation, see Vidal, Ma and Sastry, section 2.1.2.

- -

Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. -

- -

The following Python code uses NumPy’s svd() function to obtain all the principal components of the -training set, then extracts the first two principal components. First we center the data using either pandas or our own code -

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-from IPython.display import display
-np.random.seed(100)
-# setting up a 10 x 5 vanilla matrix 
-rows = 10
-cols = 5
-X = np.random.randn(rows,cols)
-df = pd.DataFrame(X)
-# Pandas does the centering for us
-df = df -df.mean()
-display(df)
-
-# we center it ourselves
-X_centered = X - X.mean(axis=0)
-# Then check the difference between pandas and our own set up
-print(X_centered-df)
-#Now we do an SVD
-U, s, V = np.linalg.svd(X_centered)
-c1 = V.T[:, 0]
-c2 = V.T[:, 1]
-W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-print(X2D)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. -

- -

Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

- - -
-
-
-
-
-
W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

PCA and scikit-learn

- -

Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -

- - -
-
-
-
-
-
#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D = pca.fit_transform(X)
-print(X2D)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -

- - -
-
-
-
-
-
pca.components_.T[:, 0]
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Another very useful piece of information is the explained variance ratio of each principal component, -available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -

- -









-

Back to the Cancer Data

-

We can now repeat the above but applied to real data, in this case our breast cancer data. -Here we compute performance scores on the training data using logistic regression. -

- - -
-
-
-
-
-
import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-
-logreg = LogisticRegression()
-logreg.fit(X_train, y_train)
-print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
-# We scale the data
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-# Then perform again a log reg fit
-logreg.fit(X_train_scaled, y_train)
-print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
-#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D_train = pca.fit_transform(X_train_scaled)
-# and finally compute the log reg fit and the score on the training data	
-logreg.fit(X2D_train,y_train)
-print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that our training data after the PCA decomposition has a performance similar to the non-scaled data.

- -

Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95% of the training set’s variance: -

- - -
-
-
-
-
-
pca = PCA()
-pca.fit(X)
-cumsum = np.cumsum(pca.explained_variance_ratio_)
-d = np.argmax(cumsum >= 0.95) + 1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

- - -
-
-
-
-
-
pca = PCA(n_components=0.95)
-X_reduced = pca.fit_transform(X)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Incremental PCA

- -

One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). -

-

Randomized PCA

- -

Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -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 -previous algorithms when \( d \) is much smaller than \( n \). -

-

Kernel PCA

- -

The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

- - -
-
-
-
-
-
from sklearn.decomposition import KernelPCA
-rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
-X_reduced = rbf_pca.fit_transform(X)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Other techniques

- -

There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.

- -

Here are some of the most popular:

-
    -
  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • -
  • 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.
  • -
  • 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).
  • -
  • 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.
  • -
- -
- © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week43/week43.html b/doc/src/week43/week43.html deleted file mode 100644 index 6b1437d42..000000000 --- a/doc/src/week43/week43.html +++ /dev/null @@ -1,3451 +0,0 @@ - - - - - - - -Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis - - - - - - - - - - - - - - -
-

Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis

-
- - -
-Morten Hjorth-Jensen [1, 2] -
- -
-[1] Department of Physics, University of Oslo -
-
-[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -
-
-
-

Nov 2, 2021

-
-
- -









-

Plans for week 43

- -
    -
  • Thursday: Summary of Convolutional Neural Networks from week 42 and Recurrent Neural Networks
  • - -
  • Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
  • - -
- - - - - - -









-

Reading Recommendations

- -
    -
  • Goodfellow et al, chapter 10 on Recurrent NNs, chapters 11 and 12 on various practicalities around deep learning are also recommended.
  • -
  • Aurelien Geron, chapter 14 on RNNs.
  • -
-









-

Summary on Deep Learning Methods

- -

We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).

- -

The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images.

- -









-

CNNs in brief

- -

In summary:

- -
    -
  • 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)
  • -
  • There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
  • -
  • Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
  • -
  • Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
  • -
  • Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
  • -
-

For more material on convolutional networks, we strongly recommend -the course -IN5400 – Machine Learning for Image Analysis -and the slides of CS231 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. -

- -

However, both standard feed forwards networks and CNNs perform well on data with unknown length.

- -

This is where recurrent nueral networks (RNNs) come to our rescue.

- -









-

Recurrent neural networks: Overarching view

- -

Till now our focus has been, including convolutional neural networks -as well, on feedforward neural networks. The output or the activations -flow only in one direction, from the input layer to the output layer. -

- -

A recurrent neural network (RNN) looks very much like a feedforward -neural network, except that it also has connections pointing -backward. -

- -

RNNs are used to analyze time series data such as stock prices, and -tell you when to buy or sell. In autonomous driving systems, they can -anticipate car trajectories and help avoid accidents. More generally, -they can work on sequences of arbitrary lengths, rather than on -fixed-sized inputs like all the nets we have discussed so far. For -example, they can take sentences, documents, or audio samples as -input, making them extremely useful for natural language processing -systems such as automatic translation and speech-to-text. -

- -









-

Set up of an RNN

- -

More to text to be added

- -









-

A simple example

- - - -
-
-
-
-
-
# Start importing packages
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-import tensorflow as tf
-from tensorflow.keras import datasets, layers, models
-from tensorflow.keras.layers import Input
-from tensorflow.keras.models import Model, Sequential 
-from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
-from tensorflow.keras import optimizers     
-from tensorflow.keras import regularizers           
-from tensorflow.keras.utils import to_categorical 
-
-
-
-# convert into dataset matrix
-def convertToMatrix(data, step):
- X, Y =[], []
- for i in range(len(data)-step):
-  d=i+step  
-  X.append(data[i:d,])
-  Y.append(data[d,])
- return np.array(X), np.array(Y)
-
-step = 4
-N = 1000    
-Tp = 800    
-
-t=np.arange(0,N)
-x=np.sin(0.02*t)+2*np.random.rand(N)
-df = pd.DataFrame(x)
-df.head()
-
-plt.plot(df)
-plt.show()
-
-values=df.values
-train,test = values[0:Tp,:], values[Tp:N,:]
-
-# add step elements into train and test
-test = np.append(test,np.repeat(test[-1,],step))
-train = np.append(train,np.repeat(train[-1,],step))
- 
-trainX,trainY =convertToMatrix(train,step)
-testX,testY =convertToMatrix(test,step)
-trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
-testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
-
-model = Sequential()
-model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu"))
-model.add(Dense(8, activation="relu")) 
-model.add(Dense(1))
-model.compile(loss='mean_squared_error', optimizer='rmsprop')
-model.summary()
-
-model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)
-trainPredict = model.predict(trainX)
-testPredict= model.predict(testX)
-predicted=np.concatenate((trainPredict,testPredict),axis=0)
-
-trainScore = model.evaluate(trainX, trainY, verbose=0)
-print(trainScore)
-
-index = df.index.values
-plt.plot(index,df)
-plt.plot(index,predicted)
-plt.axvline(df.index[Tp], c="r")
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

An extrapolation example

- -

The following code provides an example of how recurrent neural -networks can be used to extrapolate to unknown values of physics data -sets. Specifically, the data sets used in this program come from -a quantum mechanical many-body calculation of energies as functions of the number of particles. -

- - - -
-
-
-
-
-
# For matrices and calculations
-import numpy as np
-# For machine learning (backend for keras)
-import tensorflow as tf
-# User-friendly machine learning library
-# Front end for TensorFlow
-import tensorflow.keras
-# Different methods from Keras needed to create an RNN
-# This is not necessary but it shortened function calls 
-# that need to be used in the code.
-from tensorflow.keras import datasets, layers, models
-from tensorflow.keras.layers import Input
-from tensorflow.keras import regularizers
-from tensorflow.keras.models import Model, Sequential
-from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-from timeit import default_timer as timer
-# For plotting
-import matplotlib.pyplot as plt
-
-
-# The data set
-datatype='VaryDimension'
-X_tot = np.arange(2, 42, 2)
-y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
-	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
-	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Formatting the Data

- -

The way the recurrent neural networks are trained in this program -differs from how machine learning algorithms are usually trained. -Typically a machine learning algorithm is trained by learning the -relationship between the x data and the y data. In this program, the -recurrent neural network will be trained to recognize the relationship -in a sequence of y values. This is type of data formatting is -typically used time series forcasting, but it can also be used in any -extrapolation (time series forecasting is just a specific type of -extrapolation along the time axis). This method of data formatting -does not use the x data and assumes that the y data are evenly spaced. -

- -

For a standard machine learning algorithm, the training data has the -form of (x,y) so the machine learning algorithm learns to assiciate a -y value with a given x value. This is useful when the test data has x -values within the same range as the training data. However, for this -application, the x values of the test data are outside of the x values -of the training data and the traditional method of training a machine -learning algorithm does not work as well. For this reason, the -recurrent neural network is trained on sequences of y values of the -form ((y1, y2), y3), so that the network is concerned with learning -the pattern of the y data and not the relation between the x and y -data. As long as the pattern of y data outside of the training region -stays relatively stable compared to what was inside the training -region, this method of training can produce accurate extrapolations to -y values far removed from the training data set. -

- - - - - - - - - - -
-
-
-
-
-
# FORMAT_DATA
-def format_data(data, length_of_sequence = 2):  
-    """
-        Inputs:
-            data(a numpy array): the data that will be the inputs to the recurrent neural
-                network
-            length_of_sequence (an int): the number of elements in one iteration of the
-                sequence patter.  For a function approximator use length_of_sequence = 2.
-        Returns:
-            rnn_input (a 3D numpy array): the input data for the recurrent neural network.  Its
-                dimensions are length of data - length of sequence, length of sequence, 
-                dimnsion of data
-            rnn_output (a numpy array): the training data for the neural network
-        Formats data to be used in a recurrent neural network.
-    """
-
-    X, Y = [], []
-    for i in range(len(data)-length_of_sequence):
-        # Get the next length_of_sequence elements
-        a = data[i:i+length_of_sequence]
-        # Get the element that immediately follows that
-        b = data[i+length_of_sequence]
-        # Reshape so that each data point is contained in its own array
-        a = np.reshape (a, (len(a), 1))
-        X.append(a)
-        Y.append(b)
-    rnn_input = np.array(X)
-    rnn_output = np.array(Y)
-
-    return rnn_input, rnn_output
-
-
-# ## Defining the Recurrent Neural Network Using Keras
-# 
-# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.
-
-def rnn(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with one hidden layer and returns the model.
-    """
-    # Number of neurons in the input and output layers
-    in_out_neurons = 1
-    # Number of neurons in the hidden layer
-    hidden_neurons = 200
-    # Define the input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons))  
-    # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to 
-    # the network immediately after the input layer
-    rnn = SimpleRNN(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN")(inp)
-    # Define the output layer as a dense neural network layer (standard neural network layer)
-    #and add it to the network immediately after the hidden layer.
-    dens = Dense(in_out_neurons,name="dense")(rnn)
-    # Create the machine learning model starting with the input layer and ending with the 
-    # output layer
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the machine learning model using the mean squared error function as the loss 
-    # function and an Adams optimizer.
-    model.compile(loss="mean_squared_error", optimizer="adam")  
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Predicting New Points With A Trained Recurrent Neural Network

- - - -
-
-
-
-
-
def test_rnn (x1, y_test, plot_min, plot_max):
-    """
-        Inputs:
-            x1 (a list or numpy array): The complete x component of the data set
-            y_test (a list or numpy array): The complete y component of the data set
-            plot_min (an int or float): the smallest x value used in the training data
-            plot_max (an int or float): the largest x valye used in the training data
-        Returns:
-            None.
-        Uses a trained recurrent neural network model to predict future points in the 
-        series.  Computes the MSE of the predicted data set from the true data set, saves
-        the predicted data set to a csv file, and plots the predicted and true data sets w
-        while also displaying the data range used for training.
-    """
-    # Add the training data as the first dim points in the predicted data array as these
-    # are known values.
-    y_pred = y_test[:dim].tolist()
-    # Generate the first input to the trained recurrent neural network using the last two 
-    # points of the training data.  Based on how the network was trained this means that it
-    # will predict the first point in the data set after the training data.  All of the 
-    # brackets are necessary for Tensorflow.
-    next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])
-    # Save the very last point in the training data set.  This will be used later.
-    last = [y_test[dim-1]]
-
-    # Iterate until the complete data set is created.
-    for i in range (dim, len(y_test)):
-        # Predict the next point in the data set using the previous two points.
-        next = model.predict(next_input)
-        # Append just the number of the predicted data set
-        y_pred.append(next[0][0])
-        # Create the input that will be used to predict the next data point in the data set.
-        next_input = np.array([[last, next[0]]], dtype=np.float64)
-        last = next
-
-    # Print the mean squared error between the known data set and the predicted data set.
-    print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())
-    # Save the predicted data set as a csv file for later use
-    name = datatype + 'Predicted'+str(dim)+'.csv'
-    np.savetxt(name, y_pred, delimiter=',')
-    # Plot the known data set and the predicted data set.  The red box represents the region that was used
-    # for the training data.
-    fig, ax = plt.subplots()
-    ax.plot(x1, y_test, label="true", linewidth=3)
-    ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4)
-    ax.legend()
-    # Created a red region to represent the points used in the training data.
-    ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')
-    plt.show()
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-model = rnn(length_of_sequences = rnn_input.shape[1])
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Other Things to Try

- -

Changing the size of the recurrent neural network and its parameters -can drastically change the results you get from the model. The below -code takes the simple recurrent neural network from above and adds a -second hidden layer, changes the number of neurons in the hidden -layer, and explicitly declares the activation function of the hidden -layers to be a sigmoid function. The loss function and optimizer can -also be changed but are kept the same as the above network. These -parameters can be tuned to provide the optimal result from the -network. For some ideas on how to improve the performance of a -recurrent neural network. -

- - - -
-
-
-
-
-
def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with two hidden layers and returns the model.
-    """
-    # Number of neurons in the input and output layers
-    in_out_neurons = 1
-    # Number of neurons in the hidden layer, increased from the first network
-    hidden_neurons = 500
-    # Define the input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons))  
-    # Create two hidden layers instead of one hidden layer.  Explicitly set the activation
-    # function to be the sigmoid function (the default value is hyperbolic tangent)
-    rnn1 = SimpleRNN(hidden_neurons, 
-                    return_sequences=True,  # This needs to be True if another hidden layer is to follow
-                    stateful = stateful, activation = 'sigmoid',
-                    name="RNN1")(inp)
-    rnn2 = SimpleRNN(hidden_neurons, 
-                    return_sequences=False, activation = 'sigmoid',
-                    stateful = stateful,
-                    name="RNN2")(rnn1)
-    # Define the output layer as a dense neural network layer (standard neural network layer)
-    #and add it to the network immediately after the hidden layer.
-    dens = Dense(in_out_neurons,name="dense")(rnn2)
-    # Create the machine learning model starting with the input layer and ending with the 
-    # output layer
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the machine learning model using the mean squared error function as the loss 
-    # function and an Adams optimizer.
-    model.compile(loss="mean_squared_error", optimizer="adam")  
-    return model
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-model = rnn_2layers(length_of_sequences = 2)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Other Types of Recurrent Neural Networks

- -

Besides a simple recurrent neural network layer, there are two other -commonly used types of recurrent neural network layers: Long Short -Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short -introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b -and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b. -

- -

The first network created below is similar to the previous network, -but it replaces the SimpleRNN layers with LSTM layers. The second -network below has two hidden layers made up of GRUs, which are -preceeded by two dense (feeddorward) neural network layers. These -dense layers "preprocess" the data before it reaches the recurrent -layers. This architecture has been shown to improve the performance -of recurrent neural networks (see the link above and also -https://arxiv.org/pdf/1807.02857.pdf. -

- - - -
-
-
-
-
-
def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.
-    """
-    # Number of neurons on the input/output layer and the number of neurons in the hidden layer
-    in_out_neurons = 1
-    hidden_neurons = 250
-    # Input Layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons)) 
-    # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)
-    rnn= LSTM(hidden_neurons, 
-                    return_sequences=True,
-                    stateful = stateful,
-                    name="RNN", use_bias=True, activation='tanh')(inp)
-    rnn1 = LSTM(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN1", use_bias=True, activation='tanh')(rnn)
-    # Output layer
-    dens = Dense(in_out_neurons,name="dense")(rnn1)
-    # Define the midel
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the model
-    model.compile(loss='mean_squared_error', optimizer='adam')  
-    # Return the model
-    return model
-
-def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):
-    """
-        Inputs:
-            length_of_sequences (an int): the number of y values in "x data".  This is determined
-                when the data is formatted
-            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
-            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
-        Returns:
-            model (a Keras model): The recurrent neural network that is built and compiled by this
-                method
-        Builds and compiles a recurrent neural network with four hidden layers (two dense followed by
-        two GRU layers) and returns the model.
-    """    
-    # Number of neurons on the input/output layers and hidden layers
-    in_out_neurons = 1
-    hidden_neurons = 250
-    # Input layer
-    inp = Input(batch_shape=(batch_size, 
-                length_of_sequences, 
-                in_out_neurons)) 
-    # Hidden Dense (feedforward) layers
-    dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)
-    dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)
-    # Hidden GRU layers
-    rnn1 = GRU(hidden_neurons, 
-                    return_sequences=True,
-                    stateful = stateful,
-                    name="RNN1", use_bias=True)(dnn1)
-    rnn = GRU(hidden_neurons, 
-                    return_sequences=False,
-                    stateful = stateful,
-                    name="RNN", use_bias=True)(rnn1)
-    # Output layer
-    dens = Dense(in_out_neurons,name="dense")(rnn)
-    # Define the model
-    model = Model(inputs=[inp],outputs=[dens])
-    # Compile the mdoel
-    model.compile(loss='mean_squared_error', optimizer='adam')  
-    # Return the model
-    return model
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-
-# Generate the training data for the RNN, using a sequence of 2
-rnn_input, rnn_training = format_data(y_train, 2)
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-# Change the method name to reflect which network you want to use
-model = dnn2_gru2(length_of_sequences = 2)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict more points of the data set
-test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)
-# 
-# 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.
-
-# Check to make sure the data set is complete
-assert len(X_tot) == len(y_tot)
-
-# This is the number of points that will be used in as the training data
-dim=12
-
-# Separate the training data from the whole data set
-X_train = X_tot[:dim]
-y_train = y_tot[:dim]
-
-# Reshape the data for Keras specifications
-X_train = X_train.reshape((dim, 1))
-y_train = y_train.reshape((dim, 1))
-
-
-# Create a recurrent neural network in Keras and produce a summary of the 
-# machine learning model
-# Set the sequence length to 1 for regular data formatting 
-model = rnn(length_of_sequences = 1)
-model.summary()
-
-# Start the timer.  Want to time training+testing
-start = timer()
-# Fit the model using the training data genenerated above using 150 training iterations and a 5%
-# validation split.  Setting verbose to True prints information about each training iteration.
-hist = model.fit(X_train, y_train, batch_size=None, epochs=150, 
-                 verbose=True,validation_split=0.05)
-
-
-# This section plots the training loss and the validation loss as a function of training iteration.
-# This is not required for analyzing the couple cluster data but can help determine if the network is
-# being overtrained.
-for label in ["loss","val_loss"]:
-    plt.plot(hist.history[label],label=label)
-
-plt.ylabel("loss")
-plt.xlabel("epoch")
-plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
-plt.legend()
-plt.show()
-
-# Use the trained neural network to predict the remaining data points
-X_pred = X_tot[dim:]
-X_pred = X_pred.reshape((len(X_pred), 1))
-y_model = model.predict(X_pred)
-y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))
-
-# Plot the known data set and the predicted data set.  The red box represents the region that was used
-# for the training data.
-fig, ax = plt.subplots()
-ax.plot(X_tot, y_tot, label="true", linewidth=3)
-ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4)
-ax.legend()
-# Created a red region to represent the points used in the training data.
-ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')
-plt.show()
-
-# Stop the timer and calculate the total time needed.
-end = timer()
-print('Time: ', end-start)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Generative Models

- -

Generative models describe a class of statistical models that are a contrast -to discriminative models. Informally we say that generative models can -generate new data instances while discriminative models discriminate between -different kinds of data instances. A generative model could generate new photos -of animals that look like 'real' animals while a discriminative model could tell -a dog from a cat. More formally, given a data set \( x \) and a set of labels / -targets \( y \). Generative models capture the joint probability \( p(x, y) \), or -just \( p(x) \) if there are no labels, while discriminative models capture the -conditional probability \( p(y | x) \). Discriminative models generally try to draw -boundaries in the data space (often high dimensional), while generative models -try to model how data is placed throughout the space. -

- -

Note: this material is thanks to Linus Ekstrøm.

- -









-

Generative Adversarial Networks

- -

Generative Adversarial Networks are a type of unsupervised machine learning -algorithm proposed by Goodfellow et. al -in 2014 (short and good article). -

- -

The simplest formulation of -the model is based on a game theoretic approach, zero sum game, where we pit -two neural networks against one another. We define two rival networks, one -generator \( g \), and one discriminator \( d \). The generator directly produces -samples -

-$$ -\begin{equation} - x = g(z; \theta^{(g)}) -\label{_auto1} -\end{equation} -$$ - - -









-

Discriminator

-

The discriminator attempts to distinguish between samples drawn from the -training data and samples drawn from the generator. In other words, it tries to -tell the difference between the fake data produced by \( g \) and the actual data -samples we want to do prediction on. The discriminator outputs a probability -value given by -

- -$$ -\begin{equation} - d(x; \theta^{(d)}) -\label{_auto2} -\end{equation} -$$ - -

indicating the probability that \( x \) is a real training example rather than a -fake sample the generator has generated. The simplest way to formulate the -learning process in a generative adversarial network is a zero-sum game, in -which a function -

- -$$ -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) -\label{_auto3} -\end{equation} -$$ - -

determines the reward for the discriminator, while the generator gets the -conjugate reward -

- -$$ -\begin{equation} - -v(\theta^{(g)}, \theta^{(d)}) -\label{_auto4} -\end{equation} -$$ - - -









-

Learning Process

- -

During learning both of the networks maximize their own reward function, so that -the generator gets better and better at tricking the discriminator, while the -discriminator gets better and better at telling the difference between the fake -and real data. The generator and discriminator alternate on which one trains at -one time (i.e. for one epoch). In other words, we keep the generator constant -and train the discriminator, then we keep the discriminator constant to train -the generator and repeat. It is this back and forth dynamic which lets GANs -tackle otherwise intractable generative problems. As the generator improves with - training, the discriminator's performance gets worse because it cannot easily - tell the difference between real and fake. If the generator ends up succeeding - perfectly, the the discriminator will do no better than random guessing i.e. - 50\%. This progression in the training poses a problem for the convergence - criteria for GANs. The discriminator feedback gets less meaningful over time, - if we continue training after this point then the generator is effectively - training on junk data which can undo the learning up to that point. Therefore, - we stop training when the discriminator starts outputting \( 1/2 \) everywhere. -

- -









-

More about the Learning Process

- -

At convergence we have

- -$$ -\begin{equation} - g^* = \underset{g}{\mathrm{argmin}}\hspace{2pt} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\label{_auto5} -\end{equation} -$$ - -

The default choice for \( v \) is

-$$ -\begin{equation} - v(\theta^{(g)}, \theta^{(d)}) = \mathbb{E}_{x\sim p_\mathrm{data}}\log d(x) - + \mathbb{E}_{x\sim p_\mathrm{model}} - \log (1 - d(x)) -\label{_auto6} -\end{equation} -$$ - -

The main motivation for the design of GANs is that the learning process requires -neither approximate inference (variational autoencoders for example) nor -approximation of a partition function. In the case where -

-$$ -\begin{equation} - \underset{d}{\mathrm{max}}v(\theta^{(g)}, \theta^{(d)}) -\label{_auto7} -\end{equation} -$$ - -

is convex in $\theta^{(g)} then the procedure is guaranteed to converge and is -asymptotically consistent -( Seth Lloyd on QuGANs ). -

- -









-

Additional References

-

This is in -general not the case and it is possible to get situations where the training -process never converges because the generator and discriminator chase one -another around in the parameter space indefinitely. A much deeper discussion on -the currently open research problem of GAN convergence is available -here. To -anyone interested in learning more about GANs it is a highly recommended read. -Direct quote: "In this best-performing formulation, the generator aims to -increase the log probability that the discriminator makes a mistake, rather than -aiming to decrease the log probability that the discriminator makes the correct -prediction." Another interesting read -

- -









-

Writing Our First Generative Adversarial Network

-

Let us now move on to actually implementing a GAN in tensorflow. We will study -the performance of our GAN on the MNIST dataset. This code is based on and -adapted from the -google tutorial -

- -

First we import our libraries

- - - -
-
-
-
-
-
import os
-import time
-import numpy as np
-import tensorflow as tf
-import matplotlib.pyplot as plt
-from tensorflow.keras import layers
-from tensorflow.keras.utils import plot_model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define our hyperparameters and import our data the usual way

- - - -
-
-
-
-
-
BUFFER_SIZE = 60000
-BATCH_SIZE = 256
-EPOCHS = 30
-
-data = tf.keras.datasets.mnist.load_data()
-(train_images, train_labels), (test_images, test_labels) = data
-train_images = np.reshape(train_images, (train_images.shape[0],
-                                         28,
-                                         28,
-                                         1)).astype('float32')
-
-# we normalize between -1 and 1
-train_images = (train_images - 127.5) / 127.5
-training_dataset = tf.data.Dataset.from_tensor_slices(
-                      train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

MNIST and GANs

- -

Let's have a quick look

- - - -
-
-
-
-
-
plt.imshow(train_images[0], cmap='Greys')
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we define our two models. This is where the 'magic' happens. There are a -huge amount of possible formulations for both models. A lot of engineering and -trial and error can be done here to try to produce better performing models. For -more advanced GANs this is by far the step where you can 'make or break' a -model. -

- -

We start with the generator. As stated in the introductory text the generator -\( g \) upsamples from a random sample to the shape of what we want to predict. In -our case we are trying to predict MNIST images (\( 28\times 28 \) pixels). -

- - - -
-
-
-
-
-
def generator_model():
-    """
-    The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to
-    produce an image from a random seed. We start with a Dense layer taking this
-    random sample as an input and subsequently upsample through multiple
-    convolutional layers.
-    """
-
-    # we define our model
-    model = tf.keras.Sequential()
-
-
-    # adding our input layer. Dense means that every neuron is connected and
-    # the input shape is the shape of our random noise. The units need to match
-    # in some sense the upsampling strides to reach our desired output shape.
-    # we are using 100 random numbers as our seed
-    model.add(layers.Dense(units=7*7*BATCH_SIZE,
-                           use_bias=False,
-                           input_shape=(100, )))
-    # we normalize the output form the Dense layer
-    model.add(layers.BatchNormalization())
-    # and add an activation function to our 'layer'. LeakyReLU avoids vanishing
-    # gradient problem
-    model.add(layers.LeakyReLU())
-    model.add(layers.Reshape((7, 7, BATCH_SIZE)))
-    assert model.output_shape == (None, 7, 7, BATCH_SIZE)
-    # even though we just added four keras layers we think of everything above
-    # as 'one' layer
-
-    # next we add our upscaling convolutional layers
-    model.add(layers.Conv2DTranspose(filters=128,
-                                     kernel_size=(5, 5),
-                                     strides=(1, 1),
-                                     padding='same',
-                                     use_bias=False))
-    model.add(layers.BatchNormalization())
-    model.add(layers.LeakyReLU())
-    assert model.output_shape == (None, 7, 7, 128)
-
-    model.add(layers.Conv2DTranspose(filters=64,
-                                     kernel_size=(5, 5),
-                                     strides=(2, 2),
-                                     padding='same',
-                                     use_bias=False))
-    model.add(layers.BatchNormalization())
-    model.add(layers.LeakyReLU())
-    assert model.output_shape == (None, 14, 14, 64)
-
-    model.add(layers.Conv2DTranspose(filters=1,
-                                     kernel_size=(5, 5),
-                                     strides=(2, 2),
-                                     padding='same',
-                                     use_bias=False,
-                                     activation='tanh'))
-    assert model.output_shape == (None, 28, 28, 1)
-
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

And there we have our 'simple' generator model. Now we move on to defining our -discriminator model \( d \), which is a convolutional neural network based image -classifier. -

- - - -
-
-
-
-
-
def discriminator_model():
-    """
-    The discriminator is a convolutional neural network based image classifier
-    """
-
-    # we define our model
-    model = tf.keras.Sequential()
-    model.add(layers.Conv2D(filters=64,
-                            kernel_size=(5, 5),
-                            strides=(2, 2),
-                            padding='same',
-                            input_shape=[28, 28, 1]))
-    model.add(layers.LeakyReLU())
-    # adding a dropout layer as you do in conv-nets
-    model.add(layers.Dropout(0.3))
-
-
-    model.add(layers.Conv2D(filters=128,
-                            kernel_size=(5, 5),
-                            strides=(2, 2),
-                            padding='same'))
-    model.add(layers.LeakyReLU())
-    # adding a dropout layer as you do in conv-nets
-    model.add(layers.Dropout(0.3))
-
-    model.add(layers.Flatten())
-    model.add(layers.Dense(1))
-
-    return model
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Other Models

-

Let us take a look at our models. Note: double click images for bigger view.

- - - -
-
-
-
-
-
generator = generator_model()
-plot_model(generator, show_shapes=True, rankdir='LR')
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
discriminator = discriminator_model()
-plot_model(discriminator, show_shapes=True, rankdir='LR')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we need a few helper objects we will use in training

- - - -
-
-
-
-
-
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
-generator_optimizer = tf.keras.optimizers.Adam(1e-4)
-discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

The first object, cross_entropy is our loss function and the two others are -our optimizers. Notice we use the same learning rate for both \( g \) and \( d \). This -is because they need to improve their accuracy at approximately equal speeds to -get convergence (not necessarily exactly equal). Now we define our loss -functions -

- - - -
-
-
-
-
-
def generator_loss(fake_output):
-    loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
-    return loss
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
def discriminator_loss(real_output, fake_output):
-    real_loss = cross_entropy(tf.ones_like(real_output), real_output)
-    fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)
-    total_loss = real_loss + fake_loss
-
-    return total_loss
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define a kind of seed to help us compare the learning process over -multiple training epochs. -

- - - -
-
-
-
-
-
noise_dimension = 100
-n_examples_to_generate = 16
-seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Training Step

- -

Now we have everything we need to define our training step, which we will apply -for every step in our training loop. Notice the @tf.function flag signifying -that the function is tensorflow 'compiled'. Removing this flag doubles the -computation time. -

- - - -
-
-
-
-
-
@tf.function
-def train_step(images):
-    noise = tf.random.normal([BATCH_SIZE, noise_dimension])
-
-    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
-        generated_images = generator(noise, training=True)
-
-        real_output = discriminator(images, training=True)
-        fake_output = discriminator(generated_images, training=True)
-
-        gen_loss = generator_loss(fake_output)
-        disc_loss = discriminator_loss(real_output, fake_output)
-
-    gradients_of_generator = gen_tape.gradient(gen_loss,
-                                            generator.trainable_variables)
-    gradients_of_discriminator = disc_tape.gradient(disc_loss,
-                                            discriminator.trainable_variables)
-    generator_optimizer.apply_gradients(zip(gradients_of_generator,
-                                            generator.trainable_variables))
-    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,
-                                            discriminator.trainable_variables))
-
-    return gen_loss, disc_loss
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Next we define a helper function to produce an output over our training epochs -to see the predictive progression of our generator model. Note: I am including -this code here, but comment it out in the training loop. -

- - -
-
-
-
-
-
def generate_and_save_images(model, epoch, test_input):
-    # we're making inferences here
-    predictions = model(test_input, training=False)
-
-    fig = plt.figure(figsize=(4, 4))
-
-    for i in range(predictions.shape[0]):
-        plt.subplot(4, 4, i+1)
-        plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
-        plt.axis('off')
-
-    plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')
-    plt.close()
-    #plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Checkpoints

-

Setting up checkpoints to periodically save our model during training so that -everything is not lost even if the program were to somehow terminate while -training. -

- - - -
-
-
-
-
-
# Setting up checkpoints to save model during training
-checkpoint_dir = './training_checkpoints'
-checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')
-checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
-                            discriminator_optimizer=discriminator_optimizer,
-                            generator=generator,
-                            discriminator=discriminator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we define our training loop

- - - -
-
-
-
-
-
def train(dataset, epochs):
-    generator_loss_list = []
-    discriminator_loss_list = []
-
-    for epoch in range(epochs):
-        start = time.time()
-
-        for image_batch in dataset:
-            gen_loss, disc_loss = train_step(image_batch)
-            generator_loss_list.append(gen_loss.numpy())
-            discriminator_loss_list.append(disc_loss.numpy())
-
-        #generate_and_save_images(generator, epoch + 1, seed_images)
-
-        if (epoch + 1) % 15 == 0:
-            checkpoint.save(file_prefix=checkpoint_prefix)
-
-        print(f'Time for epoch {epoch} is {time.time() - start}')
-
-    #generate_and_save_images(generator, epochs, seed_images)
-
-    loss_file = './data/lossfile.txt'
-    with open(loss_file, 'w') as outfile:
-        outfile.write(str(generator_loss_list))
-        outfile.write('\n')
-        outfile.write('\n')
-        outfile.write(str(discriminator_loss_list))
-        outfile.write('\n')
-        outfile.write('\n')
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

To train simply call this function. Warning: this might take a long time so -there is a folder of a pretrained network already included in the repository. -

- - - -
-
-
-
-
-
train(train_dataset, EPOCHS)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

And here is the result of training our model for 100 epochs

- - -

- -

Now to avoid having to train and everything, which will take a while depending -on your computer setup we now load in the model which produced the above gif. -

- - - -
-
-
-
-
-
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
-restored_generator = checkpoint.generator
-restored_discriminator = checkpoint.discriminator
-
-print(restored_generator)
-print(restored_discriminator)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Exploring the Latent Space

- -

We have successfully loaded in our latest model. Let us now play around a bit -and see what kind of things we can learn about this model. Our generator takes -an array of 100 numbers. One idea can be to try to systematically change our -input. Let us try and see what we get -

- - - -
-
-
-
-
-
def generate_latent_points(number=100, scale_means=1, scale_stds=1):
-    latent_dim = 100
-    means = scale_means * tf.linspace(-1, 1, num=latent_dim)
-    stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)
-    latent_space_value_range = tf.random.normal([number, latent_dim],
-                                                means,
-                                                stds,
-                                                dtype=tf.float64)
-
-    return latent_space_value_range
-
-def generate_images(latent_points):
-    # notice we set training to false because we are making inferences
-    generated_images = restored_generator.predict(latent_points)
-
-    return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
def plot_result(generated_images, number=100):
-    # obviously this assumes sqrt number is an int
-    fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),
-                            figsize=(10, 10))
-
-    for i in range(int(np.sqrt(number))):
-        for j in range(int(np.sqrt(number))):
-            axs[i, j].imshow(generated_images[i*j], cmap='Greys')
-            axs[i, j].axis('off')
-
-    plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
-
generated_images = generate_images(generate_latent_points())
-plot_result(generated_images)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Getting Results

-

We see that the generator generates images that look like MNIST -numbers: \( 1, 4, 7, 9 \). Let's try to tweak it a bit more to see if we are able -to generate a similar plot where we generate every MNIST number. Let us now try -to 'move' a bit around in the latent space. Note: decrease the plot number if -these following cells take too long to run on your computer. -

- - - -
-
-
-
-
-
plot_number = 225
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=5,
-                                                          scale_stds=1))
-plot_result(generated_images, number=plot_number)
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=-5,
-                                                          scale_stds=1))
-plot_result(generated_images, number=plot_number)
-
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=1,
-                                                          scale_stds=5))
-plot_result(generated_images, number=plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Again, we have found something interesting. Moving around using our means -takes us from digit to digit, while moving around using our standard -deviations seem to increase the number of different digits! In the last image -above, we can barely make out every MNIST digit. Let us make on last plot using -this information by upping the standard deviation of our Gaussian noises. -

- - - -
-
-
-
-
-
plot_number = 400
-generated_images = generate_images(generate_latent_points(number=plot_number,
-                                                          scale_means=1,
-                                                          scale_stds=10))
-plot_result(generated_images, number=plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

A pretty cool result! We see that our generator indeed has learned a -distribution which qualitatively looks a whole lot like the MNIST dataset. -

- -









-

Interpolating Between MNIST Digits

-

Another interesting way to explore the latent space of our generator model is by -interpolating between the MNIST digits. This section is largely based on -this excellent blogpost -by Jason Brownlee. -

- -

So let us start by defining a function to interpolate between two points in the -latent space. -

- - - -
-
-
-
-
-
def interpolation(point_1, point_2, n_steps=10):
-    ratios = np.linspace(0, 1, num=n_steps)
-    vectors = []
-    for i, ratio in enumerate(ratios):
-        vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))
-
-    return tf.stack(vectors)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we have all we need to do our interpolation analysis.

- - - -
-
-
-
-
-
plot_number = 100
-latent_points = generate_latent_points(number=plot_number)
-results = None
-for i in range(0, 2*np.sqrt(plot_number), 2):
-    interpolated = interpolation(latent_points[i], latent_points[i+1])
-    generated_images = generate_images(interpolated)
-
-    if results is None:
-        results = generated_images
-    else:
-        results = tf.stack((results, generated_images))
-
-plot_results(results, plot_number)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Basic ideas of the Principal Component Analysis (PCA)

- -

The principal component analysis deals with the problem of fitting a -low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than -the total dimension \( D \) of the problem at hand (our data -set). Mathematically it can be formulated as a statistical problem or -a geometric problem. In our discussion of the theorem for the -classical PCA, we will stay with a statistical approach. -Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable. -

- -

We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition)

-
    -
  • Each data point is determined by \( p \) extrinsic (measurement) variables
  • -
  • We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?
  • -
  • If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
  • -
-

A good read is for example Vidal, Ma and Sastry.

- -









-

Introducing the Covariance and Correlation functions

- -

Before we discuss the PCA theorem, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities -

- -

Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as -

-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ - \end{bmatrix}, -$$ - -

where for example

-$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -$$ - -

With this definition and recalling that the variance is defined as

-$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ - -

we can rewrite the covariance matrix as

-$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ - - -









-

More on the covariance

-

The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function -

- -$$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. -$$ - -

The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as -

- -$$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ - \end{bmatrix}, -$$ - -

In the above example this is the function we constructed using pandas.

- -









-

Reminding ourselves about Linear Regression

-

In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression -we defined the design/feature matrix \( \boldsymbol{X} \) as -

- -$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ - -

with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -

-$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ - -

with a given vector

-$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ - - -









-

Simple Example

-

With these definitions, we can now rewrite our \( 2\times 2 \) -correlation/covariance matrix in terms of a moe general design/feature -matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) -covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) -

- -$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\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}]\\ -\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}]\\ -\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}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\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}]\\ -\end{bmatrix}, -$$ - - -









-

The Correlation Matrix

- -

and the correlation matrix

-$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -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}]\\ -\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}]\\ -\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}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\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\\ -\end{bmatrix}, -$$ - - -









-

Numpy Functionality

- -

The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) -

- -$$ -\boldsymbol{W}^T = \begin{bmatrix} x_0 & y_0 \\ - x_1 & y_1 \\ - x_2 & y_2\\ - \dots & \dots \\ - x_{n-2} & y_{n-2}\\ - x_{n-1} & y_{n-1} & - \end{bmatrix}, -$$ - -

which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. -

- - - -
-
-
-
-
-
# Importing various packages
-import numpy as np
-n = 100
-x = np.random.normal(size=n)
-print(np.mean(x))
-y = 4+3*x+np.random.normal(size=n)
-print(np.mean(y))
-W = np.vstack((x, y))
-C = np.cov(W)
-print(C)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Correlation Matrix again

- -

The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -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). -

- - - -
-
-
-
-
-
import numpy as np
-n = 100
-# define two vectors                                                                                           
-x = np.random.random(size=n)
-y = 4+3*x+np.random.normal(size=n)
-#scaling the x and y vectors                                                                                   
-x = x - np.mean(x)
-y = y - np.mean(y)
-variance_x = np.sum(x@x)/n
-variance_y = np.sum(y@y)/n
-print(variance_x)
-print(variance_y)
-cov_xy = np.sum(x@y)/n
-cov_xx = np.sum(x@x)/n
-cov_yy = np.sum(y@y)/n
-C = np.zeros((2,2))
-C[0,0]= cov_xx/variance_x
-C[1,1]= cov_yy/variance_y
-C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
-C[1,0]= C[0,1]
-print(C)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. -

- -

The above procedure with numpy can be made more compact if we use pandas.

- -









-

Using Pandas

- -

We whow here how we can set up the correlation matrix using pandas, as done in this simple code

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-n = 10
-x = np.random.normal(size=n)
-x = x - np.mean(x)
-y = 4+3*x+np.random.normal(size=n)
-y = y - np.mean(y)
-X = (np.vstack((x, y))).T
-print(X)
-Xpd = pd.DataFrame(X)
-print(Xpd)
-correlation_matrix = Xpd.corr()
-print(correlation_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

And then the Franke Function

- -

We expand this model to the Franke function discussed above.

- - - -
-
-
-
-
-
# Common imports
-import numpy as np
-import pandas as pd
-
-
-def FrankeFunction(x,y):
-	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
-	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
-	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
-	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
-	return term1 + term2 + term3 + term4
-
-
-def create_X(x, y, n ):
-	if len(x.shape) > 1:
-		x = np.ravel(x)
-		y = np.ravel(y)
-
-	N = len(x)
-	l = int((n+1)*(n+2)/2)		# Number of elements in beta
-	X = np.ones((N,l))
-
-	for i in range(1,n+1):
-		q = int((i)*(i+1)/2)
-		for k in range(i+1):
-			X[:,q+k] = (x**(i-k))*(y**k)
-
-	return X
-
-
-# Making meshgrid of datapoints and compute Franke's function
-n = 4
-N = 100
-x = np.sort(np.random.uniform(0, 1, N))
-y = np.sort(np.random.uniform(0, 1, N))
-z = FrankeFunction(x, y)
-X = create_X(x, y, n=n)    
-
-Xpd = pd.DataFrame(X)
-# subtract the mean values and set up the covariance matrix
-Xpd = Xpd - Xpd.mean()
-covariance_matrix = Xpd.cov()
-print(covariance_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree \( n \)). We would however not include the intercept -and wee can simply -drop these elements and construct a correlation -matrix without them by centering our matrix elements by subtracting the mean of each column. -

- -









-

Lnks with the Design Matrix

- -

We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as

-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. -$$ - -

To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)

-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ -\end{bmatrix}. -$$ - - -









-

Computing the Expectation Values

- -

If we then compute the expectation value

-$$ -\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix} -x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ -x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ -\end{bmatrix}, -$$ - -

which is just

-$$ -\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] \\ - \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ - \end{bmatrix}, -$$ - -

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} \).

- -

It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).

- -









-

Towards the PCA theorem

- -

We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as

-$$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. -$$ - -

Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). -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} \). -

- -

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}] \).

- -

That is we have

-$$ -\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}, -$$ - -

since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have

-$$ -\boldsymbol{S}\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}, -$$ - -

and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that

- -$$ -\boldsymbol{S}_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}_i. -$$ - - -









-

More on the PCA Theorem

- -

In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is -\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). -

- -

The eigenvalues tell us then how much we need to stretch the -corresponding eigenvectors. Dimensions with large eigenvalues have -thus large variations (large variance) and define therefore useful -dimensions. The data points are more spread out in the direction of -these eigenvectors. Smaller eigenvalues mean on the other hand that -the corresponding eigenvectors are shrunk accordingly and the data -points are tightly bunched together and there is not much variation in -these specific directions. Hopefully then we could leave it out -dimensions where the eigenvalues are very small. If \( p \) is very large, -we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) -features/predictors. -

- -









-

The Algorithm before theorem

- -

Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here.

-
    -
  • 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.
  • -
-$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, -$$ - -
    -
  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • -
  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}^T\overline{\boldsymbol{X}}] \).
  • -
  • 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}] \).
  • -
  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • -
  • 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.
  • -
-









-

Writing our own PCA code

- -

We will use a simple example first with two-dimensional data -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): -

-$$ -\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ -2 & 2 -\end{bmatrix} -$$ - -

Note that the mean refers to each column of data. -We will generate \( n = 10000 \) points \( X = \{ x_1, \ldots, x_N \} \) from -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. -

- -









-

Implementing it

-

The following Python code aids in setting up the data and writing out the design matrix. -Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). -

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-import matplotlib.pyplot as plt
-from IPython.display import display
-n = 10000
-mean = (-1, 2)
-cov = [[4, 2], [2, 2]]
-X = np.random.multivariate_normal(mean, cov, n)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Now we are going to implement the PCA algorithm. We will break it down into various substeps.

- -









-

First Step

- -

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

-$$ -\mu_n = \frac{1}{n} \sum_{i=1}^n x_i -$$ - -

and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form

-$$ -\bar{x}_i = x_i - \mu_n. -$$ - -

When you are done with these steps, print out \( \mu_n \) to verify it is -close to \( \mu \) and plot your mean centered data to verify it is -centered at the origin! -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. -

- - -
-
-
-
-
-
df = pd.DataFrame(X)
-# Pandas does the centering for us
-df = df -df.mean()
-# we center it ourselves
-X_centered = X - X.mean(axis=0)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Scaling

-

Alternatively, we could use the functions we discussed -earlier for scaling the data set. That is, we could have used the -StandardScaler function in Scikit-Learn, a function which ensures -that for each feature/predictor we study the mean value is zero and -the variance is one (every column in the design/feature matrix). You -would then not get the same results, since we divide by the -variance. The diagonal covariance matrix elements will then be one, -while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our -specific case. -

- -









-

Centered Data

- -

Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation

-$$ -\begin{equation*} -\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) -\end{equation*} -$$ - -

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 \). -We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows -

- - -
-
-
-
-
-
print(df.cov())
-print(np.cov(X_centered.T))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

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. -Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. -

- - -
-
-
-
-
-
# extract the relevant columns from the centered design matrix of dim n x 2
-x = X_centered[:,0]
-y = X_centered[:,1]
-Cov = np.zeros((2,2))
-Cov[0,1] = np.sum(x.T@y)/(n-1.0)
-Cov[0,0] = np.sum(x.T@x)/(n-1.0)
-Cov[1,1] = np.sum(y.T@y)/(n-1.0)
-Cov[1,0]= Cov[0,1]
-print("Centered covariance using own code")
-print(Cov)
-plt.plot(x, y, 'x')
-plt.axis('equal')
-plt.show()
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Exploring

- -

Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. -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. -

- -









-

Diagonalize the sample covariance matrix to obtain the principal components

- -

Now we are ready to solve for the principal components! To do so we -diagonalize the sample covariance matrix \( \Sigma \). We can use the -function np.linalg.eig to do so. It will return the eigenvalues and -eigenvectors of \( \Sigma \). Once we have these we can perform the -following tasks: -

- -
    -
  • We compute the percentage of the total variance captured by the first principal component
  • -
  • We plot the mean centered data and lines along the first and second principal components
  • -
  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • -
  • Finally, we approximate the data as
  • -
-$$ -\begin{equation*} -x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 -\end{equation*} -$$ - -

where \( v_0 \) is the first principal component.

- -









-

Collecting all Steps

- -

Collecting all these steps we can write our own PCA function and -compare this with the functionality included in Scikit-Learn. -

- -

The code here outlines some of the elements we could include in the -analysis. Feel free to extend upon this in order to address the above -questions. -

- - - -
-
-
-
-
-
# diagonalize and obtain eigenvalues, not necessarily sorted
-EigValues, EigVectors = np.linalg.eig(Cov)
-# sort eigenvectors and eigenvalues
-#permute = EigValues.argsort()
-#EigValues = EigValues[permute]
-#EigVectors = EigVectors[:,permute]
-print("Eigenvalues of Covariance matrix")
-for i in range(2):
-    print(EigValues[i])
-FirstEigvector = EigVectors[:,0]
-SecondEigvector = EigVectors[:,1]
-print("First eigenvector")
-print(FirstEigvector)
-print("Second eigenvector")
-print(SecondEigvector)
-#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2Dsl = pca.fit_transform(X)
-print("Eigenvector of largest eigenvalue")
-print(pca.components_.T[:, 0])
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

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?

- -









-

Classical PCA Theorem

- -

We assume now that we have a design matrix \( \boldsymbol{X} \) which has been -centered as discussed above. For the sake of simplicity we skip the -overline symbol. The matrix is defined in terms of the various column -vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension -\( \boldsymbol{x}\in {\mathbb{R}}^{n} \). -

- -

The PCA theorem states that minimizing the above reconstruction error -corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which -diagonalizes the empirical covariance(correlation) matrix. The optimal -low-dimensional encoding of the data is then given by a set of vectors -\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the -orthogonal projection of the data onto the columns spanned by the -eigenvectors of the covariance(correlations matrix). -

- -









-

The PCA Theorem

- -

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

- -

We are almost there, we have obtained a relation between minimizing -the reconstruction error and the variance and the covariance -matrix. Minimizing the error is equivalent to maximizing the variance -of the projected data. -

- -

We could trivially maximize the variance of the projection (and -thereby minimize the error in the reconstruction function) by letting -the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we -want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by -\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a -Lagrange multiplier we can then in turn maximize -

- -$$ -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). -$$ - -

Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain

- -$$ -\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, -$$ - -

meaning that

-$$ -\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. -$$ - -

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

-$$ -\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. -$$ - -

If we want to maximize the variance (minimize the construction error) -we simply pick the eigenvector of the covariance matrix with the -largest eigenvalue. This establishes the link between the minimization -of the reconstruction function \( J \) in terms of an orthogonal matrix -and the maximization of the variance and thereby the covariance of our -observations encoded in the design/feature matrix \( \boldsymbol{X} \). -

- -

The proof -for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be -established by applying the above arguments and using the fact that -our basis of eigenvectors is orthogonal, see Murphy chapter -12.2. The -discussion in chapter 12.2 of Murphy's text has also a nice link with -the Singular Value Decomposition theorem. For categorical data, see -chapter 12.4 and discussion therein. -

- -

For more details, see for example Vidal, Ma and Sastry, chapter 2.

- -









- - -

For a detailed demonstration of the geometric interpretation, see Vidal, Ma and Sastry, section 2.1.2.

- -

Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. -First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. -

- -

The following Python code uses NumPy’s svd() function to obtain all the principal components of the -training set, then extracts the first two principal components. First we center the data using either pandas or our own code -

- - -
-
-
-
-
-
import numpy as np
-import pandas as pd
-from IPython.display import display
-np.random.seed(100)
-# setting up a 10 x 5 vanilla matrix 
-rows = 10
-cols = 5
-X = np.random.randn(rows,cols)
-df = pd.DataFrame(X)
-# Pandas does the centering for us
-df = df -df.mean()
-display(df)
-
-# we center it ourselves
-X_centered = X - X.mean(axis=0)
-# Then check the difference between pandas and our own set up
-print(X_centered-df)
-#Now we do an SVD
-U, s, V = np.linalg.svd(X_centered)
-c1 = V.T[:, 0]
-c2 = V.T[:, 1]
-W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-print(X2D)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering -the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t -forget to center the data first. -

- -

Once you have identified all the principal components, you can reduce the dimensionality of the dataset -down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. -Selecting this hyperplane ensures that the projection will preserve as much variance as possible. -

- - -
-
-
-
-
-
W2 = V.T[:, :2]
-X2D = X_centered.dot(W2)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

PCA and scikit-learn

- -

Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The -following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note -that it automatically takes care of centering the data): -

- - -
-
-
-
-
-
#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D = pca.fit_transform(X)
-print(X2D)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

After fitting the PCA transformer to the dataset, you can access the principal components using the -components variable (note that it contains the PCs as horizontal vectors, so, for example, the first -principal component is equal to -

- - -
-
-
-
-
-
pca.components_.T[:, 0]
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

Another very useful piece of information is the explained variance ratio of each principal component, -available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s -variance that lies along the axis of each principal component. -

- -









-

Back to the Cancer Data

-

We can now repeat the above but applied to real data, in this case our breast cancer data. -Here we compute performance scores on the training data using logistic regression. -

- - -
-
-
-
-
-
import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import  train_test_split 
-from sklearn.datasets import load_breast_cancer
-from sklearn.linear_model import LogisticRegression
-cancer = load_breast_cancer()
-
-X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
-
-logreg = LogisticRegression()
-logreg.fit(X_train, y_train)
-print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
-# We scale the data
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-# Then perform again a log reg fit
-logreg.fit(X_train_scaled, y_train)
-print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
-#thereafter we do a PCA with Scikit-learn
-from sklearn.decomposition import PCA
-pca = PCA(n_components = 2)
-X2D_train = pca.fit_transform(X_train_scaled)
-# and finally compute the log reg fit and the score on the training data	
-logreg.fit(X2D_train,y_train)
-print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

We see that our training data after the PCA decomposition has a performance similar to the non-scaled data.

- -

Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to -choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). -Unless, of course, you are reducing dimensionality for data visualization — in that case you will -generally want to reduce the dimensionality down to 2 or 3. -The following code computes PCA without reducing dimensionality, then computes the minimum number -of dimensions required to preserve 95% of the training set’s variance: -

- - -
-
-
-
-
-
pca = PCA()
-pca.fit(X)
-cumsum = np.cumsum(pca.explained_variance_ratio_)
-d = np.argmax(cumsum >= 0.95) + 1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -

You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead -of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be -a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: -

- - -
-
-
-
-
-
pca = PCA(n_components=0.95)
-X_reduced = pca.fit_transform(X)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Incremental PCA

- -

One problem with the preceding implementation of PCA is that it requires the whole training set to fit in -memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have -been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch -at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new -instances arrive). -

-

Randomized PCA

- -

Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic -algorithm that quickly finds an approximation of the first d principal components. Its computational -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 -previous algorithms when \( d \) is much smaller than \( n \). -

-

Kernel PCA

- -

The kernel trick is a mathematical technique that implicitly maps instances into a -very high-dimensional space (called the feature space), enabling nonlinear classification and regression -with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature -space corresponds to a complex nonlinear decision boundary in the original space. -It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear -projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at -preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a -twisted manifold. -For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an -

- - -
-
-
-
-
-
from sklearn.decomposition import KernelPCA
-rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
-X_reduced = rbf_pca.fit_transform(X)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -









-

Other techniques

- -

There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.

- -

Here are some of the most popular:

-
    -
  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • -
  • 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.
  • -
  • 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).
  • -
  • 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.
  • -
- -
- © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
- - - diff --git a/doc/src/week44/week44.do.txt b/doc/src/week44/week44.do.txt index 59e4ef218..66887b363 100644 --- a/doc/src/week44/week44.do.txt +++ b/doc/src/week44/week44.do.txt @@ -55,7 +55,7 @@ Assume, we are given $n$ data points and we wish to split the data into $K < n$ different categories, or clusters. We label each cluster by an integer !bt -\[ k\in\{1, \cdots, K \}$. +\[ k\in\{1, \cdots, K \}. \] !et @@ -151,7 +151,7 @@ Now we have all the pieces necessary to formally revisit the $k$-means algorithm The $k$-means clustering algorithm goes as follows o For a given cluster assignment $C$, and $k$ cluster means - $\left{m_1, \cdots, m_k\right}$. We minimize the total cluster variance with respect to + $\left\{m_1, \cdots, m_k\right\}$. We minimize the total cluster variance with respect to the cluster means $\{m_k\}$ yielding the means of the currently assigned clusters. o Given a current set of $k$ means $\{m_k\}$ the total cluster variance is