diff --git a/doc/LectureNotes/schedule.md b/doc/LectureNotes/schedule.md
index 5f08e2068..cda1f3f89 100644
--- a/doc/LectureNotes/schedule.md
+++ b/doc/LectureNotes/schedule.md
@@ -136,6 +136,7 @@ For the reading assignments we use the following abbreviations:
- Lecture Thursday: Recurrent Neural Networks
- Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober28.mp4?vrtx=view-as-webpage
- Lecture Friday: Recurrent Neural Networks and principal component analysis (PCA)
+ - Video at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureOctober29.mp4?vrtx=view-as-webpage
- Reading recommendations:
- See lecture notes for week 43 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
- For RNNs, see Goodfellow et al chapter 10 and discussions in chapter 11 and 12 on practicalities and applications
diff --git a/doc/pub/week43/html/._week43-bs000.html b/doc/pub/week43/html/._week43-bs000.html
index 1304441ba..63d18e71e 100644
--- a/doc/pub/week43/html/._week43-bs000.html
+++ b/doc/pub/week43/html/._week43-bs000.html
@@ -1,15 +1,15 @@
@@ -227,7 +290,7 @@ MathJax.Hub.Config({
diff --git a/doc/pub/week43/html/._week43-bs001.html b/doc/pub/week43/html/._week43-bs001.html
index 58631f070..9f6572400 100644
--- a/doc/pub/week43/html/._week43-bs001.html
+++ b/doc/pub/week43/html/._week43-bs001.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
@@ -234,7 +307,7 @@ MathJax.Hub.Config({
diff --git a/doc/pub/week43/html/._week43-bs002.html b/doc/pub/week43/html/._week43-bs002.html
index 010b0534f..6631bbcc5 100644
--- a/doc/pub/week43/html/._week43-bs002.html
+++ b/doc/pub/week43/html/._week43-bs002.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -208,7 +271,7 @@ MathJax.Hub.Config({
diff --git a/doc/pub/week43/html/._week43-bs003.html b/doc/pub/week43/html/._week43-bs003.html
index b75e997de..bc1735430 100644
--- a/doc/pub/week43/html/._week43-bs003.html
+++ b/doc/pub/week43/html/._week43-bs003.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).
@@ -199,7 +262,7 @@ The first type of deep learning networks work very well on homogeneous and struc
@@ -211,7 +274,7 @@ The first type of deep learning networks work very well on homogeneous and struc
diff --git a/doc/pub/week43/html/._week43-bs004.html b/doc/pub/week43/html/._week43-bs004.html
index 0bfdb30ff..dcaa5bf23 100644
--- a/doc/pub/week43/html/._week43-bs004.html
+++ b/doc/pub/week43/html/._week43-bs004.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -228,7 +291,7 @@ This is where recurrent nueral networks (RNNs) come to our rescue.
diff --git a/doc/pub/week43/html/._week43-bs005.html b/doc/pub/week43/html/._week43-bs005.html
index 9676cb38c..f7348f1e4 100644
--- a/doc/pub/week43/html/._week43-bs005.html
+++ b/doc/pub/week43/html/._week43-bs005.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -227,7 +290,7 @@ systems such as automatic translation and speech-to-text.
diff --git a/doc/pub/week43/html/._week43-bs006.html b/doc/pub/week43/html/._week43-bs006.html
index ff9a6c1b9..0395c291a 100644
--- a/doc/pub/week43/html/._week43-bs006.html
+++ b/doc/pub/week43/html/._week43-bs006.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -211,7 +274,7 @@ More to text to be added by Wednesday October 27.
diff --git a/doc/pub/week43/html/._week43-bs007.html b/doc/pub/week43/html/._week43-bs007.html
index 406525b75..3650f97f4 100644
--- a/doc/pub/week43/html/._week43-bs007.html
+++ b/doc/pub/week43/html/._week43-bs007.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -281,7 +344,7 @@ plt.show()
diff --git a/doc/pub/week43/html/._week43-bs008.html b/doc/pub/week43/html/._week43-bs008.html
index fd514c07c..99ff3f5d3 100644
--- a/doc/pub/week43/html/._week43-bs008.html
+++ b/doc/pub/week43/html/._week43-bs008.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
The following code provides an example of how recurrent neural
@@ -183,7 +246,7 @@ a quantum mechanical many-body calculation of energies as functions of the numbe
-
# For matrices and calculations
+
# For matrices and calculationsimportnumpyasnp# For machine learning (backend for keras)importtensorflowastf
@@ -235,7 +298,7 @@ y_tot = np.17
@@ -247,7 +310,7 @@ y_tot = np.
-
+
-->
diff --git a/doc/pub/week43/html/._week43-bs009.html b/doc/pub/week43/html/._week43-bs009.html
index b8c525936..d2092a311 100644
--- a/doc/pub/week43/html/._week43-bs009.html
+++ b/doc/pub/week43/html/._week43-bs009.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -323,7 +386,7 @@ y values far removed from the training data set.
diff --git a/doc/pub/week43/html/._week43-bs010.html b/doc/pub/week43/html/._week43-bs010.html
index 2a7d7675d..62bbc40e0 100644
--- a/doc/pub/week43/html/._week43-bs010.html
+++ b/doc/pub/week43/html/._week43-bs010.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
Predicting New Points With A Trained Recurrent Neural Network
+
Predicting New Points With A Trained Recurrent Neural Network
-
deftest_rnn (x1, y_test, plot_min, plot_max):
+
deftest_rnn (x1, y_test, plot_min, plot_max):
""" Inputs: x1 (a list or numpy array): The complete x component of the data set
@@ -295,7 +358,7 @@ end = timer()
@@ -307,7 +370,7 @@ end = timer()
diff --git a/doc/pub/week43/html/._week43-bs011.html b/doc/pub/week43/html/._week43-bs011.html
index fadd49daf..4a21f9794 100644
--- a/doc/pub/week43/html/._week43-bs011.html
+++ b/doc/pub/week43/html/._week43-bs011.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
Changing the size of the recurrent neural network and its parameters
@@ -189,7 +252,7 @@ network. For some ideas on how to improve the performance of a
defrnn_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
@@ -302,7 +365,7 @@ end = timer()
@@ -314,7 +377,7 @@ end = timer()
diff --git a/doc/pub/week43/html/._week43-bs012.html b/doc/pub/week43/html/._week43-bs012.html
index 215291eef..b7a652bab 100644
--- a/doc/pub/week43/html/._week43-bs012.html
+++ b/doc/pub/week43/html/._week43-bs012.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
deflstm_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
@@ -411,7 +474,7 @@ end = timer()
@@ -423,7 +486,7 @@ end = timer()
diff --git a/doc/pub/week43/html/._week43-bs013.html b/doc/pub/week43/html/._week43-bs013.html
index d7bc48d4d..0dac13d57 100644
--- a/doc/pub/week43/html/._week43-bs013.html
+++ b/doc/pub/week43/html/._week43-bs013.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -228,7 +291,7 @@ try to model how data is placed throughout the space.
diff --git a/doc/pub/week43/html/._week43-bs014.html b/doc/pub/week43/html/._week43-bs014.html
index 1e820bb8b..db6c33228 100644
--- a/doc/pub/week43/html/._week43-bs014.html
+++ b/doc/pub/week43/html/._week43-bs014.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -230,7 +293,7 @@ $$
diff --git a/doc/pub/week43/html/._week43-bs015.html b/doc/pub/week43/html/._week43-bs015.html
index 6713eb321..f1aa9dd3b 100644
--- a/doc/pub/week43/html/._week43-bs015.html
+++ b/doc/pub/week43/html/._week43-bs015.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
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
@@ -236,7 +299,7 @@ $$
@@ -248,7 +311,7 @@ $$
diff --git a/doc/pub/week43/html/._week43-bs016.html b/doc/pub/week43/html/._week43-bs016.html
index b674e6dac..2edb9f321 100644
--- a/doc/pub/week43/html/._week43-bs016.html
+++ b/doc/pub/week43/html/._week43-bs016.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
During learning both of the networks maximize their own reward function, so that
@@ -218,7 +281,7 @@ tackle otherwise intractable generative problems. As the generator improves with
@@ -230,7 +293,7 @@ tackle otherwise intractable generative problems. As the generator improves with
diff --git a/doc/pub/week43/html/._week43-bs017.html b/doc/pub/week43/html/._week43-bs017.html
index 394a89817..4745ec303 100644
--- a/doc/pub/week43/html/._week43-bs017.html
+++ b/doc/pub/week43/html/._week43-bs017.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -245,7 +310,7 @@ asymptotically consistent
diff --git a/doc/pub/week43/html/._week43-bs018.html b/doc/pub/week43/html/._week43-bs018.html
index a14ad6cff..76b07e60c 100644
--- a/doc/pub/week43/html/._week43-bs018.html
+++ b/doc/pub/week43/html/._week43-bs018.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
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
@@ -209,6 +272,9 @@ prediction." Another i
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
@@ -184,7 +247,7 @@ First we import our libraries
-
importos
+
importosimporttimeimportnumpyasnpimporttensorflowastf
@@ -198,7 +261,7 @@ Next we define our hyperparameters and import our data the usual way
@@ -198,7 +261,7 @@ our case we are trying to predict MNIST images (\( 28\times 28 \) pixels).
-
defgenerator_model():
+
defgenerator_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
@@ -264,7 +327,7 @@ classifier.
-
defdiscriminator_model():
+
defdiscriminator_model():
""" The discriminator is a convolutional neural network based image classifier """
@@ -316,6 +379,11 @@ classifier.
@@ -327,7 +395,7 @@ classifier.
diff --git a/doc/pub/week43/html/._week43-bs021.html b/doc/pub/week43/html/._week43-bs021.html
index 0defc7904..8aeccea75 100644
--- a/doc/pub/week43/html/._week43-bs021.html
+++ b/doc/pub/week43/html/._week43-bs021.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
Now we have everything we need to define our training step, which we will apply
@@ -183,7 +246,7 @@ computation time.
-
@tf.function
+
@tf.function
deftrain_step(images):
noise = tf.random.normal([BATCH_SIZE, noise_dimension])
@@ -214,7 +277,7 @@ this code here, but comment it out in the training loop.
defgenerate_and_save_images(model, epoch, test_input):
# we're making inferences here
predictions = model(test_input, training=False)
@@ -249,6 +312,13 @@ this code here, but comment it out in the training loop.
@@ -260,7 +330,7 @@ this code here, but comment it out in the training loop.
diff --git a/doc/pub/week43/html/._week43-bs023.html b/doc/pub/week43/html/._week43-bs023.html
index c334415b2..e08f90f9f 100644
--- a/doc/pub/week43/html/._week43-bs023.html
+++ b/doc/pub/week43/html/._week43-bs023.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
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.
@@ -180,7 +243,7 @@ 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,
@@ -194,7 +257,7 @@ Now we define our training loop
-
deftrain(dataset, epochs):
+
deftrain(dataset, epochs):
generator_loss_list = []
discriminator_loss_list = []
@@ -231,7 +294,7 @@ there is a folder of a pretrained network already included in the repository.
-
train(train_dataset, EPOCHS)
+
train(train_dataset, EPOCHS)
And here is the result of training our model for 100 epochs
@@ -248,7 +311,7 @@ on your computer setup we now load in the model which produced the above gif.
defgenerate_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)
@@ -203,7 +266,7 @@ input. Let us try and see what we get
-
defplot_result(generated_images, number=100):
+
defplot_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))
@@ -218,7 +281,7 @@ input. Let us try and see what we get
@@ -250,7 +322,7 @@ plot_result(generated_images)
diff --git a/doc/pub/week43/html/._week43-bs025.html b/doc/pub/week43/html/._week43-bs025.html
index d537fe4e7..343fa7ae9 100644
--- a/doc/pub/week43/html/._week43-bs025.html
+++ b/doc/pub/week43/html/._week43-bs025.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
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
@@ -182,7 +245,7 @@ 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,
@@ -209,7 +272,7 @@ 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))
@@ -236,6 +299,16 @@ distribution which qualitatively looks a whole lot like the MNIST dataset.
@@ -247,7 +320,7 @@ distribution which qualitatively looks a whole lot like the MNIST dataset.
diff --git a/doc/pub/week43/html/._week43-bs026.html b/doc/pub/week43/html/._week43-bs026.html
index 40011026c..75fd0a2e5 100644
--- a/doc/pub/week43/html/._week43-bs026.html
+++ b/doc/pub/week43/html/._week43-bs026.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Deep Learning: Recurrent Neural Networks and other methods
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,59 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -123,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Deep Learning: Recurrent Neural Networks and other methods
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
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
@@ -185,7 +248,7 @@ latent space.
-
definterpolation(point_1, point_2, n_steps=10):
+
definterpolation(point_1, point_2, n_steps=10):
ratios = np.linspace(0, 1, num=n_steps)
vectors = []
for i, ratio inenumerate(ratios):
@@ -199,7 +262,7 @@ Now we have all we need to do our interpolation analysis.
Basic ideas of the Principal Component Analysis (PCA)
-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.
+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.
-A recurrent neural network (RNN) looks very much like a feedforward
-neural network, except that it also has connections pointing
-backward.
+We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition)
-
-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.
+
+
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.
Introducing the Covariance and Correlation functions
-Text to come.
+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}.
+$$
+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
-
-
+In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression
+we defined the design/feature matrix \( \boldsymbol{X} \) as
-
-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.
+$$
+\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},
+$$
-
-
# For matrices and calculations
-importnumpyasnp
-# For machine learning (backend for keras)
-importtensorflowastf
-# User-friendly machine learning library
-# Front end for TensorFlow
-importtensorflow.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.
-fromtensorflow.kerasimport datasets, layers, models
-fromtensorflow.keras.layersimport Input
-fromtensorflow.kerasimport regularizers
-fromtensorflow.keras.modelsimport Model, Sequential
-fromtensorflow.keras.layersimport Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-fromtimeitimport default_timer as timer
-# For plotting
-importmatplotlib.pyplotasplt
+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}.
+$$
-
-# 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])
-
+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 \)
-
-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.
+$$
+\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},
+$$
-
-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
-defformat_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 inrange(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.
-
-defrnn(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
-
@@ -332,6 +271,14 @@ y values far removed from the training data set.
@@ -343,7 +290,7 @@ y values far removed from the training data set.
diff --git a/doc/pub/week43/html/._week43-bs032.html b/doc/pub/week43/html/._week43-bs032.html
index 859844ed0..825fadb94 100644
--- a/doc/pub/week43/html/._week43-bs032.html
+++ b/doc/pub/week43/html/._week43-bs032.html
@@ -1,15 +1,15 @@
-
+
-
+
-Week 43: Convolutional Neural Networks and Recurrent Neural Networks
+Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
@@ -41,78 +41,90 @@ Automatically generated HTML file from DocOnce source
@@ -142,7 +154,7 @@ MathJax.Hub.Config({
- Week 43: Convolutional Neural Networks and Recurrent Neural Networks
+ Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis
deftest_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 inrange (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
-assertlen(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)
-
-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.
+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.
-
defrnn_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
-assertlen(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)
+
-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.
+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).
-
deflstm_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
-
-defdnn2_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
-assertlen(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
-assertlen(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)
+
importnumpyasnp
+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.
+
+
Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
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)
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.
-
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
-importnumpyasnp
-# For machine learning (backend for keras)
-importtensorflowastf
-# User-friendly machine learning library
-# Front end for TensorFlow
-importtensorflow.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.
-fromtensorflow.kerasimport datasets, layers, models
-fromtensorflow.keras.layersimport Input
-fromtensorflow.kerasimport regularizers
-fromtensorflow.keras.modelsimport Model, Sequential
-fromtensorflow.keras.layersimport Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-fromtimeitimport default_timer as timer
-# For plotting
-importmatplotlib.pyplotasplt
-
-
-# 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
-defformat_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 inrange(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.
-
-defrnn(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
-
-
-
-
-
-
-
-
-
deftest_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 inrange (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
-assertlen(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.
-
-
-
-
-
-
-
-
-
-
defrnn_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
-assertlen(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)
-
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.
-
-
-
-
-
-
-
-
-
-
deflstm_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
-
-defdnn2_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
-assertlen(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
-assertlen(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
-
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
-
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
-
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.
-
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
-
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
-
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).
-
-
-
-
-
-
-
-
-
-
defgenerator_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.
-
-
-
-
-
-
-
-
-
-
defdiscriminator_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.
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
-
-
-
-
-
-
-
-
-
-
defgenerator_loss(fake_output):
- loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
- return loss
-
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.
-
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.
-
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)
-
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.
-
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
-
-
-
-
-
-
-
-
-
-
defgenerate_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
-
-defgenerate_images(latent_points):
- # notice we set training to false because we are making inferences
- generated_images = restored_generator.predict(latent_points)
-
- return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
defplot_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 inrange(int(np.sqrt(number))):
- for j inrange(int(np.sqrt(number))):
- axs[i, j].imshow(generated_images[i*j], cmap='Greys')
- axs[i, j].axis('off')
-
- plt.show()
-
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.
-
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.
-
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.
-
-
-
-
-
-
-
-
-
-
definterpolation(point_1, point_2, n_steps=10):
- ratios = np.linspace(0, 1, num=n_steps)
- vectors = []
- for i, ratio inenumerate(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.
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.
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
-
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
-
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
-
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
-
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
-
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 \)
-
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} \)
-
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.
-
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).
-
-
-
-
-
-
-
-
-
-
importnumpyasnp
-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
We expand this model to the Franke function discussed above.
-
-
-
-
-
-
-
-
-
# Common imports
-importnumpyasnp
-importpandasaspd
-
-
-defFrankeFunction(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
-
-
-defcreate_X(x, y, n ):
- iflen(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 inrange(1,n+1):
- q =int((i)*(i+1)/2)
- for k inrange(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
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
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}] \).
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.
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):
-
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 \).
-
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
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.
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 inrange(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
-fromsklearn.decompositionimport 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
-
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
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.
-
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
-
-
-
-
-
-
-
-
-
importnumpyasnp
-importpandasaspd
-fromIPython.displayimport 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
-fromsklearn.decompositionimport 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.
-
-
-
-
-
-
-
-
-
importmatplotlib.pyplotasplt
-importnumpyasnp
-fromsklearn.model_selectionimport train_test_split
-fromsklearn.datasetsimport load_breast_cancer
-fromsklearn.linear_modelimport 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
-fromsklearn.preprocessingimport 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
-fromsklearn.decompositionimport 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:
-
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:
-
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
-
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.
Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
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:
+
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)
@@ -275,30 +267,35 @@ MathJax.Hub.Config({
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)
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
-
Till now our focus has been, including convolutional neural networks
+
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
+
+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
@@ -306,24 +303,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.
-
The following code provides an example of how recurrent neural
+
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
+
# For matrices and calculationsimportnumpyasnp# For machine learning (backend for keras)importtensorflowastf
@@ -450,26 +430,14 @@ 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
-
The way the recurrent neural networks are trained in this program
+
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
@@ -479,9 +447,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
@@ -495,8 +463,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.
-
+
@@ -504,14 +472,10 @@ y values far removed from the training data set.
+
-
-
-
-
-
-
# FORMAT_DATA
+
# FORMAT_DATAdefformat_data(data, length_of_sequence = 2):
""" Inputs:
@@ -583,33 +547,16 @@ 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
+
+
-
-
-
-
-
-
deftest_rnn (x1, y_test, plot_min, plot_max):
+
deftest_rnn (x1, y_test, plot_min, plot_max):
""" Inputs: x1 (a list or numpy array): The complete x component of the data set
@@ -700,26 +647,14 @@ 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
-
Changing the size of the recurrent neural network and its parameters
+
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
@@ -729,16 +664,11 @@ 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.
-
defrnn_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
@@ -824,33 +754,21 @@ 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
-
Besides a simple recurrent neural network layer, there are two other
+
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
@@ -858,16 +776,11 @@ 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.
-
deflstm_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
@@ -1057,26 +970,14 @@ 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
+
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
@@ -1087,24 +988,26 @@ 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 are a type of unsupervised machine learning
+
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 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
-
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}
@@ -1129,11 +1032,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
-
During learning both of the networks maximize their own reward function, so that
+
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
@@ -1173,12 +1078,14 @@ 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
-
At convergence we have
+
More about the Learning Process
+
+
+At convergence we have
$$
\begin{equation}
@@ -1188,7 +1095,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)
@@ -1198,10 +1105,9 @@ $$
\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
-
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
@@ -1227,57 +1134,37 @@ 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
-
-
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).
-
+
-
-
-
-
-
-
defgenerator_model():
+
defgenerator_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
@@ -1413,34 +1266,16 @@ 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.
-
+
-
-
-
-
-
-
defdiscriminator_model():
+
defdiscriminator_model():
""" The discriminator is a convolutional neural network based image classifier """
@@ -1469,203 +1304,86 @@ 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.
+
+
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
-
+
-
-
-
-
-
-
defgenerator_loss(fake_output):
+
defgenerator_loss(fake_output):
loss = cross_entropy(tf.ones_like(fake_output), fake_output)
return loss
-
Now we have everything we need to define our training step, which we will apply
+
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.
-
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.
-
defgenerate_and_save_images(model, epoch, test_input):
# we're making inferences here
predictions = model(test_input, training=False)
@@ -1728,68 +1428,33 @@ 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)
-
To train simply call this function. Warning: this might take a long time so
+
+
+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)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
train(train_dataset, EPOCHS)
+
+
+And here is the result of training our model for 100 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.
-
We have successfully loaded in our latest model. Let us now play around a bit
+
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
-
defgenerate_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)
@@ -1930,26 +1545,11 @@ input. Let us try and see what we get
generated_images = restored_generator.predict(latent_points)
return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
-
-
-
-
-
-
defplot_result(generated_images, number=100):
+
defplot_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))
@@ -1960,60 +1560,27 @@ input. Let us try and see what we get
axs[i, j].axis('off')
plt.show()
-
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.
-
+
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.
-
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.
-
+
-
-
-
-
-
-
definterpolation(point_1, point_2, n_steps=10):
+
definterpolation(point_1, point_2, n_steps=10):
ratios = np.linspace(0, 1, num=n_steps)
vectors = []
for i, ratio inenumerate(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.
+
Basic ideas of the Principal Component Analysis (PCA)
-
The principal component analysis deals with the problem of fitting a
+
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)
+
+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.
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
-
+
Introducing the Covariance and Correlation functions
-
Suppose we have defined two vectors
+
+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
-
+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
-
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}
@@ -2259,27 +1768,26 @@ 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
-
+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}
@@ -2292,11 +1800,13 @@ $$
\end{bmatrix},
$$
-
+
The Numpy function np.cov calculates the covariance elements using
+
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} \)
-
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 packagesimportnumpyasnp
n = 100
x = np.random.normal(size=n)
@@ -2353,40 +1860,23 @@ y = 4+3*
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
+
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).
-
+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).
+
-
-
-
-
-
-
importnumpyasnp
+
importnumpyasnp
n = 100# define two vectors
x = np.random.random(size=n)
@@ -2407,40 +1897,26 @@ 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
-
We whow here how we can set up the correlation matrix using pandas, as done in this simple code
+
Using Pandas
+
+
+We whow here how we can set up the correlation matrix using pandas, as done in this simple code
+
-
-
-
-
-
-
importnumpyasnp
+
importnumpyasnpimportpandasaspd
n = 10
x = np.random.normal(size=n)
@@ -2453,35 +1929,19 @@ 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.
+
And then the Franke Function
+
+We expand this model to the Franke function discussed above.
+
+
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
-
We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as
+
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} \)
+
+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}\\
@@ -2565,11 +2015,13 @@ x_{10} & x_{11}\\
\end{bmatrix}.
$$
-
+
-
Computing the Expectation Values
-
If we then compute the expectation value
+
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}\\
@@ -2577,56 +2029,63 @@ 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
-
We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as
+
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} \).
+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
-
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} \).
-
+
More on the PCA Theorem
-
The eigenvalues tell us then how much we need to stretch the
+
+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
@@ -2637,15 +2096,19 @@ 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.
+
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.
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}}] \).
@@ -2664,36 +2128,34 @@ $$
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
+
+
+
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):
-
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 \).
-
+
-
-
-
-
-
-
importnumpyasnp
+
importnumpyasnpimportpandasaspdimportmatplotlib.pyplotaspltfromIPython.displayimport display
@@ -2701,72 +2163,44 @@ 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
-
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
+
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
+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
@@ -2775,56 +2209,35 @@ 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
+
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 \).
+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))
@@ -2837,38 +2250,27 @@ Cov[1,0]
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.
-
+
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 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
@@ -2876,34 +2278,33 @@ following tasks:
Then we project the mean centered data onto the first and second principal components, and plot the projected data.
+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.
-
+
Collecting all Steps
-
The code here outlines some of the elements we could include in the
+
+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
+
# diagonalize and obtain eigenvalues, not necessarily sorted
EigValues, EigVectors = np.linalg.eig(Cov)
# sort eigenvectors and eigenvalues#permute = EigValues.argsort()
@@ -2924,90 +2325,83 @@ 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
-
We assume now that we have a design matrix \( \boldsymbol{X} \) which has been
+
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
+
+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
+
The PCA Theorem
-
We are almost there, we have obtained a relation between minimizing
+
+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
+
+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
-
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} \).
-
+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
-
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
-
Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
+
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
+
#thereafter we do a PCA with Scikit-learnfromsklearn.decompositionimport 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.
-
+
-
-
-
-
-
-
importmatplotlib.pyplotasplt
+
importmatplotlib.pyplotaspltimportnumpyasnpfromsklearn.model_selectionimport train_test_split
fromsklearn.datasetsimport load_breast_cancer
@@ -3217,104 +2540,59 @@ 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.
-
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
+
+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:
-
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:
-
One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
+
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
+
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
+
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.
@@ -3323,49 +2601,41 @@ 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
-
There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
+
Other techniques
+
+
+There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
+
+
+Here are some of the most popular:
-
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.
Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
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:
+
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)
@@ -352,30 +272,35 @@ MathJax.Hub.Config({
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)
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
-
Till now our focus has been, including convolutional neural networks
+
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
+
+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
@@ -383,24 +308,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.
-
The following code provides an example of how recurrent neural
+
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
+
# For matrices and calculationsimportnumpyasnp# For machine learning (backend for keras)importtensorflowastf
@@ -527,26 +435,14 @@ 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
-
The way the recurrent neural networks are trained in this program
+
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
@@ -556,9 +452,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
@@ -572,8 +468,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.
-
+
@@ -581,14 +477,10 @@ y values far removed from the training data set.
+
-
-
-
-
-
-
# FORMAT_DATA
+
# FORMAT_DATAdefformat_data(data, length_of_sequence =2):
""" Inputs:
@@ -660,33 +552,16 @@ 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
+
+
-
-
-
-
-
-
deftest_rnn (x1, y_test, plot_min, plot_max):
+
deftest_rnn (x1, y_test, plot_min, plot_max):
""" Inputs: x1 (a list or numpy array): The complete x component of the data set
@@ -777,26 +652,14 @@ 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
-
Changing the size of the recurrent neural network and its parameters
+
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
@@ -806,16 +669,11 @@ 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.
-
defrnn_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
@@ -901,33 +759,21 @@ 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
-
Besides a simple recurrent neural network layer, there are two other
+
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
@@ -935,16 +781,11 @@ 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.
-
deflstm_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
@@ -1134,26 +975,14 @@ 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
+
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
@@ -1164,24 +993,26 @@ 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 are a type of unsupervised machine learning
+
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 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
-
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}
@@ -1206,11 +1037,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
-
During learning both of the networks maximize their own reward function, so that
+
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
@@ -1250,12 +1083,14 @@ 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
-
At convergence we have
+
More about the Learning Process
+
+
+At convergence we have
$$
\begin{equation}
@@ -1265,7 +1100,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)
@@ -1275,10 +1110,9 @@ $$
\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
-
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
@@ -1304,57 +1139,37 @@ 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
-
-
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).
-
+
-
-
-
-
-
-
defgenerator_model():
+
defgenerator_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
@@ -1490,34 +1271,16 @@ 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.
-
+
-
-
-
-
-
-
defdiscriminator_model():
+
defdiscriminator_model():
""" The discriminator is a convolutional neural network based image classifier """
@@ -1546,203 +1309,86 @@ 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.
+
+
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
-
+
-
-
-
-
-
-
defgenerator_loss(fake_output):
+
defgenerator_loss(fake_output):
loss = cross_entropy(tf.ones_like(fake_output), fake_output)
return loss
-
Now we have everything we need to define our training step, which we will apply
+
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.
-
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.
-
defgenerate_and_save_images(model, epoch, test_input):
# we're making inferences here
predictions = model(test_input, training=False)
@@ -1805,68 +1433,33 @@ 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)
-
To train simply call this function. Warning: this might take a long time so
+
+
+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)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
train(train_dataset, EPOCHS)
+
+
+And here is the result of training our model for 100 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.
-
We have successfully loaded in our latest model. Let us now play around a bit
+
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
-
defgenerate_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)
@@ -2007,26 +1550,11 @@ input. Let us try and see what we get
generated_images = restored_generator.predict(latent_points)
return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
-
-
-
-
-
-
defplot_result(generated_images, number=100):
+
defplot_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))
@@ -2037,60 +1565,27 @@ input. Let us try and see what we get
axs[i, j].axis('off')
plt.show()
-
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.
-
+
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.
-
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.
-
+
-
-
-
-
-
-
definterpolation(point_1, point_2, n_steps=10):
+
definterpolation(point_1, point_2, n_steps=10):
ratios = np.linspace(0, 1, num=n_steps)
vectors = []
for i, ratio inenumerate(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.
+
Basic ideas of the Principal Component Analysis (PCA)
-
The principal component analysis deals with the problem of fitting a
+
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)
+
+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.
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
-
+
Introducing the Covariance and Correlation functions
-
Suppose we have defined two vectors
+
+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
-
+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
-
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}
@@ -2336,27 +1773,26 @@ 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
-
+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}
@@ -2369,11 +1805,13 @@ $$
\end{bmatrix},
$$
-
+
The Numpy function np.cov calculates the covariance elements using
+
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} \)
-
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 packagesimportnumpyasnp
n =100
x = np.random.normal(size=n)
@@ -2430,40 +1865,23 @@ y =4+3*
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
+
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).
-
+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).
+
-
-
-
-
-
-
importnumpyasnp
+
importnumpyasnp
n =100# define two vectors
x = np.random.random(size=n)
@@ -2484,40 +1902,26 @@ 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
-
We whow here how we can set up the correlation matrix using pandas, as done in this simple code
+
Using Pandas
+
+
+We whow here how we can set up the correlation matrix using pandas, as done in this simple code
+
-
-
-
-
-
-
importnumpyasnp
+
importnumpyasnpimportpandasaspd
n =10
x = np.random.normal(size=n)
@@ -2530,35 +1934,19 @@ Xpd = pd.print(Xpd)
correlation_matrix = Xpd.corr()
print(correlation_matrix)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
And then the Franke Function
-
We expand this model to the Franke function discussed above.
+
And then the Franke Function
+
+We expand this model to the Franke function discussed above.
+
+
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
-
We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as
+
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} \)
+
+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}\\
@@ -2642,11 +2020,13 @@ x_{10} & x_{11}\\
\end{bmatrix}.
$$
-
+
-
Computing the Expectation Values
-
If we then compute the expectation value
+
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}\\
@@ -2654,56 +2034,63 @@ 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
-
We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as
+
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} \).
+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
-
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} \).
-
+
More on the PCA Theorem
-
The eigenvalues tell us then how much we need to stretch the
+
+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
@@ -2714,15 +2101,19 @@ 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.
+
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.
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}}] \).
@@ -2741,36 +2133,34 @@ $$
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
+
+
+
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):
-
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 \).
-
+
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
-
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
+
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
+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
@@ -2852,56 +2214,35 @@ 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
+
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 \).
+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))
@@ -2914,38 +2255,27 @@ Cov[1,0]
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.
-
+
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 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
@@ -2953,34 +2283,33 @@ following tasks:
Then we project the mean centered data onto the first and second principal components, and plot the projected data.
+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.
-
+
Collecting all Steps
-
The code here outlines some of the elements we could include in the
+
+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
+
# diagonalize and obtain eigenvalues, not necessarily sorted
EigValues, EigVectors = np.linalg.eig(Cov)
# sort eigenvectors and eigenvalues#permute = EigValues.argsort()
@@ -3001,90 +2330,83 @@ 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
-
We assume now that we have a design matrix \( \boldsymbol{X} \) which has been
+
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
+
+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
+
The PCA Theorem
-
We are almost there, we have obtained a relation between minimizing
+
+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
+
+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
-
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} \).
-
+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
-
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
-
Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
+
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
+
#thereafter we do a PCA with Scikit-learnfromsklearn.decompositionimport 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.
-
+
-
-
-
-
-
-
importmatplotlib.pyplotasplt
+
importmatplotlib.pyplotaspltimportnumpyasnpfromsklearn.model_selectionimport train_test_split
fromsklearn.datasetsimport load_breast_cancer
@@ -3294,104 +2545,59 @@ 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.
-
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
+
+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:
-
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:
-
One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
+
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
+
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
+
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.
@@ -3400,49 +2606,41 @@ 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
-
There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
+
Other techniques
+
+
+There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
+
+
+Here are some of the most popular:
-
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/pub/week43/ipynb/ipynb-week43-src.tar.gz b/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz
index 8d094f6c9..c6261b79a 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 cae677b85..66765cf9b 100644
--- a/doc/pub/week43/ipynb/week43.ipynb
+++ b/doc/pub/week43/ipynb/week43.ipynb
@@ -2,58 +2,32 @@
"cells": [
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "fc0e9b18",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
- "\n",
- ""
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "2c6b6382",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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"
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "2624a425",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
+ "\n",
+ "\n",
+ "\n",
"## 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",
@@ -62,60 +36,29 @@
"\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)"
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "d0b80f33",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "* [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",
"## Reading Recommendations\n",
"\n",
"* Goodfellow et al, chapter 10 on Recurrent NNs, chapters 11 and 12 on various practicalities around deep learning are also recommended.\n",
"\n",
- "* Aurelien Geron, chapter 14 on RNNs."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "c6e4412c",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "* Aurelien Geron, chapter 14 on RNNs.\n",
+ "\n",
"## Summary on Deep Learning Methods\n",
"\n",
"We have studied fully connected neural networks (also called artifical nueral networks) and convolutional neural networks (CNNs).\n",
"\n",
- "The first type of deep learning networks work very well on homogeneous and structured input data while CCNs are normally tailored to recognizing images."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "266676bd",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "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",
"## CNNs in brief\n",
"\n",
"In summary:\n",
@@ -135,22 +78,11 @@
"[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."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "6d6fc0e4",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "This is where recurrent nueral networks (RNNs) come to our rescue.\n",
+ "\n",
"## Recurrent neural networks: Overarching view\n",
"\n",
"Till now our focus has been, including convolutional neural networks\n",
@@ -168,300 +100,23 @@
"fixed-sized inputs like all the nets we have discussed so far. For\n",
"example, they can take sentences, documents, or audio samples as\n",
"input, making them extremely useful for natural language processing\n",
- "systems such as automatic translation and speech-to-text."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "bf281e51",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "systems such as automatic translation and speech-to-text.\n",
+ "\n",
+ "\n",
"## Set up of an RNN\n",
"\n",
- "More to text to be added"
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "07498ec3",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "More to text to be added\n",
+ "\n",
"## A simple example"
]
},
{
"cell_type":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K5CYII=\n",
- "text/plain": [
- "
"
- ]
- },
- "metadata": {
- "needs_background": "light"
- },
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Time: 7.055008993000001\n"
- ]
- }
- ],
-=======
- "id": "5f584ce6",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
"outputs": [],
->>>>>>> origin/master
"source": [
"def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
" \"\"\"\n",
@@ -2687,14 +810,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "3c028690",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Generative Models\n",
"\n",
@@ -2710,20 +826,8 @@
"boundaries in the data space (often high dimensional), while generative models\n",
"try to model how data is placed throughout the space.\n",
"\n",
- "**Note**: this material is thanks to Linus Ekstrøm."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "a005479e",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "**Note**: this material is thanks to Linus Ekstrøm. \n",
+ "\n",
"## Generative Adversarial Networks\n",
"\n",
"**Generative Adversarial Networks** are a type of unsupervised machine learning\n",
@@ -2739,14 +843,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "d0dffd1b",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"\n",
"\n",
@@ -2761,14 +858,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "4c7b94fe",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Discriminator\n",
"The discriminator attempts to distinguish between samples drawn from the\n",
@@ -2780,14 +870,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "61339180",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"\n",
"\n",
@@ -2802,14 +885,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "7a9204c2",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -2819,14 +895,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "dc620460",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"\n",
"\n",
@@ -2841,14 +910,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "274b6221",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"determines the reward for the discriminator, while the generator gets the\n",
"conjugate reward"
@@ -2856,14 +918,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "7ac921a1",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"\n",
"\n",
@@ -2878,14 +933,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "b42f7081",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Learning Process\n",
"\n",
@@ -2904,20 +952,9 @@
" criteria for GANs. The discriminator feedback gets less meaningful over time,\n",
" if we continue training after this point then the generator is effectively\n",
" training on junk data which can undo the learning up to that point. Therefore,\n",
- " we stop training when the discriminator starts outputting $1/2$ everywhere."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "1f9c6701",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ " we stop training when the discriminator starts outputting $1/2$ everywhere.\n",
+ "\n",
+ "\n",
"## More about the Learning Process\n",
"\n",
"At convergence we have"
@@ -2925,14 +962,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "89b9067e",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"\n",
"\n",
@@ -2948,28 +978,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "2264c357",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"The default choice for $v$ is"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "7a087f74",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"\n",
"\n",
@@ -2986,14 +1002,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "e6557946",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -3002,14 +1011,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "50dd2a46",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"\n",
"\n",
@@ -3024,31 +1026,12 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "7e997d75",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"is convex in $\\theta^{(g)} then the procedure is guaranteed to converge and is\n",
"asymptotically consistent\n",
- "( [Seth Lloyd on QuGANs](https://arxiv.org/pdf/1804.09139.pdf) )."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "d64335ff",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "( [Seth Lloyd on QuGANs](https://arxiv.org/pdf/1804.09139.pdf) ).\n",
+ "\n",
"## Additional References\n",
"This is in\n",
"general not the case and it is possible to get situations where the training\n",
@@ -3060,20 +1043,9 @@
"Direct quote: \"In this best-performing formulation, the generator aims to\n",
"increase the log probability that the discriminator makes a mistake, rather than\n",
"aiming to decrease the log probability that the discriminator makes the correct\n",
- "prediction.\" [Another interesting read](https://arxiv.org/abs/1701.00160)"
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "f35bc917",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "prediction.\" [Another interesting read](https://arxiv.org/abs/1701.00160)\n",
+ "\n",
+ "\n",
"## 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",
@@ -3086,15 +1058,9 @@
{
"cell_type": "code",
"execution_count": 7,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "44c10a9a",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"import os\n",
@@ -3108,14 +1074,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "461c8f05",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"Next we define our hyperparameters and import our data the usual way"
]
@@ -3123,26 +1082,10 @@
{
"cell_type": "code",
"execution_count": 8,
-<<<<<<< HEAD
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n",
- "11493376/11490434 [==============================] - 1s 0us/step\n"
- ]
- }
- ],
-=======
- "id": "5ca09c8c",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
"outputs": [],
->>>>>>> origin/master
"source": [
"BUFFER_SIZE = 60000\n",
"BATCH_SIZE = 256\n",
@@ -3163,14 +1106,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "4872f2ad",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## MNIST and GANs\n",
"\n",
@@ -3179,49 +1115,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 10,
- "metadata": {},
- "outputs": [
- {
- "ename": "TypeError",
- "evalue": "Invalid shape (28, 28, 1) for image data",
- "output_type": "error",
- "traceback": [
- "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
- "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mimshow\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtrain_images\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcmap\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m'Greys'\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 2\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mshow\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[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py\u001b[0m in \u001b[0;36mimshow\u001b[0;34m(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, data, **kwargs)\u001b[0m\n\u001b[1;32m 2643\u001b[0m \u001b[0mfilterrad\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m4.0\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mimlim\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcbook\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdeprecation\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_deprecated_parameter\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2644\u001b[0m resample=None, url=None, *, data=None, **kwargs):\n\u001b[0;32m-> 2645\u001b[0;31m __ret = gca().imshow(\n\u001b[0m\u001b[1;32m 2646\u001b[0m \u001b[0mX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcmap\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcmap\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnorm\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mnorm\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0maspect\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0maspect\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2647\u001b[0m \u001b[0minterpolation\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0minterpolation\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0malpha\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0malpha\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mvmin\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mvmin\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/__init__.py\u001b[0m in \u001b[0;36minner\u001b[0;34m(ax, data, *args, **kwargs)\u001b[0m\n\u001b[1;32m 1563\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0minner\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mNone\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\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[1;32m 1564\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1565\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0mmap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msanitize_sequence\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\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 1566\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1567\u001b[0m \u001b[0mbound\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnew_sig\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbind\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0max\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/cbook/deprecation.py\u001b[0m in \u001b[0;36mwrapper\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 356\u001b[0m \u001b[0;34mf\"%(removal)s. If any parameter follows {name!r}, they \"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 357\u001b[0m f\"should be pass as keyword, not positionally.\")\n\u001b[0;32m--> 358\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\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 359\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 360\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mwrapper\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/cbook/deprecation.py\u001b[0m in \u001b[0;36mwrapper\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 356\u001b[0m \u001b[0;34mf\"%(removal)s. If any parameter follows {name!r}, they \"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 357\u001b[0m f\"should be pass as keyword, not positionally.\")\n\u001b[0;32m--> 358\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\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 359\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 360\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mwrapper\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py\u001b[0m in \u001b[0;36mimshow\u001b[0;34m(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)\u001b[0m\n\u001b[1;32m 5624\u001b[0m resample=resample, **kwargs)\n\u001b[1;32m 5625\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 5626\u001b[0;31m \u001b[0mim\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_data\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\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 5627\u001b[0m \u001b[0mim\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_alpha\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0malpha\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5628\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mim\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_clip_path\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/image.py\u001b[0m in \u001b[0;36mset_data\u001b[0;34m(self, A)\u001b[0m\n\u001b[1;32m 696\u001b[0m if not (self._A.ndim == 2\n\u001b[1;32m 697\u001b[0m or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):\n\u001b[0;32m--> 698\u001b[0;31m raise TypeError(\"Invalid shape {} for image data\"\n\u001b[0m\u001b[1;32m 699\u001b[0m .format(self._A.shape))\n\u001b[1;32m 700\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;31mTypeError\u001b[0m: Invalid shape (28, 28, 1) for image data"
- ]
- },
- {
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAAQYAAAD8CAYAAACVSwr3AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAMX0lEQVR4nO3bX4il9X3H8fenuxEak0aJk5DuKt2WNbotsZiJkdA/pqHNrrlYAl5oQqUSWIQYcqkUmhRy01wUQoi6LLJIbrI3kXRTTKS0JBasjbPgvzUo05XqZAXXJKRgoLL67cWcpqfnO7vzzHr+7JD3CwbmeZ7fOefLMOc9zzzzTKoKSRr3G4seQNLFxzBIagyDpMYwSGoMg6TGMEhqNg1DkqNJXk3y7DmOJ8nXk6wmeTrJ9dMfU9I8DTljeBDYf57jB4C9o49DwP1vfyxJi7RpGKrqUeBn51lyEPhmrXscuCzJB6Y1oKT52zmF59gFvDy2vTba98rkwiSHWD+r4NJLL/3wNddcM4WXl3QuJ06ceK2qlrb6uGmEIRvs2/A+66o6AhwBWF5erpWVlSm8vKRzSfKfF/K4afxVYg24cmx7N3B6Cs8raUGmEYbjwO2jv07cCPyiqtqvEZK2j01/lUjyLeAm4Ioka8CXgXcAVNVh4GHgZmAV+CVwx6yGlTQfm4ahqm7b5HgBn5/aRJIWzjsfJTWGQVJjGCQ1hkFSYxgkNYZBUmMYJDWGQVJjGCQ1hkFSYxgkNYZBUmMYJDWGQVJjGCQ1hkFSYxgkNYZBUmMYJDWGQVJjGCQ1hkFSYxgkNYZBUmMYJDWGQVJjGCQ1hkFSYxgkNYZBUmMYJDWG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IkHmXgWOjKFwB3JzkbFV9Zz4j/srQ74PXqup14PUkjwLXAYsIw5B57wD+rtZ/iV9N8iJwDfCj+Yy4JVt/j834oshO4BSwh/+7iPP7E2s+xf+/MPKjBV3AGTLrVazf3fmxRcy41Xkn1j/I4i4+DvnaXgv882jtO4FngT+4iOe9H/jb0efvB34CXLHA74ff4dwXH7f8HpvpGUPN7nbqRc36JeC9wH2jn8Jna0H/aTdw3ovCkFmr6sdJvg88DbwFPFBVC/m3/IFf268ADyZ5hvU33N1VtZB/x07yLeAm4Ioka8CXgXeMzbrl95i3REtqvPNRUmMYJDWGQVJjGCQ1hkFSYxgkNYZBUvM/YA1djXA4+xYAAAAASUVORK5CYII=\n",
- "text/plain": [
- "
"
- ]
- },
- "metadata": {
- "needs_background": "light"
- },
- "output_type": "display_data"
- }
- ],
-=======
"execution_count": 9,
- "id": "1248ad33",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
"outputs": [],
->>>>>>> origin/master
"source": [
"plt.imshow(train_images[0], cmap='Greys')\n",
"plt.show()"
@@ -3229,14 +1127,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "61808c2b",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -3251,17 +1142,10 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 11,
- "metadata": {},
-=======
"execution_count": 10,
- "id": "fe8867c5",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def generator_model():\n",
@@ -3325,14 +1209,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "48bd3c5b",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -3341,17 +1218,10 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 12,
- "metadata": {},
-=======
"execution_count": 11,
- "id": "c713c710",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def discriminator_model():\n",
@@ -3387,14 +1257,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "a1dc2608",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Other Models\n",
"Let us take a look at our models. **Note**: double click images for bigger view."
@@ -3402,31 +1265,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 13,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAADs0AAABoCAIAAACPechlAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nOzdd1wU19oH8LPLAqIoGkvsooKi2NCLveUaNYo1othNUFFjiTUm1xuTGGNiYonGJJZ4vfaAvQRbIgoqlqCgsTciKIqgSFEpMu8f581k75bZ3dmpO7/vH35gdnf2zHmec+Y847CrYxiGAAAAAAAAAAAAAAAAAAAAAAAAAAAAABjRy90AAAAAAAAAAAAAAAAAAAAAAAAAAAAAUBzcZwwAAAAAAAAAAAAAAAAAAAAAAAAAAACmcJ8xAAAAAAAAAAAAAAAAAAAAAAAAAAAAmMJ9xgAAAAAAAAAAAAAAAAAAAAAAAAAAAGDKYPxLfHz8kiVL5GoKgInp06e3adNG7lb8v4EDB8rdBFAW5CcAiA3zDGjWtm3b5G7C/0N9BErQpk2b6dOny92K/7dkyZL4+Hi5WwGgUTg/AoAyYa0CICBcCwIA3lAvAIAyoV4AUAKsEwCAH5Pz+P98nnFKSsr27dslbxKABdu3b09JSZG7FX/bvn17amqq3K0ApUB+AoDYMM+ANqWmpiqqHkF9BLI7ffq0oq59x8fHnz59Wu5WAGgOzo8AoFhYqwAICNeCAIAf1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lYSkm6ouY5LdKnERZDDhSrMoSQsVGEStkWiFrKVyMWx3JD8LNSx/NRc5YylvJTrhQEAAAAAAAAAAACA1nKfMQAAAAAAAAAAAAAwy33GAAAAAAAAAAAAAMAs9xkDAAAAAAAAAAAAALMuzz/0+PHj9P3ojK9fv/aMYUe9fv36/fv3uXsRnQwXqpJ80lNr8pG9tZhPw0zGrW3UcSXnh3hGo9H9+/dz9+Ivo9HIQVGi0WjUc0IrlvmR1rIGwFqlKva5FXKe7wZ17Dz7BVrL+Qf7BaY5J2RhnUAWjvdumJ/Hd168eHHxw8+fP3/8+JG6U93S7/eHw2HuXnTBcDh88ODBnTt3cnfk3MePH/v9fu5epCDDTcgnuQyHQ7WuhPNM6cynYSbj9uTJk9wdOWd/1IS5KarBYHB4eHh4eJi7I+faeVGSJgaDwWAwyN0LApkfaSdrAHrWKpWxz43NtSBiMF/XwH6BdnL+oWe/wBTnhFysE0jP8d4Z8/P4f+PxOGOHAAAAAAAAAAAAAIAWupS7AwAAAAAAAAAAAABA67jPGAAAAAAAAAAAAACY5T5jAAAAAAAAAAAAAGCW+4wBAAAAAAAAAAAAgFn/A1Ms5rws4XhiAAAAAElFTkSuQmCC\n",
- "text/plain": [
- ""
- ]
- },
- "execution_count": 13,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
-=======
"execution_count": 12,
- "id": "48dd8c9e",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
"outputs": [],
->>>>>>> origin/master
"source": [
"generator = generator_model()\n",
"plot_model(generator, show_shapes=True, rankdir='LR')"
@@ -3434,31 +1277,11 @@
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 14,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAACagAAABoCAIAAACRjBLSAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nO3deUAU9f8/8PfCgiKIeCAe4A2pqHl8SNA0q58ZCmqFoNhHC8UzKUw7rMz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JHYbtSUlL8/f3ljuJ/pKSkIDFFkpeXR9DvyQS5Bpow9smC9oFKgzSURUpKCkHhwz/QJ8sC81IbhFwTD8Y1UWEOaYPQX4kH50ZsCuZ7FMYRZbKm9mk/b9489klJScnDhw/lCwYIIaRr166urq5yR2HTPD09AwICAgIC5A7kb8ocCayGq6tr165d5Y7CRiHXgIWxTy60DwwNDZU7kL9hLiojT09PT09PuaOwUV27dn355Ze9vLzkDuRvFy9eRJ8sC8xLxYZcsykY10SFOaStwfGaqHBuxKZgvkdhHFEmy22fuvN8FcMwMgYEAAAAAAAAAAAAAAAAAGA+/McnAAAAAAAAAAAAAAAAAFg8XPgEAAAAAAAAAAAAAAAAAIuHC58AAAAAAAAAAAAAAAAAYPFw4RMAAAAAAAAAAAAAAAAALN7/B7wM+6hUMlHsAAAAAElFTkSuQmCC\n",
- "text/plain": [
- ""
- ]
- },
- "execution_count": 14,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
-=======
"execution_count": 13,
- "id": "0f581c34",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
"outputs": [],
->>>>>>> origin/master
"source": [
"discriminator = discriminator_model()\n",
"plot_model(discriminator, show_shapes=True, rankdir='LR')"
@@ -3466,31 +1289,17 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "9924cefc",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"Next we need a few helper objects we will use in training"
]
},
{
"cell_type": "code",
-<<<<<<< HEAD
- "execution_count": 15,
- "metadata": {},
-=======
"execution_count": 14,
- "id": "50712a5c",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n",
@@ -3500,14 +1309,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "ddf3f0e1",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -3519,15 +1321,9 @@
{
"cell_type": "code",
"execution_count": 15,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "19d93fd5",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def generator_loss(fake_output):\n",
@@ -3539,15 +1335,9 @@
{
"cell_type": "code",
"execution_count": 16,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "4432394d",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def discriminator_loss(real_output, fake_output):\n",
@@ -3560,14 +1350,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "bc7155dd",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"Next we define a kind of seed to help us compare the learning process over\n",
"multiple training epochs."
@@ -3576,15 +1359,9 @@
{
"cell_type": "code",
"execution_count": 17,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "5f8e2ac8",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"noise_dimension = 100\n",
@@ -3594,14 +1371,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "375ea5e6",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Training Step\n",
"\n",
@@ -3614,15 +1384,9 @@
{
"cell_type": "code",
"execution_count": 18,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "d30d0d7a",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"@tf.function\n",
@@ -3652,14 +1416,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "0f4e4419",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -3669,15 +1426,9 @@
{
"cell_type": "code",
"execution_count": 19,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "5d73f712",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def generate_and_save_images(model, epoch, test_input):\n",
@@ -3698,14 +1449,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "c9d625a0",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Checkpoints\n",
"Setting up checkpoints to periodically save our model during training so that\n",
@@ -3716,15 +1460,9 @@
{
"cell_type": "code",
"execution_count": 20,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "7b8e092d",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"# Setting up checkpoints to save model during training\n",
@@ -3738,14 +1476,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "d609d006",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"Now we define our training loop"
]
@@ -3753,15 +1484,9 @@
{
"cell_type": "code",
"execution_count": 21,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "6b070a66",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def train(dataset, epochs):\n",
@@ -3797,14 +1522,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "6adbeece",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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."
@@ -3813,15 +1531,9 @@
{
"cell_type": "code",
"execution_count": 22,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "d9d2967e",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"train(train_dataset, EPOCHS)"
@@ -3829,14 +1541,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "5ebfb622",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"And here is the result of training our model for 100 epochs\n",
"\n",
@@ -3847,15 +1552,9 @@
{
"cell_type": "code",
"execution_count": 23,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "beb99df1",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"from IPython.display import HTML\n",
@@ -3868,17 +1567,11 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "47c73def",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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."
]
@@ -3886,15 +1579,9 @@
{
"cell_type": "code",
"execution_count": 24,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "76c10c8e",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))\n",
@@ -3907,14 +1594,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "afcc9765",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Exploring the Latent Space\n",
"\n",
@@ -3927,15 +1607,9 @@
{
"cell_type": "code",
"execution_count": 25,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "6588a84c",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def generate_latent_points(number=100, scale_means=1, scale_stds=1):\n",
@@ -3959,15 +1633,9 @@
{
"cell_type": "code",
"execution_count": 26,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "8612bfe0",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def plot_result(generated_images, number=100):\n",
@@ -3986,15 +1654,9 @@
{
"cell_type": "code",
"execution_count": 27,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "50f8077e",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"generated_images = generate_images(generate_latent_points())\n",
@@ -4003,14 +1665,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "1583c26d",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Getting Results\n",
"We see that the generator generates images that look like MNIST\n",
@@ -4023,15 +1678,9 @@
{
"cell_type": "code",
"execution_count": 28,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "76a63595",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"plot_number = 225\n",
@@ -4054,14 +1703,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "7f697350",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -4073,15 +1715,9 @@
{
"cell_type": "code",
"execution_count": 29,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "0245f48d",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"plot_number = 400\n",
@@ -4093,30 +1729,11 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "88c2f763",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"A pretty cool result! We see that our generator indeed has learned a\n",
- "distribution which qualitatively looks a whole lot like the MNIST dataset."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "2a14475d",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "distribution which qualitatively looks a whole lot like the MNIST dataset.\n",
+ "\n",
"## 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",
@@ -4130,15 +1747,9 @@
{
"cell_type": "code",
"execution_count": 30,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "87bec507",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"def interpolation(point_1, point_2, n_steps=10):\n",
@@ -4152,14 +1763,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "50de7c62",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"Now we have all we need to do our interpolation analysis."
]
@@ -4167,15 +1771,9 @@
{
"cell_type": "code",
"execution_count": 31,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "169a4ddf",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"plot_number = 100\n",
@@ -4195,14 +1793,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "85ae3d2a",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Basic ideas of the Principal Component Analysis (PCA)\n",
"\n",
@@ -4221,20 +1812,9 @@
"\n",
"* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. \n",
"\n",
- "A good read is for example [Vidal, Ma and Sastry](https://www.springer.com/gp/book/9780387878102)."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "090721ed",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "A good read is for example [Vidal, Ma and Sastry](https://www.springer.com/gp/book/9780387878102).\n",
+ "\n",
+ "\n",
"## Introducing the Covariance and Correlation functions\n",
"\n",
"Before we discuss the PCA theorem, we need to remind ourselves about\n",
@@ -4246,14 +1826,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "ac9b9bf9",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
@@ -4264,28 +1837,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "4452b018",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"where for example"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "a876875d",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -4294,28 +1853,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "bd544bd6",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"With this definition and recalling that the variance is defined as"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "c16e6106",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
@@ -4324,28 +1869,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "82d97aac",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"we can rewrite the covariance matrix as"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "faf3e9a6",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
@@ -4356,14 +1887,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "3e9c4c64",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## More on the covariance\n",
"The covariance takes values between zero and infinity and may thus\n",
@@ -4375,14 +1899,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "f68a7ead",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -4391,14 +1908,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "29981a6f",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -4408,14 +1918,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "1c284543",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
@@ -4426,25 +1929,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "f4226b36",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
- "In the above example this is the function we constructed using **pandas**."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7cdc504e",
- "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"
@@ -4452,14 +1940,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "e5f4e808",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix}\n",
@@ -4475,14 +1956,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "b693c9da",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -4491,14 +1965,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "2c6171bc",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n",
@@ -4507,28 +1974,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "b613b25e",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"with a given vector"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "df517ed7",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -4537,14 +1990,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "417de4e9",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Simple Example\n",
"With these definitions, we can now rewrite our $2\\times 2$\n",
@@ -4555,14 +2001,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "1c0ee648",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
@@ -4578,14 +2017,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "a9b12654",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## The Correlation Matrix\n",
"\n",
@@ -4594,14 +2026,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "8f4547f0",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
@@ -4617,14 +2042,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "493b6037",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Numpy Functionality\n",
"\n",
@@ -4637,14 +2055,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "3158ec7d",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{W}^T = \\begin{bmatrix} x_0 & y_0 \\\\\n",
@@ -4659,14 +2070,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "00fe5e0c",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -4678,15 +2082,9 @@
{
"cell_type": "code",
"execution_count": 32,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "72724b57",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"# Importing various packages\n",
@@ -4703,14 +2101,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "ea4c06a4",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Correlation Matrix again\n",
"\n",
@@ -4724,15 +2115,9 @@
{
"cell_type": "code",
"execution_count": 33,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "c531bda3",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"import numpy as np\n",
@@ -4760,29 +2145,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "de5b39f6",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"We see that the matrix elements along the diagonal are one as they\n",
"should be and that the matrix is symmetric. Furthermore, diagonalizing\n",
"this matrix we easily see that it is a positive definite matrix.\n",
"\n",
- "The above procedure with **numpy** can be made more compact if we use **pandas**."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2e92766e",
- "metadata": {
- "editable": true
- },
- "source": [
+ "The above procedure with **numpy** can be made more compact if we use **pandas**.\n",
+ "\n",
"## Using Pandas\n",
"\n",
"We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code"
@@ -4791,15 +2161,9 @@
{
"cell_type": "code",
"execution_count": 34,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "2c212a03",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"import numpy as np\n",
@@ -4819,14 +2183,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "6dfd3cbc",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## And then the Franke Function\n",
"\n",
@@ -4836,15 +2193,9 @@
{
"cell_type": "code",
"execution_count": 35,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "1b22b6fd",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"# Common imports\n",
@@ -4894,30 +2245,15 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "c300052e",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"We note here that the covariance is zero for the first rows and\n",
"columns since all matrix elements in the design matrix were set to one\n",
"(we are fitting the function in terms of a polynomial of degree $n$). We would however not include the intercept\n",
"and wee can simply\n",
"drop these elements and construct a correlation\n",
- "matrix without them by centering our matrix elements by subtracting the mean of each column."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "86948c3e",
- "metadata": {
- "editable": true
- },
- "source": [
+ "matrix without them by centering our matrix elements by subtracting the mean of each column. \n",
+ "\n",
"## 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"
@@ -4925,14 +2261,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "b9e71c39",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
@@ -4941,28 +2270,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "cb255745",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "2bd67de5",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix}\n",
@@ -4976,14 +2291,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "dcfb0032",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Computing the Expectation Values\n",
"\n",
@@ -4992,14 +2300,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "4e60fe22",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
@@ -5011,28 +2312,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "c306e801",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"which is just"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "afb7f0cb",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5043,31 +2330,13 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "4cd98212",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n",
"\n",
- "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "d19211a1",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n",
+ "\n",
+ "\n",
"## Towards the PCA theorem\n",
"\n",
"We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as"
@@ -5075,14 +2344,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "c67cc4e9",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n",
@@ -5091,14 +2353,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "7b1eaa9b",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5110,14 +2365,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "2f6c8503",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5126,28 +2374,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "8a4112f7",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"since the matrix $\\boldsymbol{S}$ is not a data dependent matrix. Multiplying with $\\boldsymbol{S}$ from the left we have"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "f5ac5fa8",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n",
@@ -5156,28 +2390,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "9a6681bc",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"and since $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "4367f34d",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{S}_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}_i.\n",
@@ -5186,20 +2406,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "2a346c2d",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5210,20 +2424,8 @@
"these specific directions. Hopefully then we could leave it out\n",
"dimensions where the eigenvalues are very small. If $p$ is very large,\n",
"we could then aim at reducing $p$ to $l << p$ and handle only $l$\n",
- "features/predictors."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "59f55fef",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "features/predictors.\n",
+ "\n",
"## 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",
@@ -5232,14 +2434,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "ab36f66c",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{X}=\\begin{bmatrix}\n",
@@ -5255,14 +2450,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "b975e498",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5272,20 +2460,8 @@
"\n",
"* Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.\n",
"\n",
- "* Keep only those $l$ eigenvalues larger than a selected threshold value, discarding thus $p-l$ features since we expect small variations in the data here."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "f1065453",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "* 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",
"## Writing our own PCA code\n",
"\n",
"We will use a simple example first with two-dimensional data\n",
@@ -5294,14 +2470,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "0066482f",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\mu = (-1,2) \\qquad \\Sigma = \\begin{bmatrix} 4 & 2 \\\\\n",
@@ -5312,27 +2481,12 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "4f807a3f",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"Note that the mean refers to each column of data. \n",
"We will generate $n = 10000$ points $X = \\{ x_1, \\ldots, x_N \\}$ from\n",
- "this distribution, and store them in the $1000 \\times 2$ matrix $\\boldsymbol{X}$. This is our design matrix where we have forced the covariance and mean values to take specific values."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "e31a55ba",
- "metadata": {
- "editable": true
- },
- "source": [
+ "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",
"## 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$."
@@ -5341,15 +2495,9 @@
{
"cell_type": "code",
"execution_count": 36,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "c098cc4e",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"import numpy as np\n",
@@ -5364,25 +2512,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "0ea28cbe",
- "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": "05f17319",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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"
@@ -5390,14 +2523,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "d116f6f9",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\mu_n = \\frac{1}{n} \\sum_{i=1}^n x_i\n",
@@ -5406,28 +2532,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "9d26cd23",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"and the mean-centered data $\\bar{X} = \\{ \\bar{x}_1, \\ldots, \\bar{x}_n \\}$ takes the form"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "47051865",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\bar{x}_i = x_i - \\mu_n.\n",
@@ -5436,14 +2548,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "64c7a2e3",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5454,15 +2559,9 @@
{
"cell_type": "code",
"execution_count": 37,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "daf0ce1c",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"df = pd.DataFrame(X)\n",
@@ -5474,14 +2573,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "0cf49f56",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Scaling\n",
"Alternatively, we could use the functions we discussed\n",
@@ -5492,16 +2584,8 @@
"would then not get the same results, since we divide by the\n",
"variance. The diagonal covariance matrix elements will then be one,\n",
"while the non-diagonal ones need to be divided by $2\\sqrt{2}$ for our\n",
- "specific case."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "730806f0",
- "metadata": {
- "editable": true
- },
- "source": [
+ "specific case.\n",
+ "\n",
"## 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"
@@ -5509,14 +2593,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "ae8d7cc8",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5525,14 +2602,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "53c9bdde",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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"
@@ -5541,15 +2611,9 @@
{
"cell_type": "code",
"execution_count": 38,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "31e91d87",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"print(df.cov())\n",
@@ -5558,14 +2622,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "1aed4afb",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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."
@@ -5574,15 +2631,9 @@
{
"cell_type": "code",
"execution_count": 39,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "54c879c1",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"# extract the relevant columns from the centered design matrix of dim n x 2\n",
@@ -5602,32 +2653,13 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "7a0f246b",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Exploring\n",
"\n",
"Depending on the number of points $n$, we will get results that are close to the covariance values defined above.\n",
- "The plot shows how the data are clustered around a line with slope close to one. Is this expected? Try to change the covariance and the mean values. For example, try to make the variance of the first element much larger than that of the second diagonal element. Try also to shrink the covariance (the non-diagonal elements) and see how the data points are distributed."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "22931505",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "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",
"## 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",
@@ -5647,14 +2679,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "b62266c9",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"x_i \\approx \\tilde{x}_i = \\mu_n + \\langle x_i, v_0 \\rangle v_0\n",
@@ -5663,25 +2688,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "6f283411",
- "metadata": {
- "editable": true
- },
- "source": [
- "where $v_0$ is the first principal component."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "f2fb0eee",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5695,15 +2705,9 @@
{
"cell_type": "code",
"execution_count": 40,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "4f9bcd7e",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"# diagonalize and obtain eigenvalues, not necessarily sorted\n",
@@ -5731,29 +2735,10 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "ad5d8bd2",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "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",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "8447c3c3",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5762,31 +2747,30 @@
"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)."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b127c2a1",
- "metadata": {
- "editable": true
- },
- "source": [
+ "eigenvectors of the covariance(correlations matrix).\n",
+ "\n",
+ "\n",
+ "\n",
"## 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",
@@ -5797,14 +2781,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "83adaedf",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5813,28 +2790,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "3be07303",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"Taking the derivative with respect to $\\boldsymbol{w}_0$ we obtain"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "24f72531",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5843,28 +2806,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "6bf3baed",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"meaning that"
]
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "9e7ea828",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0\\boldsymbol{w}_0.\n",
@@ -5873,28 +2822,14 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "336873c8",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "d1270aab",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"$$\n",
"\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0.\n",
@@ -5903,14 +2838,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "11da32f3",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -5928,24 +2856,13 @@
"the Singular Value Decomposition theorem. For categorical data, see\n",
"chapter 12.4 and discussion therein.\n",
"\n",
- "For more details, see for example [Vidal, Ma and Sastry, chapter 2](https://www.springer.com/gp/book/9780387878102)."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "a733436e",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "For more details, see for example [Vidal, Ma and Sastry, chapter 2](https://www.springer.com/gp/book/9780387878102).\n",
+ "\n",
"## 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",
@@ -5956,15 +2873,9 @@
{
"cell_type": "code",
"execution_count": 41,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "aa097235",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"import numpy as np\n",
@@ -5995,14 +2906,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "1c68d5eb",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -6016,15 +2920,9 @@
{
"cell_type": "code",
"execution_count": 42,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "3de742c4",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"W2 = V.T[:, :2]\n",
@@ -6033,14 +2931,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "3f205661",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## PCA and scikit-learn\n",
"\n",
@@ -6052,15 +2943,9 @@
{
"cell_type": "code",
"execution_count": 43,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "67475c8a",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"#thereafter we do a PCA with Scikit-learn\n",
@@ -6072,14 +2957,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "60d37815",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -6089,15 +2967,9 @@
{
"cell_type": "code",
"execution_count": 44,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "7be09d48",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"pca.components_.T[:, 0]"
@@ -6105,31 +2977,12 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "41c3c78b",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"Another very useful piece of information is the explained variance ratio of each principal component,\n",
"available via the $explained\\_variance\\_ratio$ variable. It indicates the proportion of the dataset’s\n",
- "variance that lies along the axis of each principal component."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "3ef0d7f4",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "variance that lies along the axis of each principal component. \n",
+ "\n",
"## 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."
@@ -6138,15 +2991,9 @@
{
"cell_type": "code",
"execution_count": 45,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "d51362ba",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
@@ -6181,17 +3028,11 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "3e380841",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -6203,15 +3044,9 @@
{
"cell_type": "code",
"execution_count": 46,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "ca2f6d3d",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"pca = PCA()\n",
@@ -6222,14 +3057,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "3da7b4f7",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -6239,15 +3067,9 @@
{
"cell_type": "code",
"execution_count": 47,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "378b56fc",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"pca = PCA(n_components=0.95)\n",
@@ -6256,14 +3078,7 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "1b31ecd4",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"source": [
"## Incremental PCA\n",
"\n",
@@ -6271,39 +3086,17 @@
"memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have\n",
"been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch\n",
"at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new\n",
- "instances arrive)."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "ad8ef5d2",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "instances arrive).\n",
+ "\n",
+ "\n",
"### Randomized PCA\n",
"\n",
"Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic\n",
"algorithm that quickly finds an approximation of the first d principal components. Its computational\n",
"complexity is $O(m \\times d^2)+O(d^3)$, instead of $O(m \\times n^2) + O(n^3)$, so it is dramatically faster than the\n",
- "previous algorithms when $d$ is much smaller than $n$."
- ]
- },
- {
- "cell_type": "markdown",
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "955d7d0a",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
- "source": [
+ "previous algorithms when $d$ is much smaller than $n$.\n",
+ "\n",
+ "\n",
"### Kernel PCA\n",
"\n",
"The kernel trick is a mathematical technique that implicitly maps instances into a\n",
@@ -6320,15 +3113,9 @@
{
"cell_type": "code",
"execution_count": 48,
-<<<<<<< HEAD
- "metadata": {},
-=======
- "id": "faa1ce89",
"metadata": {
- "collapsed": false,
- "editable": true
+ "collapsed": false
},
->>>>>>> origin/master
"outputs": [],
"source": [
"from sklearn.decomposition import KernelPCA\n",
@@ -6338,17 +3125,11 @@
},
{
"cell_type": "markdown",
-<<<<<<< HEAD
"metadata": {},
-=======
- "id": "35bf0446",
- "metadata": {
- "editable": true
- },
->>>>>>> origin/master
"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",
@@ -6362,25 +3143,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.3"
- }
- },
+ "metadata": {},
"nbformat": 4,
- "nbformat_minor": 5
+ "nbformat_minor": 4
}
diff --git a/doc/src/week43/ipynb-week43-src.tar.gz b/doc/src/week43/ipynb-week43-src.tar.gz
deleted file mode 100644
index 8d094f6c9..000000000
Binary files a/doc/src/week43/ipynb-week43-src.tar.gz and /dev/null differ
diff --git a/doc/src/week43/make.sh b/doc/src/week43/make.sh
index a4c3f133a..4722a0918 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/reveal.js/.gitignore b/doc/src/week43/reveal.js/.gitignore
deleted file mode 100644
index a5df3133d..000000000
--- a/doc/src/week43/reveal.js/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-.DS_Store
-.svn
-log/*.log
-tmp/**
-node_modules/
-.sass-cache
-css/reveal.min.css
-js/reveal.min.js
diff --git a/doc/src/week43/reveal.js/.travis.yml b/doc/src/week43/reveal.js/.travis.yml
deleted file mode 100644
index 165d9ae9f..000000000
--- a/doc/src/week43/reveal.js/.travis.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-language: node_js
-node_js:
- - 0.10
-before_script:
- - npm install -g grunt-cli
\ No newline at end of file
diff --git a/doc/src/week43/reveal.js/CONTRIBUTING.md b/doc/src/week43/reveal.js/CONTRIBUTING.md
deleted file mode 100644
index c2091e88f..000000000
--- a/doc/src/week43/reveal.js/CONTRIBUTING.md
+++ /dev/null
@@ -1,23 +0,0 @@
-## Contributing
-
-Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**.
-
-
-### Personal Support
-If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js).
-
-
-### Bug Reports
-When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested.
-
-
-### Pull Requests
-- Should follow the coding style of the file you work in, most importantly:
- - Tabs to indent
- - Single-quoted strings
-- Should be made towards the **dev branch**
-- Should be submitted from a feature/topic branch (not your master)
-
-
-### Plugins
-Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines
diff --git a/doc/src/week43/reveal.js/Gruntfile.js b/doc/src/week43/reveal.js/Gruntfile.js
deleted file mode 100644
index b257e8f32..000000000
--- a/doc/src/week43/reveal.js/Gruntfile.js
+++ /dev/null
@@ -1,140 +0,0 @@
-/* global module:false */
-module.exports = function(grunt) {
- var port = grunt.option('port') || 8000;
- // Project configuration
- grunt.initConfig({
- pkg: grunt.file.readJSON('package.json'),
- meta: {
- banner:
- '/*!\n' +
- ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
- ' * http://lab.hakim.se/reveal-js\n' +
- ' * MIT licensed\n' +
- ' *\n' +
- ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' +
- ' */'
- },
-
- qunit: {
- files: [ 'test/*.html' ]
- },
-
- uglify: {
- options: {
- banner: '<%= meta.banner %>\n'
- },
- build: {
- src: 'js/reveal.js',
- dest: 'js/reveal.min.js'
- }
- },
-
- cssmin: {
- compress: {
- files: {
- 'css/reveal.min.css': [ 'css/reveal.css' ]
- }
- }
- },
-
- sass: {
- main: {
- files: {
- 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss',
- 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss',
- 'css/theme/cbc.css': 'css/theme/source/cbc.scss',
- 'css/theme/default.css': 'css/theme/source/default.scss',
- 'css/theme/beige.css': 'css/theme/source/beige.scss',
- 'css/theme/night.css': 'css/theme/source/night.scss',
- 'css/theme/serif.css': 'css/theme/source/serif.scss',
- 'css/theme/simple.css': 'css/theme/source/simple.scss',
- 'css/theme/sky.css': 'css/theme/source/sky.scss',
- 'css/theme/moon.css': 'css/theme/source/moon.scss',
- 'css/theme/solarized.css': 'css/theme/source/solarized.scss',
- 'css/theme/blood.css': 'css/theme/source/blood.scss'
- }
- }
- },
-
- jshint: {
- options: {
- curly: false,
- eqeqeq: true,
- immed: true,
- latedef: true,
- newcap: true,
- noarg: true,
- sub: true,
- undef: true,
- eqnull: true,
- browser: true,
- expr: true,
- globals: {
- head: false,
- module: false,
- console: false,
- unescape: false
- }
- },
- files: [ 'Gruntfile.js', 'js/reveal.js' ]
- },
-
- connect: {
- server: {
- options: {
- port: port,
- base: '.'
- }
- }
- },
-
- zip: {
- 'reveal-js-presentation.zip': [
- 'index.html',
- 'css/**',
- 'js/**',
- 'lib/**',
- 'images/**',
- 'plugin/**'
- ]
- },
-
- watch: {
- main: {
- files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ],
- tasks: 'default'
- },
- theme: {
- files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ],
- tasks: 'themes'
- }
- }
-
- });
-
- // Dependencies
- grunt.loadNpmTasks( 'grunt-contrib-qunit' );
- grunt.loadNpmTasks( 'grunt-contrib-jshint' );
- grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
- grunt.loadNpmTasks( 'grunt-contrib-uglify' );
- grunt.loadNpmTasks( 'grunt-contrib-watch' );
- grunt.loadNpmTasks( 'grunt-contrib-sass' );
- grunt.loadNpmTasks( 'grunt-contrib-connect' );
- grunt.loadNpmTasks( 'grunt-zip' );
-
- // Default task
- grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] );
-
- // Theme task
- grunt.registerTask( 'themes', [ 'sass' ] );
-
- // Package presentation to archive
- grunt.registerTask( 'package', [ 'default', 'zip' ] );
-
- // Serve presentation locally
- grunt.registerTask( 'serve', [ 'connect', 'watch' ] );
-
- // Run tests
- grunt.registerTask( 'test', [ 'jshint', 'qunit' ] );
-
-};
diff --git a/doc/src/week43/reveal.js/LICENSE b/doc/src/week43/reveal.js/LICENSE
deleted file mode 100644
index 09623076f..000000000
--- a/doc/src/week43/reveal.js/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (C) 2015 Hakim El Hattab, http://hakim.se
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
\ No newline at end of file
diff --git a/doc/src/week43/reveal.js/README.md b/doc/src/week43/reveal.js/README.md
deleted file mode 100644
index 573b19597..000000000
--- a/doc/src/week43/reveal.js/README.md
+++ /dev/null
@@ -1,1052 +0,0 @@
-# reveal.js [](https://travis-ci.org/hakimel/reveal.js)
-
-A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/).
-
-reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere.
-
-
-#### More reading:
-- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer.
-- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history.
-- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own!
-- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks.
-- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js.
-
-## Online Editor
-
-Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com).
-
-
-## Instructions
-
-### Markup
-
-Markup hierarchy needs to be ``
`` where the ```` represents one slide and can be repeated indefinitely. If you place multiple ````'s inside of another ```` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example:
-
-```html
-
-```
-
-### Markdown
-
-It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your `````` elements and wrap the contents in a ```
-
-```
-
-#### External Markdown
-
-You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file.
-
-When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup).
-
-```html
-
-
-```
-
-#### Element Attributes
-
-Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things.
-
-```html
-
-
-
-```
-
-#### Slide Attributes
-
-Special syntax (in html comment) is available for adding attributes to the slide `` elements generated by your Markdown.
-
-```html
-
-
-
-```
-
-
-### Configuration
-
-At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below.
-
-```javascript
-Reveal.initialize({
-
- // Display controls in the bottom right corner
- controls: true,
-
- // Display a presentation progress bar
- progress: true,
-
- // Display the page number of the current slide
- slideNumber: false,
-
- // Push each slide change to the browser history
- history: false,
-
- // Enable keyboard shortcuts for navigation
- keyboard: true,
-
- // Enable the slide overview mode
- overview: true,
-
- // Vertical centering of slides
- center: true,
-
- // Enables touch navigation on devices with touch input
- touch: true,
-
- // Loop the presentation
- loop: false,
-
- // Change the presentation direction to be RTL
- rtl: false,
-
- // Turns fragments on and off globally
- fragments: true,
-
- // Flags if the presentation is running in an embedded mode,
- // i.e. contained within a limited portion of the screen
- embedded: false,
-
- // Flags if we should show a help overlay when the questionmark
- // key is pressed
- help: true,
-
- // Number of milliseconds between automatically proceeding to the
- // next slide, disabled when set to 0, this value can be overwritten
- // by using a data-autoslide attribute on your slides
- autoSlide: 0,
-
- // Stop auto-sliding after user input
- autoSlideStoppable: true,
-
- // Enable slide navigation via mouse wheel
- mouseWheel: false,
-
- // Hides the address bar on mobile devices
- hideAddressBar: true,
-
- // Opens links in an iframe preview overlay
- previewLinks: false,
-
- // Transition style
- transition: 'default', // none/fade/slide/convex/concave/zoom
-
- // Transition speed
- transitionSpeed: 'default', // default/fast/slow
-
- // Transition style for full page slide backgrounds
- backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom
-
- // Number of slides away from the current that are visible
- viewDistance: 3,
-
- // Parallax background image
- parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'"
-
- // Parallax background size
- parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px"
-
- // Amount to move parallax background (horizontal and vertical) on slide change
- // Number, e.g. 100
- parallaxBackgroundHorizontal: '',
- parallaxBackgroundVertical: ''
-
-});
-```
-
-
-The configuration can be updated after initialization using the ```configure``` method:
-
-```javascript
-// Turn autoSlide off
-Reveal.configure({ autoSlide: 0 });
-
-// Start auto-sliding every 5s
-Reveal.configure({ autoSlide: 5000 });
-```
-
-
-### Dependencies
-
-Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example:
-
-```javascript
-Reveal.initialize({
- dependencies: [
- // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/
- { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
-
- // Interpret Markdown in elements
- { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
- { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
-
- // Syntax highlight for elements
- { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
-
- // Zoom in and out with Alt+click
- { src: 'plugin/zoom-js/zoom.js', async: true },
-
- // Speaker notes
- { src: 'plugin/notes/notes.js', async: true },
-
- // Remote control your reveal.js presentation using a touch device
- { src: 'plugin/remotes/remotes.js', async: true },
-
- // MathJax
- { src: 'plugin/math/math.js', async: true }
- ]
-});
-```
-
-You can add your own extensions using the same syntax. The following properties are available for each dependency object:
-- **src**: Path to the script to load
-- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false
-- **callback**: [optional] Function to execute when the script has loaded
-- **condition**: [optional] Function which must return true for the script to be loaded
-
-
-### Ready Event
-
-A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`.
-
-```javascript
-Reveal.addEventListener( 'ready', function( event ) {
- // event.currentSlide, event.indexh, event.indexv
-} );
-```
-
-
-### Presentation Size
-
-All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport.
-
-See below for a list of configuration options related to sizing, including default values:
-
-```javascript
-Reveal.initialize({
-
- ...
-
- // The "normal" size of the presentation, aspect ratio will be preserved
- // when the presentation is scaled to fit different resolutions. Can be
- // specified using percentage units.
- width: 960,
- height: 700,
-
- // Factor of the display size that should remain empty around the content
- margin: 0.1,
-
- // Bounds for smallest/largest possible scale to apply to content
- minScale: 0.2,
- maxScale: 1.5
-
-});
-```
-
-
-### Auto-sliding
-
-Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides:
-
-```javascript
-// Slide every five seconds
-Reveal.configure({
- autoSlide: 5000
-});
-```
-When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config.
-
-You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute:
-
-```html
-
-
After 2 seconds the first fragment will be shown.
-
After 10 seconds the next fragment will be shown.
-
Now, the fragment is displayed for 2 seconds before the next slide is shown.
-
-```
-
-Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired.
-
-
-### Keyboard Bindings
-
-If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option:
-
-```javascript
-Reveal.configure({
- keyboard: {
- 13: 'next', // go to the next slide when the ENTER key is pressed
- 27: function() {}, // do something custom when ESC is pressed
- 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding)
- }
-});
-```
-
-### Lazy Loading
-
-When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option.
-
-To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible.
-
-```html
-
-
-
-
-
-```
-
-
-### API
-
-The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state:
-
-```javascript
-// Navigation
-Reveal.slide( indexh, indexv, indexf );
-Reveal.left();
-Reveal.right();
-Reveal.up();
-Reveal.down();
-Reveal.prev();
-Reveal.next();
-Reveal.prevFragment();
-Reveal.nextFragment();
-
-// Toggle presentation states, optionally pass true/false to force on/off
-Reveal.toggleOverview();
-Reveal.togglePause();
-Reveal.toggleAutoSlide();
-
-// Change a config value at runtime
-Reveal.configure({ controls: true });
-
-// Returns the present configuration options
-Reveal.getConfig();
-
-// Fetch the current scale of the presentation
-Reveal.getScale();
-
-// Retrieves the previous and current slide elements
-Reveal.getPreviousSlide();
-Reveal.getCurrentSlide();
-
-Reveal.getIndices(); // { h: 0, v: 0 } }
-Reveal.getProgress(); // 0-1
-Reveal.getTotalSlides();
-
-// State checks
-Reveal.isFirstSlide();
-Reveal.isLastSlide();
-Reveal.isOverview();
-Reveal.isPaused();
-Reveal.isAutoSliding();
-```
-
-### Slide Changed Event
-
-A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes.
-
-Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback.
-
-```javascript
-Reveal.addEventListener( 'slidechanged', function( event ) {
- // event.previousSlide, event.currentSlide, event.indexh, event.indexv
-} );
-```
-
-### Presentation State
-
-The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire.
-
-```javascript
-Reveal.slide( 1 );
-// we're on slide 1
-
-var state = Reveal.getState();
-
-Reveal.slide( 3 );
-// we're on slide 3
-
-Reveal.setState( state );
-// we're back on slide 1
-```
-
-### Slide States
-
-If you set ``data-state="somestate"`` on a slide ````, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide.
-
-Furthermore you can also listen to these changes in state via JavaScript:
-
-```javascript
-Reveal.addEventListener( 'somestate', function() {
- // TODO: Sprinkle magic
-}, false );
-```
-
-### Slide Backgrounds
-
-Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your `````` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples.
-
-```html
-
-
All CSS color formats are supported, like rgba() or hsl().
-
-
-
This slide will have a full-size background image.
-
-
-
This background image will be sized to 100px and repeated.
-
-
-
Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.
-
-
-
Embeds a web page as a background. Note that the page won't be interactive.
-
-```
-
-Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition.
-
-
-### Parallax Background
-
-If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional).
-
-```javascript
-Reveal.initialize({
-
- // Parallax background image
- parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg"
-
- // Parallax background size
- parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto)
-
- // Amount of pixels to move the parallax background per slide step,
- // a value of 0 disables movement along the given axis
- // These are optional, if they aren't specified they'll be calculated automatically
- parallaxBackgroundHorizontal: 200,
- parallaxBackgroundVertical: 50
-
-});
-```
-
-Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px).
-
-
-
-### Slide Transitions
-The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute:
-
-```html
-
-
This slide will override the presentation transition and zoom!
-
-
-
-
Choose from three transition speeds: default, fast or slow!
Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
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)
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.
-
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
-importnumpyasnp
-# For machine learning (backend for keras)
-importtensorflowastf
-# User-friendly machine learning library
-# Front end for TensorFlow
-importtensorflow.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.
-fromtensorflow.kerasimport datasets, layers, models
-fromtensorflow.keras.layersimport Input
-fromtensorflow.kerasimport regularizers
-fromtensorflow.keras.modelsimport Model, Sequential
-fromtensorflow.keras.layersimport Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-fromtimeitimport default_timer as timer
-# For plotting
-importmatplotlib.pyplotasplt
-
-
-# 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
-defformat_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 inrange(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.
-
-defrnn(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
-
-
-
-
-
-
-
-
-
deftest_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 inrange (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
-assertlen(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.
-
-
-
-
-
-
-
-
-
-
defrnn_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
-assertlen(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)
-
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.
-
-
-
-
-
-
-
-
-
-
deflstm_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
-
-defdnn2_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
-assertlen(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
-assertlen(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
-
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
-
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
-
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.
-
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
-
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
-
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).
-
-
-
-
-
-
-
-
-
-
defgenerator_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.
-
-
-
-
-
-
-
-
-
-
defdiscriminator_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.
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
-
-
-
-
-
-
-
-
-
-
defgenerator_loss(fake_output):
- loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
- return loss
-
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.
-
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.
-
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)
-
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.
-
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
-
-
-
-
-
-
-
-
-
-
defgenerate_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
-
-defgenerate_images(latent_points):
- # notice we set training to false because we are making inferences
- generated_images = restored_generator.predict(latent_points)
-
- return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
defplot_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 inrange(int(np.sqrt(number))):
- for j inrange(int(np.sqrt(number))):
- axs[i, j].imshow(generated_images[i*j], cmap='Greys')
- axs[i, j].axis('off')
-
- plt.show()
-
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.
-
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.
-
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.
-
-
-
-
-
-
-
-
-
-
definterpolation(point_1, point_2, n_steps=10):
- ratios = np.linspace(0, 1, num=n_steps)
- vectors = []
- for i, ratio inenumerate(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.
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.
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
-
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
-
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
-
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
-
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
-
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 \)
-
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} \)
-
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.
-
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).
-
-
-
-
-
-
-
-
-
-
importnumpyasnp
-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
We expand this model to the Franke function discussed above.
-
-
-
-
-
-
-
-
-
# Common imports
-importnumpyasnp
-importpandasaspd
-
-
-defFrankeFunction(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
-
-
-defcreate_X(x, y, n ):
- iflen(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 inrange(1,n+1):
- q =int((i)*(i+1)/2)
- for k inrange(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
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
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}] \).
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.
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):
-
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 \).
-
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
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.
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 inrange(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
-fromsklearn.decompositionimport 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
-
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
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.
-
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
-
-
-
-
-
-
-
-
-
importnumpyasnp
-importpandasaspd
-fromIPython.displayimport 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
-fromsklearn.decompositionimport 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.
-
-
-
-
-
-
-
-
-
importmatplotlib.pyplotasplt
-importnumpyasnp
-fromsklearn.model_selectionimport train_test_split
-fromsklearn.datasetsimport load_breast_cancer
-fromsklearn.linear_modelimport 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
-fromsklearn.preprocessingimport 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
-fromsklearn.decompositionimport 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:
-
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:
-
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
-
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.
Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
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)
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.
-
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
-importnumpyasnp
-# For machine learning (backend for keras)
-importtensorflowastf
-# User-friendly machine learning library
-# Front end for TensorFlow
-importtensorflow.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.
-fromtensorflow.kerasimport datasets, layers, models
-fromtensorflow.keras.layersimport Input
-fromtensorflow.kerasimport regularizers
-fromtensorflow.keras.modelsimport Model, Sequential
-fromtensorflow.keras.layersimport Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-fromtimeitimport default_timer as timer
-# For plotting
-importmatplotlib.pyplotasplt
-
-
-# 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
-defformat_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 inrange(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.
-
-defrnn(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
-
-
-
-
-
-
-
-
-
deftest_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 inrange (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
-assertlen(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.
-
-
-
-
-
-
-
-
-
-
defrnn_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
-assertlen(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)
-
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.
-
-
-
-
-
-
-
-
-
-
deflstm_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
-
-defdnn2_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
-assertlen(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
-assertlen(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
-
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
-
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
-
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.
-
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
-
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
-
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).
-
-
-
-
-
-
-
-
-
-
defgenerator_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.
-
-
-
-
-
-
-
-
-
-
defdiscriminator_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.
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
-
-
-
-
-
-
-
-
-
-
defgenerator_loss(fake_output):
- loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
- return loss
-
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.
-
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.
-
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)
-
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.
-
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
-
-
-
-
-
-
-
-
-
-
defgenerate_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
-
-defgenerate_images(latent_points):
- # notice we set training to false because we are making inferences
- generated_images = restored_generator.predict(latent_points)
-
- return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
defplot_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 inrange(int(np.sqrt(number))):
- for j inrange(int(np.sqrt(number))):
- axs[i, j].imshow(generated_images[i*j], cmap='Greys')
- axs[i, j].axis('off')
-
- plt.show()
-
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.
-
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.
-
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.
-
-
-
-
-
-
-
-
-
-
definterpolation(point_1, point_2, n_steps=10):
- ratios = np.linspace(0, 1, num=n_steps)
- vectors = []
- for i, ratio inenumerate(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.
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.
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
-
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
-
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
-
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
-
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
-
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 \)
-
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} \)
-
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.
-
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).
-
-
-
-
-
-
-
-
-
-
importnumpyasnp
-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
We expand this model to the Franke function discussed above.
-
-
-
-
-
-
-
-
-
# Common imports
-importnumpyasnp
-importpandasaspd
-
-
-defFrankeFunction(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
-
-
-defcreate_X(x, y, n ):
- iflen(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 inrange(1,n+1):
- q = int((i)*(i+1)/2)
- for k inrange(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
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}] \).
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.
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):
-
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 \).
-
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
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.
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 inrange(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
-fromsklearn.decompositionimport 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
-
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
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.
-
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
-
-
-
-
-
-
-
-
-
importnumpyasnp
-importpandasaspd
-fromIPython.displayimport 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
-fromsklearn.decompositionimport 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.
-
-
-
-
-
-
-
-
-
importmatplotlib.pyplotasplt
-importnumpyasnp
-fromsklearn.model_selectionimport train_test_split
-fromsklearn.datasetsimport load_breast_cancer
-fromsklearn.linear_modelimport 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
-fromsklearn.preprocessingimport 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
-fromsklearn.decompositionimport 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:
-
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:
-
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
-
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.
Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
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)
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.
-
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
-importnumpyasnp
-# For machine learning (backend for keras)
-importtensorflowastf
-# User-friendly machine learning library
-# Front end for TensorFlow
-importtensorflow.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.
-fromtensorflow.kerasimport datasets, layers, models
-fromtensorflow.keras.layersimport Input
-fromtensorflow.kerasimport regularizers
-fromtensorflow.keras.modelsimport Model, Sequential
-fromtensorflow.keras.layersimport Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-fromtimeitimport default_timer as timer
-# For plotting
-importmatplotlib.pyplotasplt
-
-
-# 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
-defformat_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 inrange(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.
-
-defrnn(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
-
-
-
-
-
-
-
-
-
deftest_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 inrange (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
-assertlen(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.
-
-
-
-
-
-
-
-
-
-
defrnn_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
-assertlen(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)
-
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.
-
-
-
-
-
-
-
-
-
-
deflstm_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
-
-defdnn2_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
-assertlen(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
-assertlen(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
-
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
-
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
-
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.
-
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
-
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
-
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).
-
-
-
-
-
-
-
-
-
-
defgenerator_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.
-
-
-
-
-
-
-
-
-
-
defdiscriminator_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.
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
-
-
-
-
-
-
-
-
-
-
defgenerator_loss(fake_output):
- loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
- return loss
-
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.
-
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.
-
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)
-
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.
-
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
-
-
-
-
-
-
-
-
-
-
defgenerate_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
-
-defgenerate_images(latent_points):
- # notice we set training to false because we are making inferences
- generated_images = restored_generator.predict(latent_points)
-
- return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
defplot_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 inrange(int(np.sqrt(number))):
- for j inrange(int(np.sqrt(number))):
- axs[i, j].imshow(generated_images[i*j], cmap='Greys')
- axs[i, j].axis('off')
-
- plt.show()
-
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.
-
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.
-
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.
-
-
-
-
-
-
-
-
-
-
definterpolation(point_1, point_2, n_steps=10):
- ratios = np.linspace(0, 1, num=n_steps)
- vectors = []
- for i, ratio inenumerate(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.
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.
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
-
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
-
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
-
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
-
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
-
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 \)
-
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} \)
-
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.
-
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).
-
-
-
-
-
-
-
-
-
-
importnumpyasnp
-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
We expand this model to the Franke function discussed above.
-
-
-
-
-
-
-
-
-
# Common imports
-importnumpyasnp
-importpandasaspd
-
-
-defFrankeFunction(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
-
-
-defcreate_X(x, y, n ):
- iflen(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 inrange(1,n+1):
- q = int((i)*(i+1)/2)
- for k inrange(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
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
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}] \).
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.
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):
-
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 \).
-
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
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.
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 inrange(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
-fromsklearn.decompositionimport 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
-
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
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.
-
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
-
-
-
-
-
-
-
-
-
importnumpyasnp
-importpandasaspd
-fromIPython.displayimport 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
-fromsklearn.decompositionimport 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.
-
-
-
-
-
-
-
-
-
importmatplotlib.pyplotasplt
-importnumpyasnp
-fromsklearn.model_selectionimport train_test_split
-fromsklearn.datasetsimport load_breast_cancer
-fromsklearn.linear_modelimport 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
-fromsklearn.preprocessingimport 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
-fromsklearn.decompositionimport 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:
-
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:
-
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
-
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.
Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis
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)
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.
-
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
-importnumpyasnp
-# For machine learning (backend for keras)
-importtensorflowastf
-# User-friendly machine learning library
-# Front end for TensorFlow
-importtensorflow.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.
-fromtensorflow.kerasimport datasets, layers, models
-fromtensorflow.keras.layersimport Input
-fromtensorflow.kerasimport regularizers
-fromtensorflow.keras.modelsimport Model, Sequential
-fromtensorflow.keras.layersimport Dense, SimpleRNN, LSTM, GRU
-# For timing the code
-fromtimeitimport default_timer as timer
-# For plotting
-importmatplotlib.pyplotasplt
-
-
-# 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
-defformat_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 inrange(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.
-
-defrnn(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
-
-
-
-
-
-
-
-
-
deftest_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 inrange (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
-assertlen(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.
-
-
-
-
-
-
-
-
-
-
defrnn_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
-assertlen(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)
-
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.
-
-
-
-
-
-
-
-
-
-
deflstm_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
-
-defdnn2_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
-assertlen(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
-assertlen(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
-
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
-
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
-
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.
-
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
-
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
-
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).
-
-
-
-
-
-
-
-
-
-
defgenerator_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.
-
-
-
-
-
-
-
-
-
-
defdiscriminator_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.
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
-
-
-
-
-
-
-
-
-
-
defgenerator_loss(fake_output):
- loss = cross_entropy(tf.ones_like(fake_output), fake_output)
-
- return loss
-
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.
-
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.
-
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)
-
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.
-
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
-
-
-
-
-
-
-
-
-
-
defgenerate_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
-
-defgenerate_images(latent_points):
- # notice we set training to false because we are making inferences
- generated_images = restored_generator.predict(latent_points)
-
- return generated_images
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
defplot_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 inrange(int(np.sqrt(number))):
- for j inrange(int(np.sqrt(number))):
- axs[i, j].imshow(generated_images[i*j], cmap='Greys')
- axs[i, j].axis('off')
-
- plt.show()
-
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.
-
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.
-
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.
-
-
-
-
-
-
-
-
-
-
definterpolation(point_1, point_2, n_steps=10):
- ratios = np.linspace(0, 1, num=n_steps)
- vectors = []
- for i, ratio inenumerate(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.
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.
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
-
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
-
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
-
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
-
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
-
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 \)
-
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} \)
-
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.
-
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).
-
-
-
-
-
-
-
-
-
-
importnumpyasnp
-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
We expand this model to the Franke function discussed above.
-
-
-
-
-
-
-
-
-
# Common imports
-importnumpyasnp
-importpandasaspd
-
-
-defFrankeFunction(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
-
-
-defcreate_X(x, y, n ):
- iflen(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 inrange(1,n+1):
- q =int((i)*(i+1)/2)
- for k inrange(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
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
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}] \).
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.
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):
-
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 \).
-
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
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.
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 inrange(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
-fromsklearn.decompositionimport 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
-
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
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.
-
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
-
-
-
-
-
-
-
-
-
importnumpyasnp
-importpandasaspd
-fromIPython.displayimport 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
-fromsklearn.decompositionimport 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.
-
-
-
-
-
-
-
-
-
importmatplotlib.pyplotasplt
-importnumpyasnp
-fromsklearn.model_selectionimport train_test_split
-fromsklearn.datasetsimport load_breast_cancer
-fromsklearn.linear_modelimport 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
-fromsklearn.preprocessingimport 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
-fromsklearn.decompositionimport 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:
-
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:
-
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
-
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.ipynb b/doc/src/week43/week43.ipynb
deleted file mode 100644
index fc834c8f1..000000000
--- a/doc/src/week43/week43.ipynb
+++ /dev/null
@@ -1,3818 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "id": "fc0e9b18",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- ""
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2c6b6382",
- "metadata": {
- "editable": true
- },
- "source": [
- "# Week 43: Deep Learning: Recurrent Neural Networks and other Deep Learning Methods. Principal Component analysis\n",
- "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
- "\n",
- "Date: **Oct 29, 2021**\n",
- "\n",
- "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2624a425",
- "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",
- "* Friday: Recurrent Neural Networks and other Deep Learning methods such as Generalized Adversarial Neural Networks. Start discussing Principal component analysis\n",
- "\n",
- "**Excellent lectures on CNNs and RNNs.**\n",
- "\n",
- "* [Video on Convolutional Neural Networks from MIT](https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini)\n",
- "\n",
- "* [Video on Recurrent Neural Networks from MIT](https://www.youtube.com/watch?v=SEnXr6v2ifU&ab_channel=AlexanderAmini)\n",
- "\n",
- "* [Video on Deep Learning](https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi)\n",
- "\n",
- "**More resources.**\n",
- "\n",
- "* [IN5400 at UiO Lecture](https://www.uio.no/studier/emner/matnat/ifi/IN5400/v20/material/week10/in5400_2020_week10_recurrent_neural_network.pdf)\n",
- "\n",
- "* [CS231 at Stanford Lecture](https://www.youtube.com/watch?v=6niqTuYFZLQ&list=PLzUTmXVwsnXod6WNdg57Yc3zFx_f-RYsq&index=10&ab_channel=StanfordUniversitySchoolofEngineering)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d0b80f33",
- "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."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "c6e4412c",
- "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."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "266676bd",
- "metadata": {
- "editable": true
- },
- "source": [
- "## CNNs in brief\n",
- "\n",
- "In summary:\n",
- "\n",
- "* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n",
- "\n",
- "* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n",
- "\n",
- "* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n",
- "\n",
- "* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)\n",
- "\n",
- "* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n",
- "\n",
- "For more material on convolutional networks, we strongly recommend\n",
- "the course\n",
- "[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
- "and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n",
- "\n",
- "However, both standard feed forwards networks and CNNs perform well on data with unknown length.\n",
- "\n",
- "This is where recurrent nueral networks (RNNs) come to our rescue."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "6d6fc0e4",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Recurrent neural networks: Overarching view\n",
- "\n",
- "Till now our focus has been, including convolutional neural networks\n",
- "as well, on feedforward neural networks. The output or the activations\n",
- "flow only in one direction, from the input layer to the output layer.\n",
- "\n",
- "A recurrent neural network (RNN) looks very much like a feedforward\n",
- "neural network, except that it also has connections pointing\n",
- "backward. \n",
- "\n",
- "RNNs are used to analyze time series data such as stock prices, and\n",
- "tell you when to buy or sell. In autonomous driving systems, they can\n",
- "anticipate car trajectories and help avoid accidents. More generally,\n",
- "they can work on sequences of arbitrary lengths, rather than on\n",
- "fixed-sized inputs like all the nets we have discussed so far. For\n",
- "example, they can take sentences, documents, or audio samples as\n",
- "input, making them extremely useful for natural language processing\n",
- "systems such as automatic translation and speech-to-text."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "bf281e51",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Set up of an RNN\n",
- "\n",
- "More to text to be added"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "07498ec3",
- "metadata": {
- "editable": true
- },
- "source": [
- "## A simple example"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "id": "7075cff8",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "%matplotlib inline\n",
- "\n",
- "# Start importing packages\n",
- "import pandas as pd\n",
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "import tensorflow as tf\n",
- "from tensorflow.keras import datasets, layers, models\n",
- "from tensorflow.keras.layers import Input\n",
- "from tensorflow.keras.models import Model, Sequential \n",
- "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
- "from tensorflow.keras import optimizers \n",
- "from tensorflow.keras import regularizers \n",
- "from tensorflow.keras.utils import to_categorical \n",
- "\n",
- "\n",
- "\n",
- "# convert into dataset matrix\n",
- "def convertToMatrix(data, step):\n",
- " X, Y =[], []\n",
- " for i in range(len(data)-step):\n",
- " d=i+step \n",
- " X.append(data[i:d,])\n",
- " Y.append(data[d,])\n",
- " return np.array(X), np.array(Y)\n",
- "\n",
- "step = 4\n",
- "N = 1000 \n",
- "Tp = 800 \n",
- "\n",
- "t=np.arange(0,N)\n",
- "x=np.sin(0.02*t)+2*np.random.rand(N)\n",
- "df = pd.DataFrame(x)\n",
- "df.head()\n",
- "\n",
- "plt.plot(df)\n",
- "plt.show()\n",
- "\n",
- "values=df.values\n",
- "train,test = values[0:Tp,:], values[Tp:N,:]\n",
- "\n",
- "# add step elements into train and test\n",
- "test = np.append(test,np.repeat(test[-1,],step))\n",
- "train = np.append(train,np.repeat(train[-1,],step))\n",
- " \n",
- "trainX,trainY =convertToMatrix(train,step)\n",
- "testX,testY =convertToMatrix(test,step)\n",
- "trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n",
- "testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n",
- "\n",
- "model = Sequential()\n",
- "model.add(SimpleRNN(units=32, input_shape=(1,step), activation=\"relu\"))\n",
- "model.add(Dense(8, activation=\"relu\")) \n",
- "model.add(Dense(1))\n",
- "model.compile(loss='mean_squared_error', optimizer='rmsprop')\n",
- "model.summary()\n",
- "\n",
- "model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)\n",
- "trainPredict = model.predict(trainX)\n",
- "testPredict= model.predict(testX)\n",
- "predicted=np.concatenate((trainPredict,testPredict),axis=0)\n",
- "\n",
- "trainScore = model.evaluate(trainX, trainY, verbose=0)\n",
- "print(trainScore)\n",
- "\n",
- "index = df.index.values\n",
- "plt.plot(index,df)\n",
- "plt.plot(index,predicted)\n",
- "plt.axvline(df.index[Tp], c=\"r\")\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ab3a2fa1",
- "metadata": {
- "editable": true
- },
- "source": [
- "## An extrapolation example\n",
- "\n",
- "The following code provides an example of how recurrent neural\n",
- "networks can be used to extrapolate to unknown values of physics data\n",
- "sets. Specifically, the data sets used in this program come from\n",
- "a quantum mechanical many-body calculation of energies as functions of the number of particles."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "id": "d8b4e1df",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "\n",
- "# For matrices and calculations\n",
- "import numpy as np\n",
- "# For machine learning (backend for keras)\n",
- "import tensorflow as tf\n",
- "# User-friendly machine learning library\n",
- "# Front end for TensorFlow\n",
- "import tensorflow.keras\n",
- "# Different methods from Keras needed to create an RNN\n",
- "# This is not necessary but it shortened function calls \n",
- "# that need to be used in the code.\n",
- "from tensorflow.keras import datasets, layers, models\n",
- "from tensorflow.keras.layers import Input\n",
- "from tensorflow.keras import regularizers\n",
- "from tensorflow.keras.models import Model, Sequential\n",
- "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n",
- "# For timing the code\n",
- "from timeit import default_timer as timer\n",
- "# For plotting\n",
- "import matplotlib.pyplot as plt\n",
- "\n",
- "\n",
- "# The data set\n",
- "datatype='VaryDimension'\n",
- "X_tot = np.arange(2, 42, 2)\n",
- "y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,\n",
- "\t-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, \n",
- "\t-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "5a137cf7",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Formatting the Data\n",
- "\n",
- "The way the recurrent neural networks are trained in this program\n",
- "differs from how machine learning algorithms are usually trained.\n",
- "Typically a machine learning algorithm is trained by learning the\n",
- "relationship between the x data and the y data. In this program, the\n",
- "recurrent neural network will be trained to recognize the relationship\n",
- "in a sequence of y values. This is type of data formatting is\n",
- "typically used time series forcasting, but it can also be used in any\n",
- "extrapolation (time series forecasting is just a specific type of\n",
- "extrapolation along the time axis). This method of data formatting\n",
- "does not use the x data and assumes that the y data are evenly spaced.\n",
- "\n",
- "For a standard machine learning algorithm, the training data has the\n",
- "form of (x,y) so the machine learning algorithm learns to assiciate a\n",
- "y value with a given x value. This is useful when the test data has x\n",
- "values within the same range as the training data. However, for this\n",
- "application, the x values of the test data are outside of the x values\n",
- "of the training data and the traditional method of training a machine\n",
- "learning algorithm does not work as well. For this reason, the\n",
- "recurrent neural network is trained on sequences of y values of the\n",
- "form ((y1, y2), y3), so that the network is concerned with learning\n",
- "the pattern of the y data and not the relation between the x and y\n",
- "data. As long as the pattern of y data outside of the training region\n",
- "stays relatively stable compared to what was inside the training\n",
- "region, this method of training can produce accurate extrapolations to\n",
- "y values far removed from the training data set.\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- "\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "id": "e1f5a2fe",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# FORMAT_DATA\n",
- "def format_data(data, length_of_sequence = 2): \n",
- " \"\"\"\n",
- " Inputs:\n",
- " data(a numpy array): the data that will be the inputs to the recurrent neural\n",
- " network\n",
- " length_of_sequence (an int): the number of elements in one iteration of the\n",
- " sequence patter. For a function approximator use length_of_sequence = 2.\n",
- " Returns:\n",
- " rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its\n",
- " dimensions are length of data - length of sequence, length of sequence, \n",
- " dimnsion of data\n",
- " rnn_output (a numpy array): the training data for the neural network\n",
- " Formats data to be used in a recurrent neural network.\n",
- " \"\"\"\n",
- "\n",
- " X, Y = [], []\n",
- " for i in range(len(data)-length_of_sequence):\n",
- " # Get the next length_of_sequence elements\n",
- " a = data[i:i+length_of_sequence]\n",
- " # Get the element that immediately follows that\n",
- " b = data[i+length_of_sequence]\n",
- " # Reshape so that each data point is contained in its own array\n",
- " a = np.reshape (a, (len(a), 1))\n",
- " X.append(a)\n",
- " Y.append(b)\n",
- " rnn_input = np.array(X)\n",
- " rnn_output = np.array(Y)\n",
- "\n",
- " return rnn_input, rnn_output\n",
- "\n",
- "\n",
- "# ## Defining the Recurrent Neural Network Using Keras\n",
- "# \n",
- "# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.\n",
- "\n",
- "def rnn(length_of_sequences, batch_size = None, stateful = False):\n",
- " \"\"\"\n",
- " Inputs:\n",
- " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
- " when the data is formatted\n",
- " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
- " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
- " Returns:\n",
- " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
- " method\n",
- " Builds and compiles a recurrent neural network with one hidden layer and returns the model.\n",
- " \"\"\"\n",
- " # Number of neurons in the input and output layers\n",
- " in_out_neurons = 1\n",
- " # Number of neurons in the hidden layer\n",
- " hidden_neurons = 200\n",
- " # Define the input layer\n",
- " inp = Input(batch_shape=(batch_size, \n",
- " length_of_sequences, \n",
- " in_out_neurons)) \n",
- " # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to \n",
- " # the network immediately after the input layer\n",
- " rnn = SimpleRNN(hidden_neurons, \n",
- " return_sequences=False,\n",
- " stateful = stateful,\n",
- " name=\"RNN\")(inp)\n",
- " # Define the output layer as a dense neural network layer (standard neural network layer)\n",
- " #and add it to the network immediately after the hidden layer.\n",
- " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
- " # Create the machine learning model starting with the input layer and ending with the \n",
- " # output layer\n",
- " model = Model(inputs=[inp],outputs=[dens])\n",
- " # Compile the machine learning model using the mean squared error function as the loss \n",
- " # function and an Adams optimizer.\n",
- " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
- " return model"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "5cd2a0b6",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Predicting New Points With A Trained Recurrent Neural Network"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "id": "a16d8ce2",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def test_rnn (x1, y_test, plot_min, plot_max):\n",
- " \"\"\"\n",
- " Inputs:\n",
- " x1 (a list or numpy array): The complete x component of the data set\n",
- " y_test (a list or numpy array): The complete y component of the data set\n",
- " plot_min (an int or float): the smallest x value used in the training data\n",
- " plot_max (an int or float): the largest x valye used in the training data\n",
- " Returns:\n",
- " None.\n",
- " Uses a trained recurrent neural network model to predict future points in the \n",
- " series. Computes the MSE of the predicted data set from the true data set, saves\n",
- " the predicted data set to a csv file, and plots the predicted and true data sets w\n",
- " while also displaying the data range used for training.\n",
- " \"\"\"\n",
- " # Add the training data as the first dim points in the predicted data array as these\n",
- " # are known values.\n",
- " y_pred = y_test[:dim].tolist()\n",
- " # Generate the first input to the trained recurrent neural network using the last two \n",
- " # points of the training data. Based on how the network was trained this means that it\n",
- " # will predict the first point in the data set after the training data. All of the \n",
- " # brackets are necessary for Tensorflow.\n",
- " next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])\n",
- " # Save the very last point in the training data set. This will be used later.\n",
- " last = [y_test[dim-1]]\n",
- "\n",
- " # Iterate until the complete data set is created.\n",
- " for i in range (dim, len(y_test)):\n",
- " # Predict the next point in the data set using the previous two points.\n",
- " next = model.predict(next_input)\n",
- " # Append just the number of the predicted data set\n",
- " y_pred.append(next[0][0])\n",
- " # Create the input that will be used to predict the next data point in the data set.\n",
- " next_input = np.array([[last, next[0]]], dtype=np.float64)\n",
- " last = next\n",
- "\n",
- " # Print the mean squared error between the known data set and the predicted data set.\n",
- " print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())\n",
- " # Save the predicted data set as a csv file for later use\n",
- " name = datatype + 'Predicted'+str(dim)+'.csv'\n",
- " np.savetxt(name, y_pred, delimiter=',')\n",
- " # Plot the known data set and the predicted data set. The red box represents the region that was used\n",
- " # for the training data.\n",
- " fig, ax = plt.subplots()\n",
- " ax.plot(x1, y_test, label=\"true\", linewidth=3)\n",
- " ax.plot(x1, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
- " ax.legend()\n",
- " # Created a red region to represent the points used in the training data.\n",
- " ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')\n",
- " plt.show()\n",
- "\n",
- "# Check to make sure the data set is complete\n",
- "assert len(X_tot) == len(y_tot)\n",
- "\n",
- "# This is the number of points that will be used in as the training data\n",
- "dim=12\n",
- "\n",
- "# Separate the training data from the whole data set\n",
- "X_train = X_tot[:dim]\n",
- "y_train = y_tot[:dim]\n",
- "\n",
- "\n",
- "# Generate the training data for the RNN, using a sequence of 2\n",
- "rnn_input, rnn_training = format_data(y_train, 2)\n",
- "\n",
- "\n",
- "# Create a recurrent neural network in Keras and produce a summary of the \n",
- "# machine learning model\n",
- "model = rnn(length_of_sequences = rnn_input.shape[1])\n",
- "model.summary()\n",
- "\n",
- "# Start the timer. Want to time training+testing\n",
- "start = timer()\n",
- "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
- "# validation split. Setting verbose to True prints information about each training iteration.\n",
- "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
- " verbose=True,validation_split=0.05)\n",
- "\n",
- "for label in [\"loss\",\"val_loss\"]:\n",
- " plt.plot(hist.history[label],label=label)\n",
- "\n",
- "plt.ylabel(\"loss\")\n",
- "plt.xlabel(\"epoch\")\n",
- "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
- "plt.legend()\n",
- "plt.show()\n",
- "\n",
- "# Use the trained neural network to predict more points of the data set\n",
- "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
- "# Stop the timer and calculate the total time needed.\n",
- "end = timer()\n",
- "print('Time: ', end-start)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "8fca4b7d",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Other Things to Try\n",
- "\n",
- "Changing the size of the recurrent neural network and its parameters\n",
- "can drastically change the results you get from the model. The below\n",
- "code takes the simple recurrent neural network from above and adds a\n",
- "second hidden layer, changes the number of neurons in the hidden\n",
- "layer, and explicitly declares the activation function of the hidden\n",
- "layers to be a sigmoid function. The loss function and optimizer can\n",
- "also be changed but are kept the same as the above network. These\n",
- "parameters can be tuned to provide the optimal result from the\n",
- "network. For some ideas on how to improve the performance of a\n",
- "[recurrent neural network](https://danijar.com/tips-for-training-recurrent-neural-networks)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "id": "87614cd8",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
- " \"\"\"\n",
- " Inputs:\n",
- " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
- " when the data is formatted\n",
- " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
- " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
- " Returns:\n",
- " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
- " method\n",
- " Builds and compiles a recurrent neural network with two hidden layers and returns the model.\n",
- " \"\"\"\n",
- " # Number of neurons in the input and output layers\n",
- " in_out_neurons = 1\n",
- " # Number of neurons in the hidden layer, increased from the first network\n",
- " hidden_neurons = 500\n",
- " # Define the input layer\n",
- " inp = Input(batch_shape=(batch_size, \n",
- " length_of_sequences, \n",
- " in_out_neurons)) \n",
- " # Create two hidden layers instead of one hidden layer. Explicitly set the activation\n",
- " # function to be the sigmoid function (the default value is hyperbolic tangent)\n",
- " rnn1 = SimpleRNN(hidden_neurons, \n",
- " return_sequences=True, # This needs to be True if another hidden layer is to follow\n",
- " stateful = stateful, activation = 'sigmoid',\n",
- " name=\"RNN1\")(inp)\n",
- " rnn2 = SimpleRNN(hidden_neurons, \n",
- " return_sequences=False, activation = 'sigmoid',\n",
- " stateful = stateful,\n",
- " name=\"RNN2\")(rnn1)\n",
- " # Define the output layer as a dense neural network layer (standard neural network layer)\n",
- " #and add it to the network immediately after the hidden layer.\n",
- " dens = Dense(in_out_neurons,name=\"dense\")(rnn2)\n",
- " # Create the machine learning model starting with the input layer and ending with the \n",
- " # output layer\n",
- " model = Model(inputs=[inp],outputs=[dens])\n",
- " # Compile the machine learning model using the mean squared error function as the loss \n",
- " # function and an Adams optimizer.\n",
- " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n",
- " return model\n",
- "\n",
- "# Check to make sure the data set is complete\n",
- "assert len(X_tot) == len(y_tot)\n",
- "\n",
- "# This is the number of points that will be used in as the training data\n",
- "dim=12\n",
- "\n",
- "# Separate the training data from the whole data set\n",
- "X_train = X_tot[:dim]\n",
- "y_train = y_tot[:dim]\n",
- "\n",
- "\n",
- "# Generate the training data for the RNN, using a sequence of 2\n",
- "rnn_input, rnn_training = format_data(y_train, 2)\n",
- "\n",
- "\n",
- "# Create a recurrent neural network in Keras and produce a summary of the \n",
- "# machine learning model\n",
- "model = rnn_2layers(length_of_sequences = 2)\n",
- "model.summary()\n",
- "\n",
- "# Start the timer. Want to time training+testing\n",
- "start = timer()\n",
- "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
- "# validation split. Setting verbose to True prints information about each training iteration.\n",
- "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
- " verbose=True,validation_split=0.05)\n",
- "\n",
- "\n",
- "# This section plots the training loss and the validation loss as a function of training iteration.\n",
- "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
- "# being overtrained.\n",
- "for label in [\"loss\",\"val_loss\"]:\n",
- " plt.plot(hist.history[label],label=label)\n",
- "\n",
- "plt.ylabel(\"loss\")\n",
- "plt.xlabel(\"epoch\")\n",
- "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
- "plt.legend()\n",
- "plt.show()\n",
- "\n",
- "# Use the trained neural network to predict more points of the data set\n",
- "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
- "# Stop the timer and calculate the total time needed.\n",
- "end = timer()\n",
- "print('Time: ', end-start)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "a3f0a13e",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Other Types of Recurrent Neural Networks\n",
- "\n",
- "Besides a simple recurrent neural network layer, there are two other\n",
- "commonly used types of recurrent neural network layers: Long Short\n",
- "Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short\n",
- "introduction to these layers see \n",
- "and .\n",
- "\n",
- "The first network created below is similar to the previous network,\n",
- "but it replaces the SimpleRNN layers with LSTM layers. The second\n",
- "network below has two hidden layers made up of GRUs, which are\n",
- "preceeded by two dense (feeddorward) neural network layers. These\n",
- "dense layers \"preprocess\" the data before it reaches the recurrent\n",
- "layers. This architecture has been shown to improve the performance\n",
- "of recurrent neural networks (see the link above and also\n",
- "."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "id": "5f584ce6",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):\n",
- " \"\"\"\n",
- " Inputs:\n",
- " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
- " when the data is formatted\n",
- " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
- " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
- " Returns:\n",
- " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
- " method\n",
- " Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.\n",
- " \"\"\"\n",
- " # Number of neurons on the input/output layer and the number of neurons in the hidden layer\n",
- " in_out_neurons = 1\n",
- " hidden_neurons = 250\n",
- " # Input Layer\n",
- " inp = Input(batch_shape=(batch_size, \n",
- " length_of_sequences, \n",
- " in_out_neurons)) \n",
- " # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)\n",
- " rnn= LSTM(hidden_neurons, \n",
- " return_sequences=True,\n",
- " stateful = stateful,\n",
- " name=\"RNN\", use_bias=True, activation='tanh')(inp)\n",
- " rnn1 = LSTM(hidden_neurons, \n",
- " return_sequences=False,\n",
- " stateful = stateful,\n",
- " name=\"RNN1\", use_bias=True, activation='tanh')(rnn)\n",
- " # Output layer\n",
- " dens = Dense(in_out_neurons,name=\"dense\")(rnn1)\n",
- " # Define the midel\n",
- " model = Model(inputs=[inp],outputs=[dens])\n",
- " # Compile the model\n",
- " model.compile(loss='mean_squared_error', optimizer='adam') \n",
- " # Return the model\n",
- " return model\n",
- "\n",
- "def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):\n",
- " \"\"\"\n",
- " Inputs:\n",
- " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n",
- " when the data is formatted\n",
- " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n",
- " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n",
- " Returns:\n",
- " model (a Keras model): The recurrent neural network that is built and compiled by this\n",
- " method\n",
- " Builds and compiles a recurrent neural network with four hidden layers (two dense followed by\n",
- " two GRU layers) and returns the model.\n",
- " \"\"\" \n",
- " # Number of neurons on the input/output layers and hidden layers\n",
- " in_out_neurons = 1\n",
- " hidden_neurons = 250\n",
- " # Input layer\n",
- " inp = Input(batch_shape=(batch_size, \n",
- " length_of_sequences, \n",
- " in_out_neurons)) \n",
- " # Hidden Dense (feedforward) layers\n",
- " dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)\n",
- " dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)\n",
- " # Hidden GRU layers\n",
- " rnn1 = GRU(hidden_neurons, \n",
- " return_sequences=True,\n",
- " stateful = stateful,\n",
- " name=\"RNN1\", use_bias=True)(dnn1)\n",
- " rnn = GRU(hidden_neurons, \n",
- " return_sequences=False,\n",
- " stateful = stateful,\n",
- " name=\"RNN\", use_bias=True)(rnn1)\n",
- " # Output layer\n",
- " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n",
- " # Define the model\n",
- " model = Model(inputs=[inp],outputs=[dens])\n",
- " # Compile the mdoel\n",
- " model.compile(loss='mean_squared_error', optimizer='adam') \n",
- " # Return the model\n",
- " return model\n",
- "\n",
- "# Check to make sure the data set is complete\n",
- "assert len(X_tot) == len(y_tot)\n",
- "\n",
- "# This is the number of points that will be used in as the training data\n",
- "dim=12\n",
- "\n",
- "# Separate the training data from the whole data set\n",
- "X_train = X_tot[:dim]\n",
- "y_train = y_tot[:dim]\n",
- "\n",
- "\n",
- "# Generate the training data for the RNN, using a sequence of 2\n",
- "rnn_input, rnn_training = format_data(y_train, 2)\n",
- "\n",
- "\n",
- "# Create a recurrent neural network in Keras and produce a summary of the \n",
- "# machine learning model\n",
- "# Change the method name to reflect which network you want to use\n",
- "model = dnn2_gru2(length_of_sequences = 2)\n",
- "model.summary()\n",
- "\n",
- "# Start the timer. Want to time training+testing\n",
- "start = timer()\n",
- "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
- "# validation split. Setting verbose to True prints information about each training iteration.\n",
- "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n",
- " verbose=True,validation_split=0.05)\n",
- "\n",
- "\n",
- "# This section plots the training loss and the validation loss as a function of training iteration.\n",
- "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
- "# being overtrained.\n",
- "for label in [\"loss\",\"val_loss\"]:\n",
- " plt.plot(hist.history[label],label=label)\n",
- "\n",
- "plt.ylabel(\"loss\")\n",
- "plt.xlabel(\"epoch\")\n",
- "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
- "plt.legend()\n",
- "plt.show()\n",
- "\n",
- "# Use the trained neural network to predict more points of the data set\n",
- "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n",
- "# Stop the timer and calculate the total time needed.\n",
- "end = timer()\n",
- "print('Time: ', end-start)\n",
- "\n",
- "\n",
- "# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)\n",
- "# \n",
- "# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.\n",
- "\n",
- "# Check to make sure the data set is complete\n",
- "assert len(X_tot) == len(y_tot)\n",
- "\n",
- "# This is the number of points that will be used in as the training data\n",
- "dim=12\n",
- "\n",
- "# Separate the training data from the whole data set\n",
- "X_train = X_tot[:dim]\n",
- "y_train = y_tot[:dim]\n",
- "\n",
- "# Reshape the data for Keras specifications\n",
- "X_train = X_train.reshape((dim, 1))\n",
- "y_train = y_train.reshape((dim, 1))\n",
- "\n",
- "\n",
- "# Create a recurrent neural network in Keras and produce a summary of the \n",
- "# machine learning model\n",
- "# Set the sequence length to 1 for regular data formatting \n",
- "model = rnn(length_of_sequences = 1)\n",
- "model.summary()\n",
- "\n",
- "# Start the timer. Want to time training+testing\n",
- "start = timer()\n",
- "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n",
- "# validation split. Setting verbose to True prints information about each training iteration.\n",
- "hist = model.fit(X_train, y_train, batch_size=None, epochs=150, \n",
- " verbose=True,validation_split=0.05)\n",
- "\n",
- "\n",
- "# This section plots the training loss and the validation loss as a function of training iteration.\n",
- "# This is not required for analyzing the couple cluster data but can help determine if the network is\n",
- "# being overtrained.\n",
- "for label in [\"loss\",\"val_loss\"]:\n",
- " plt.plot(hist.history[label],label=label)\n",
- "\n",
- "plt.ylabel(\"loss\")\n",
- "plt.xlabel(\"epoch\")\n",
- "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n",
- "plt.legend()\n",
- "plt.show()\n",
- "\n",
- "# Use the trained neural network to predict the remaining data points\n",
- "X_pred = X_tot[dim:]\n",
- "X_pred = X_pred.reshape((len(X_pred), 1))\n",
- "y_model = model.predict(X_pred)\n",
- "y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))\n",
- "\n",
- "# Plot the known data set and the predicted data set. The red box represents the region that was used\n",
- "# for the training data.\n",
- "fig, ax = plt.subplots()\n",
- "ax.plot(X_tot, y_tot, label=\"true\", linewidth=3)\n",
- "ax.plot(X_tot, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n",
- "ax.legend()\n",
- "# Created a red region to represent the points used in the training data.\n",
- "ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')\n",
- "plt.show()\n",
- "\n",
- "# Stop the timer and calculate the total time needed.\n",
- "end = timer()\n",
- "print('Time: ', end-start)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3c028690",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Generative Models\n",
- "\n",
- "**Generative models** describe a class of statistical models that are a contrast\n",
- "to **discriminative models**. Informally we say that generative models can\n",
- "generate new data instances while discriminative models discriminate between\n",
- "different kinds of data instances. A generative model could generate new photos\n",
- "of animals that look like 'real' animals while a discriminative model could tell\n",
- "a dog from a cat. More formally, given a data set $x$ and a set of labels /\n",
- "targets $y$. Generative models capture the joint probability $p(x, y)$, or\n",
- "just $p(x)$ if there are no labels, while discriminative models capture the\n",
- "conditional probability $p(y | x)$. Discriminative models generally try to draw\n",
- "boundaries in the data space (often high dimensional), while generative models\n",
- "try to model how data is placed throughout the space.\n",
- "\n",
- "**Note**: this material is thanks to Linus Ekstrøm."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "a005479e",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Generative Adversarial Networks\n",
- "\n",
- "**Generative Adversarial Networks** are a type of unsupervised machine learning\n",
- "algorithm proposed by [Goodfellow et. al](https://arxiv.org/pdf/1406.2661.pdf)\n",
- "in 2014 (short and good article).\n",
- "\n",
- "The simplest formulation of\n",
- "the model is based on a game theoretic approach, *zero sum game*, where we pit\n",
- "two neural networks against one another. We define two rival networks, one\n",
- "generator $g$, and one discriminator $d$. The generator directly produces\n",
- "samples"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d0dffd1b",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- "\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- " x = g(z; \\theta^{(g)})\n",
- "\\label{_auto1} \\tag{1}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "4c7b94fe",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Discriminator\n",
- "The discriminator attempts to distinguish between samples drawn from the\n",
- "training data and samples drawn from the generator. In other words, it tries to\n",
- "tell the difference between the fake data produced by $g$ and the actual data\n",
- "samples we want to do prediction on. The discriminator outputs a probability\n",
- "value given by"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "61339180",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- "\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- " d(x; \\theta^{(d)})\n",
- "\\label{_auto2} \\tag{2}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7a9204c2",
- "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",
- "learning process in a generative adversarial network is a zero-sum game, in\n",
- "which a function"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "dc620460",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- "\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- " v(\\theta^{(g)}, \\theta^{(d)})\n",
- "\\label{_auto3} \\tag{3}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "274b6221",
- "metadata": {
- "editable": true
- },
- "source": [
- "determines the reward for the discriminator, while the generator gets the\n",
- "conjugate reward"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7ac921a1",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- "\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- " -v(\\theta^{(g)}, \\theta^{(d)})\n",
- "\\label{_auto4} \\tag{4}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b42f7081",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Learning Process\n",
- "\n",
- "During learning both of the networks maximize their own reward function, so that\n",
- "the generator gets better and better at tricking the discriminator, while the\n",
- "discriminator gets better and better at telling the difference between the fake\n",
- "and real data. The generator and discriminator alternate on which one trains at\n",
- "one time (i.e. for one epoch). In other words, we keep the generator constant\n",
- "and train the discriminator, then we keep the discriminator constant to train\n",
- "the generator and repeat. It is this back and forth dynamic which lets GANs\n",
- "tackle otherwise intractable generative problems. As the generator improves with\n",
- " training, the discriminator's performance gets worse because it cannot easily\n",
- " tell the difference between real and fake. If the generator ends up succeeding\n",
- " perfectly, the the discriminator will do no better than random guessing i.e.\n",
- " 50\\%. This progression in the training poses a problem for the convergence\n",
- " criteria for GANs. The discriminator feedback gets less meaningful over time,\n",
- " if we continue training after this point then the generator is effectively\n",
- " training on junk data which can undo the learning up to that point. Therefore,\n",
- " we stop training when the discriminator starts outputting $1/2$ everywhere."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "1f9c6701",
- "metadata": {
- "editable": true
- },
- "source": [
- "## More about the Learning Process\n",
- "\n",
- "At convergence we have"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "89b9067e",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- "\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- " g^* = \\underset{g}{\\mathrm{argmin}}\\hspace{2pt}\n",
- " \\underset{d}{\\mathrm{max}}v(\\theta^{(g)}, \\theta^{(d)})\n",
- "\\label{_auto5} \\tag{5}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2264c357",
- "metadata": {
- "editable": true
- },
- "source": [
- "The default choice for $v$ is"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7a087f74",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- "\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- " v(\\theta^{(g)}, \\theta^{(d)}) = \\mathbb{E}_{x\\sim p_\\mathrm{data}}\\log d(x)\n",
- " + \\mathbb{E}_{x\\sim p_\\mathrm{model}}\n",
- " \\log (1 - d(x))\n",
- "\\label{_auto6} \\tag{6}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "e6557946",
- "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",
- "approximation of a partition function. In the case where"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "50dd2a46",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- "\n",
- "\n",
- "$$\n",
- "\\begin{equation}\n",
- " \\underset{d}{\\mathrm{max}}v(\\theta^{(g)}, \\theta^{(d)})\n",
- "\\label{_auto7} \\tag{7}\n",
- "\\end{equation}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7e997d75",
- "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) )."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d64335ff",
- "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",
- "process never converges because the generator and discriminator chase one\n",
- "another around in the parameter space indefinitely. A much deeper discussion on\n",
- "the currently open research problem of GAN convergence is available\n",
- "[here](https://www.deeplearningbook.org/contents/generative_models.html). To\n",
- "anyone interested in learning more about GANs it is a highly recommended read.\n",
- "Direct quote: \"In this best-performing formulation, the generator aims to\n",
- "increase the log probability that the discriminator makes a mistake, rather than\n",
- "aiming to decrease the log probability that the discriminator makes the correct\n",
- "prediction.\" [Another interesting read](https://arxiv.org/abs/1701.00160)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "f35bc917",
- "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",
- "adapted from the\n",
- "[google tutorial](https://www.tensorflow.org/tutorials/generative/dcgan)\n",
- "\n",
- "First we import our libraries"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "id": "44c10a9a",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import os\n",
- "import time\n",
- "import numpy as np\n",
- "import tensorflow as tf\n",
- "import matplotlib.pyplot as plt\n",
- "from tensorflow.keras import layers\n",
- "from tensorflow.keras.utils import plot_model"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "461c8f05",
- "metadata": {
- "editable": true
- },
- "source": [
- "Next we define our hyperparameters and import our data the usual way"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "id": "5ca09c8c",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "BUFFER_SIZE = 60000\n",
- "BATCH_SIZE = 256\n",
- "EPOCHS = 30\n",
- "\n",
- "data = tf.keras.datasets.mnist.load_data()\n",
- "(train_images, train_labels), (test_images, test_labels) = data\n",
- "train_images = np.reshape(train_images, (train_images.shape[0],\n",
- " 28,\n",
- " 28,\n",
- " 1)).astype('float32')\n",
- "\n",
- "# we normalize between -1 and 1\n",
- "train_images = (train_images - 127.5) / 127.5\n",
- "training_dataset = tf.data.Dataset.from_tensor_slices(\n",
- " train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "4872f2ad",
- "metadata": {
- "editable": true
- },
- "source": [
- "## MNIST and GANs\n",
- "\n",
- "Let's have a quick look"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "id": "1248ad33",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "plt.imshow(train_images[0], cmap='Greys')\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "61808c2b",
- "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",
- "trial and error can be done here to try to produce better performing models. For\n",
- "more advanced GANs this is by far the step where you can 'make or break' a\n",
- "model.\n",
- "\n",
- "We start with the generator. As stated in the introductory text the generator\n",
- "$g$ upsamples from a random sample to the shape of what we want to predict. In\n",
- "our case we are trying to predict MNIST images ($28\\times 28$ pixels)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "id": "fe8867c5",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def generator_model():\n",
- " \"\"\"\n",
- " The generator uses upsampling layers tf.keras.layers.Conv2DTranspose() to\n",
- " produce an image from a random seed. We start with a Dense layer taking this\n",
- " random sample as an input and subsequently upsample through multiple\n",
- " convolutional layers.\n",
- " \"\"\"\n",
- "\n",
- " # we define our model\n",
- " model = tf.keras.Sequential()\n",
- "\n",
- "\n",
- " # adding our input layer. Dense means that every neuron is connected and\n",
- " # the input shape is the shape of our random noise. The units need to match\n",
- " # in some sense the upsampling strides to reach our desired output shape.\n",
- " # we are using 100 random numbers as our seed\n",
- " model.add(layers.Dense(units=7*7*BATCH_SIZE,\n",
- " use_bias=False,\n",
- " input_shape=(100, )))\n",
- " # we normalize the output form the Dense layer\n",
- " model.add(layers.BatchNormalization())\n",
- " # and add an activation function to our 'layer'. LeakyReLU avoids vanishing\n",
- " # gradient problem\n",
- " model.add(layers.LeakyReLU())\n",
- " model.add(layers.Reshape((7, 7, BATCH_SIZE)))\n",
- " assert model.output_shape == (None, 7, 7, BATCH_SIZE)\n",
- " # even though we just added four keras layers we think of everything above\n",
- " # as 'one' layer\n",
- "\n",
- " # next we add our upscaling convolutional layers\n",
- " model.add(layers.Conv2DTranspose(filters=128,\n",
- " kernel_size=(5, 5),\n",
- " strides=(1, 1),\n",
- " padding='same',\n",
- " use_bias=False))\n",
- " model.add(layers.BatchNormalization())\n",
- " model.add(layers.LeakyReLU())\n",
- " assert model.output_shape == (None, 7, 7, 128)\n",
- "\n",
- " model.add(layers.Conv2DTranspose(filters=64,\n",
- " kernel_size=(5, 5),\n",
- " strides=(2, 2),\n",
- " padding='same',\n",
- " use_bias=False))\n",
- " model.add(layers.BatchNormalization())\n",
- " model.add(layers.LeakyReLU())\n",
- " assert model.output_shape == (None, 14, 14, 64)\n",
- "\n",
- " model.add(layers.Conv2DTranspose(filters=1,\n",
- " kernel_size=(5, 5),\n",
- " strides=(2, 2),\n",
- " padding='same',\n",
- " use_bias=False,\n",
- " activation='tanh'))\n",
- " assert model.output_shape == (None, 28, 28, 1)\n",
- "\n",
- " return model"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "48bd3c5b",
- "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",
- "classifier."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "id": "c713c710",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def discriminator_model():\n",
- " \"\"\"\n",
- " The discriminator is a convolutional neural network based image classifier\n",
- " \"\"\"\n",
- "\n",
- " # we define our model\n",
- " model = tf.keras.Sequential()\n",
- " model.add(layers.Conv2D(filters=64,\n",
- " kernel_size=(5, 5),\n",
- " strides=(2, 2),\n",
- " padding='same',\n",
- " input_shape=[28, 28, 1]))\n",
- " model.add(layers.LeakyReLU())\n",
- " # adding a dropout layer as you do in conv-nets\n",
- " model.add(layers.Dropout(0.3))\n",
- "\n",
- "\n",
- " model.add(layers.Conv2D(filters=128,\n",
- " kernel_size=(5, 5),\n",
- " strides=(2, 2),\n",
- " padding='same'))\n",
- " model.add(layers.LeakyReLU())\n",
- " # adding a dropout layer as you do in conv-nets\n",
- " model.add(layers.Dropout(0.3))\n",
- "\n",
- " model.add(layers.Flatten())\n",
- " model.add(layers.Dense(1))\n",
- "\n",
- " return model"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "a1dc2608",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Other Models\n",
- "Let us take a look at our models. **Note**: double click images for bigger view."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "id": "48dd8c9e",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "generator = generator_model()\n",
- "plot_model(generator, show_shapes=True, rankdir='LR')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "id": "0f581c34",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "discriminator = discriminator_model()\n",
- "plot_model(discriminator, show_shapes=True, rankdir='LR')"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "9924cefc",
- "metadata": {
- "editable": true
- },
- "source": [
- "Next we need a few helper objects we will use in training"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "id": "50712a5c",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n",
- "generator_optimizer = tf.keras.optimizers.Adam(1e-4)\n",
- "discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ddf3f0e1",
- "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",
- "is because they need to improve their accuracy at approximately equal speeds to\n",
- "get convergence (not necessarily exactly equal). Now we define our loss\n",
- "functions"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "id": "19d93fd5",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def generator_loss(fake_output):\n",
- " loss = cross_entropy(tf.ones_like(fake_output), fake_output)\n",
- "\n",
- " return loss"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "id": "4432394d",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def discriminator_loss(real_output, fake_output):\n",
- " real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n",
- " fake_loss = cross_entropy(tf.zeros_liks(fake_output), fake_output)\n",
- " total_loss = real_loss + fake_loss\n",
- "\n",
- " return total_loss"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "bc7155dd",
- "metadata": {
- "editable": true
- },
- "source": [
- "Next we define a kind of seed to help us compare the learning process over\n",
- "multiple training epochs."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "id": "5f8e2ac8",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "noise_dimension = 100\n",
- "n_examples_to_generate = 16\n",
- "seed_images = tf.random.normal([n_examples_to_generate, noise_dimension])"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "375ea5e6",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Training Step\n",
- "\n",
- "Now we have everything we need to define our training step, which we will apply\n",
- "for every step in our training loop. Notice the @tf.function flag signifying\n",
- "that the function is tensorflow 'compiled'. Removing this flag doubles the\n",
- "computation time."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "id": "d30d0d7a",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "@tf.function\n",
- "def train_step(images):\n",
- " noise = tf.random.normal([BATCH_SIZE, noise_dimension])\n",
- "\n",
- " with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n",
- " generated_images = generator(noise, training=True)\n",
- "\n",
- " real_output = discriminator(images, training=True)\n",
- " fake_output = discriminator(generated_images, training=True)\n",
- "\n",
- " gen_loss = generator_loss(fake_output)\n",
- " disc_loss = discriminator_loss(real_output, fake_output)\n",
- "\n",
- " gradients_of_generator = gen_tape.gradient(gen_loss,\n",
- " generator.trainable_variables)\n",
- " gradients_of_discriminator = disc_tape.gradient(disc_loss,\n",
- " discriminator.trainable_variables)\n",
- " generator_optimizer.apply_gradients(zip(gradients_of_generator,\n",
- " generator.trainable_variables))\n",
- " discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator,\n",
- " discriminator.trainable_variables))\n",
- "\n",
- " return gen_loss, disc_loss"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "0f4e4419",
- "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",
- "this code here, but comment it out in the training loop."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 19,
- "id": "5d73f712",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def generate_and_save_images(model, epoch, test_input):\n",
- " # we're making inferences here\n",
- " predictions = model(test_input, training=False)\n",
- "\n",
- " fig = plt.figure(figsize=(4, 4))\n",
- "\n",
- " for i in range(predictions.shape[0]):\n",
- " plt.subplot(4, 4, i+1)\n",
- " plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')\n",
- " plt.axis('off')\n",
- "\n",
- " plt.savefig(f'./images_from_seed_images/image_at_epoch_{str(epoch).zfill(3)}.png')\n",
- " plt.close()\n",
- " #plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "c9d625a0",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Checkpoints\n",
- "Setting up checkpoints to periodically save our model during training so that\n",
- "everything is not lost even if the program were to somehow terminate while\n",
- "training."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 20,
- "id": "7b8e092d",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Setting up checkpoints to save model during training\n",
- "checkpoint_dir = './training_checkpoints'\n",
- "checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt')\n",
- "checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n",
- " discriminator_optimizer=discriminator_optimizer,\n",
- " generator=generator,\n",
- " discriminator=discriminator)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d609d006",
- "metadata": {
- "editable": true
- },
- "source": [
- "Now we define our training loop"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 21,
- "id": "6b070a66",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def train(dataset, epochs):\n",
- " generator_loss_list = []\n",
- " discriminator_loss_list = []\n",
- "\n",
- " for epoch in range(epochs):\n",
- " start = time.time()\n",
- "\n",
- " for image_batch in dataset:\n",
- " gen_loss, disc_loss = train_step(image_batch)\n",
- " generator_loss_list.append(gen_loss.numpy())\n",
- " discriminator_loss_list.append(disc_loss.numpy())\n",
- "\n",
- " #generate_and_save_images(generator, epoch + 1, seed_images)\n",
- "\n",
- " if (epoch + 1) % 15 == 0:\n",
- " checkpoint.save(file_prefix=checkpoint_prefix)\n",
- "\n",
- " print(f'Time for epoch {epoch} is {time.time() - start}')\n",
- "\n",
- " #generate_and_save_images(generator, epochs, seed_images)\n",
- "\n",
- " loss_file = './data/lossfile.txt'\n",
- " with open(loss_file, 'w') as outfile:\n",
- " outfile.write(str(generator_loss_list))\n",
- " outfile.write('\\n')\n",
- " outfile.write('\\n')\n",
- " outfile.write(str(discriminator_loss_list))\n",
- " outfile.write('\\n')\n",
- " outfile.write('\\n')"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "6adbeece",
- "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."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 22,
- "id": "d9d2967e",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "train(train_dataset, EPOCHS)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "5ebfb622",
- "metadata": {
- "editable": true
- },
- "source": [
- "And here is the result of training our model for 100 epochs\n",
- "\n",
- "\n",
- ""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 23,
- "id": "beb99df1",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from IPython.display import HTML\n",
- "_s = \"\"\"\n",
- "\n",
- "
\n",
- "\"\"\"\n",
- "HTML(_s)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "47c73def",
- "metadata": {
- "editable": true
- },
- "source": [
- "\n",
- "\n",
- "Now to avoid having to train and everything, which will take a while depending\n",
- "on your computer setup we now load in the model which produced the above gif."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 24,
- "id": "76c10c8e",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))\n",
- "restored_generator = checkpoint.generator\n",
- "restored_discriminator = checkpoint.discriminator\n",
- "\n",
- "print(restored_generator)\n",
- "print(restored_discriminator)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "afcc9765",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Exploring the Latent Space\n",
- "\n",
- "We have successfully loaded in our latest model. Let us now play around a bit\n",
- "and see what kind of things we can learn about this model. Our generator takes\n",
- "an array of 100 numbers. One idea can be to try to systematically change our\n",
- "input. Let us try and see what we get"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 25,
- "id": "6588a84c",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def generate_latent_points(number=100, scale_means=1, scale_stds=1):\n",
- " latent_dim = 100\n",
- " means = scale_means * tf.linspace(-1, 1, num=latent_dim)\n",
- " stds = scale_stds * tf.linspace(-1, 1, num=latent_dim)\n",
- " latent_space_value_range = tf.random.normal([number, latent_dim],\n",
- " means,\n",
- " stds,\n",
- " dtype=tf.float64)\n",
- "\n",
- " return latent_space_value_range\n",
- "\n",
- "def generate_images(latent_points):\n",
- " # notice we set training to false because we are making inferences\n",
- " generated_images = restored_generator.predict(latent_points)\n",
- "\n",
- " return generated_images"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 26,
- "id": "8612bfe0",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def plot_result(generated_images, number=100):\n",
- " # obviously this assumes sqrt number is an int\n",
- " fig, axs = plt.subplots(int(np.sqrt(number)), int(np.sqrt(number)),\n",
- " figsize=(10, 10))\n",
- "\n",
- " for i in range(int(np.sqrt(number))):\n",
- " for j in range(int(np.sqrt(number))):\n",
- " axs[i, j].imshow(generated_images[i*j], cmap='Greys')\n",
- " axs[i, j].axis('off')\n",
- "\n",
- " plt.show()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 27,
- "id": "50f8077e",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "generated_images = generate_images(generate_latent_points())\n",
- "plot_result(generated_images)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "1583c26d",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Getting Results\n",
- "We see that the generator generates images that look like MNIST\n",
- "numbers: $1, 4, 7, 9$. Let's try to tweak it a bit more to see if we are able\n",
- "to generate a similar plot where we generate every MNIST number. Let us now try\n",
- "to 'move' a bit around in the latent space. **Note**: decrease the plot number if\n",
- "these following cells take too long to run on your computer."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 28,
- "id": "76a63595",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "plot_number = 225\n",
- "\n",
- "generated_images = generate_images(generate_latent_points(number=plot_number,\n",
- " scale_means=5,\n",
- " scale_stds=1))\n",
- "plot_result(generated_images, number=plot_number)\n",
- "\n",
- "generated_images = generate_images(generate_latent_points(number=plot_number,\n",
- " scale_means=-5,\n",
- " scale_stds=1))\n",
- "plot_result(generated_images, number=plot_number)\n",
- "\n",
- "generated_images = generate_images(generate_latent_points(number=plot_number,\n",
- " scale_means=1,\n",
- " scale_stds=5))\n",
- "plot_result(generated_images, number=plot_number)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7f697350",
- "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",
- "deviations seem to increase the number of different digits! In the last image\n",
- "above, we can barely make out every MNIST digit. Let us make on last plot using\n",
- "this information by upping the standard deviation of our Gaussian noises."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 29,
- "id": "0245f48d",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "plot_number = 400\n",
- "generated_images = generate_images(generate_latent_points(number=plot_number,\n",
- " scale_means=1,\n",
- " scale_stds=10))\n",
- "plot_result(generated_images, number=plot_number)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "88c2f763",
- "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."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2a14475d",
- "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",
- "[this excellent blogpost](https://machinelearningmastery.com/how-to-interpolate-and-perform-vector-arithmetic-with-faces-using-a-generative-adversarial-network/)\n",
- "by Jason Brownlee.\n",
- "\n",
- "So let us start by defining a function to interpolate between two points in the\n",
- "latent space."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 30,
- "id": "87bec507",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "def interpolation(point_1, point_2, n_steps=10):\n",
- " ratios = np.linspace(0, 1, num=n_steps)\n",
- " vectors = []\n",
- " for i, ratio in enumerate(ratios):\n",
- " vectors.append(((1.0 - ratio) * point_1 + ratio * point_2))\n",
- "\n",
- " return tf.stack(vectors)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "50de7c62",
- "metadata": {
- "editable": true
- },
- "source": [
- "Now we have all we need to do our interpolation analysis."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 31,
- "id": "169a4ddf",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "plot_number = 100\n",
- "latent_points = generate_latent_points(number=plot_number)\n",
- "results = None\n",
- "for i in range(0, 2*np.sqrt(plot_number), 2):\n",
- " interpolated = interpolation(latent_points[i], latent_points[i+1])\n",
- " generated_images = generate_images(interpolated)\n",
- "\n",
- " if results is None:\n",
- " results = generated_images\n",
- " else:\n",
- " results = tf.stack((results, generated_images))\n",
- "\n",
- "plot_results(results, plot_number)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "85ae3d2a",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Basic ideas of the Principal Component Analysis (PCA)\n",
- "\n",
- "The principal component analysis deals with the problem of fitting a\n",
- "low-dimensional affine subspace $S$ of dimension $d$ much smaller than\n",
- "the total dimension $D$ of the problem at hand (our data\n",
- "set). Mathematically it can be formulated as a statistical problem or\n",
- "a geometric problem. In our discussion of the theorem for the\n",
- "classical PCA, we will stay with a statistical approach. \n",
- "Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable.\n",
- "\n",
- "We have a data set defined by a design/feature matrix $\\boldsymbol{X}$ (see below for its definition) \n",
- "* Each data point is determined by $p$ extrinsic (measurement) variables\n",
- "\n",
- "* We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data?\n",
- "\n",
- "* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. \n",
- "\n",
- "A good read is for example [Vidal, Ma and Sastry](https://www.springer.com/gp/book/9780387878102)."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "090721ed",
- "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",
- "the definition of the covariance and the correlation function. These are quantities \n",
- "\n",
- "Suppose we have defined two vectors\n",
- "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ac9b9bf9",
- "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",
- " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "4452b018",
- "metadata": {
- "editable": true
- },
- "source": [
- "where for example"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "a876875d",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "bd544bd6",
- "metadata": {
- "editable": true
- },
- "source": [
- "With this definition and recalling that the variance is defined as"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "c16e6106",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "82d97aac",
- "metadata": {
- "editable": true
- },
- "source": [
- "we can rewrite the covariance matrix as"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "faf3e9a6",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n",
- " \\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3e9c4c64",
- "metadata": {
- "editable": true
- },
- "source": [
- "## More on the covariance\n",
- "The covariance takes values between zero and infinity and may thus\n",
- "lead to problems with loss of numerical precision for particularly\n",
- "large values. It is common to scale the covariance matrix by\n",
- "introducing instead the correlation matrix defined via the so-called\n",
- "correlation function"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "f68a7ead",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "29981a6f",
- "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",
- "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n",
- "and $\\boldsymbol{y}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "1c284543",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n",
- " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "f4226b36",
- "metadata": {
- "editable": true
- },
- "source": [
- "In the above example this is the function we constructed using **pandas**."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7cdc504e",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Reminding ourselves about Linear Regression\n",
- "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n",
- "we defined the design/feature matrix $\\boldsymbol{X}$ as"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "e5f4e808",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
- "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
- "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
- "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
- "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
- "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b693c9da",
- "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",
- "We can rewrite the design/feature matrix in terms of its column vectors as"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2c6171bc",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b613b25e",
- "metadata": {
- "editable": true
- },
- "source": [
- "with a given vector"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "df517ed7",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "417de4e9",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Simple Example\n",
- "With these definitions, we can now rewrite our $2\\times 2$\n",
- "correlation/covariance matrix in terms of a moe general design/feature\n",
- "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n",
- "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "1c0ee648",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "a9b12654",
- "metadata": {
- "editable": true
- },
- "source": [
- "## The Correlation Matrix\n",
- "\n",
- "and the correlation matrix"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "8f4547f0",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n",
- "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n",
- "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "493b6037",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Numpy Functionality\n",
- "\n",
- "The Numpy function **np.cov** calculates the covariance elements using\n",
- "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n",
- "the exact mean values. The following simple function uses the\n",
- "**np.vstack** function which takes each vector of dimension $1\\times n$\n",
- "and produces a $2\\times n$ matrix $\\boldsymbol{W}$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3158ec7d",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{W}^T = \\begin{bmatrix} x_0 & y_0 \\\\\n",
- " x_1 & y_1 \\\\\n",
- " x_2 & y_2\\\\\n",
- " \\dots & \\dots \\\\\n",
- " x_{n-2} & y_{n-2}\\\\\n",
- " x_{n-1} & y_{n-1} & \n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "00fe5e0c",
- "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",
- "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n",
- "function **np.mean(x)**. We can also extract the eigenvalues of the\n",
- "covariance matrix through the **np.linalg.eig()** function."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 32,
- "id": "72724b57",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Importing various packages\n",
- "import numpy as np\n",
- "n = 100\n",
- "x = np.random.normal(size=n)\n",
- "print(np.mean(x))\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "print(np.mean(y))\n",
- "W = np.vstack((x, y))\n",
- "C = np.cov(W)\n",
- "print(C)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ea4c06a4",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Correlation Matrix again\n",
- "\n",
- "The previous example can be converted into the correlation matrix by\n",
- "simply scaling the matrix elements with the variances. We should also\n",
- "subtract the mean values for each column. This leads to the following\n",
- "code which sets up the correlations matrix for the previous example in\n",
- "a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 33,
- "id": "c531bda3",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "n = 100\n",
- "# define two vectors \n",
- "x = np.random.random(size=n)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "#scaling the x and y vectors \n",
- "x = x - np.mean(x)\n",
- "y = y - np.mean(y)\n",
- "variance_x = np.sum(x@x)/n\n",
- "variance_y = np.sum(y@y)/n\n",
- "print(variance_x)\n",
- "print(variance_y)\n",
- "cov_xy = np.sum(x@y)/n\n",
- "cov_xx = np.sum(x@x)/n\n",
- "cov_yy = np.sum(y@y)/n\n",
- "C = np.zeros((2,2))\n",
- "C[0,0]= cov_xx/variance_x\n",
- "C[1,1]= cov_yy/variance_y\n",
- "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n",
- "C[1,0]= C[0,1]\n",
- "print(C)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "de5b39f6",
- "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**."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2e92766e",
- "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"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 34,
- "id": "2c212a03",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import pandas as pd\n",
- "n = 10\n",
- "x = np.random.normal(size=n)\n",
- "x = x - np.mean(x)\n",
- "y = 4+3*x+np.random.normal(size=n)\n",
- "y = y - np.mean(y)\n",
- "X = (np.vstack((x, y))).T\n",
- "print(X)\n",
- "Xpd = pd.DataFrame(X)\n",
- "print(Xpd)\n",
- "correlation_matrix = Xpd.corr()\n",
- "print(correlation_matrix)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "6dfd3cbc",
- "metadata": {
- "editable": true
- },
- "source": [
- "## And then the Franke Function\n",
- "\n",
- "We expand this model to the Franke function discussed above."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 35,
- "id": "1b22b6fd",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# Common imports\n",
- "import numpy as np\n",
- "import pandas as pd\n",
- "\n",
- "\n",
- "def FrankeFunction(x,y):\n",
- "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
- "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
- "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
- "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
- "\treturn term1 + term2 + term3 + term4\n",
- "\n",
- "\n",
- "def create_X(x, y, n ):\n",
- "\tif len(x.shape) > 1:\n",
- "\t\tx = np.ravel(x)\n",
- "\t\ty = np.ravel(y)\n",
- "\n",
- "\tN = len(x)\n",
- "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
- "\tX = np.ones((N,l))\n",
- "\n",
- "\tfor i in range(1,n+1):\n",
- "\t\tq = int((i)*(i+1)/2)\n",
- "\t\tfor k in range(i+1):\n",
- "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
- "\n",
- "\treturn X\n",
- "\n",
- "\n",
- "# Making meshgrid of datapoints and compute Franke's function\n",
- "n = 4\n",
- "N = 100\n",
- "x = np.sort(np.random.uniform(0, 1, N))\n",
- "y = np.sort(np.random.uniform(0, 1, N))\n",
- "z = FrankeFunction(x, y)\n",
- "X = create_X(x, y, n=n) \n",
- "\n",
- "Xpd = pd.DataFrame(X)\n",
- "# subtract the mean values and set up the covariance matrix\n",
- "Xpd = Xpd - Xpd.mean()\n",
- "covariance_matrix = Xpd.cov()\n",
- "print(covariance_matrix)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "c300052e",
- "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."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "86948c3e",
- "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"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b9e71c39",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "cb255745",
- "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",
- "id": "2bd67de5",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00} & x_{01}\\\\\n",
- "x_{10} & x_{11}\\\\\n",
- "\\end{bmatrix}=\\begin{bmatrix}\n",
- "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n",
- "\\end{bmatrix}.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "dcfb0032",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Computing the Expectation Values\n",
- "\n",
- "If we then compute the expectation value"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "4e60fe22",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n",
- "x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "c306e801",
- "metadata": {
- "editable": true
- },
- "source": [
- "which is just"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "afb7f0cb",
- "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",
- " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n",
- " \\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "4cd98212",
- "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}$."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d19211a1",
- "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"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "c67cc4e9",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7b1eaa9b",
- "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",
- "\n",
- "Assume also that there is a transformation $\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}=\\boldsymbol{C}[\\boldsymbol{y}]$ such that the new matrix $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal with elements $[\\lambda_0,\\lambda_1,\\lambda_2,\\dots,\\lambda_{p-1}]$. \n",
- "\n",
- "That is we have"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2f6c8503",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "8a4112f7",
- "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",
- "id": "f5ac5fa8",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "9a6681bc",
- "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",
- "id": "4367f34d",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{S}_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}_i.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "2a346c2d",
- "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",
- "The eigenvalues tell us then how much we need to stretch the\n",
- "corresponding eigenvectors. Dimensions with large eigenvalues have\n",
- "thus large variations (large variance) and define therefore useful\n",
- "dimensions. The data points are more spread out in the direction of\n",
- "these eigenvectors. Smaller eigenvalues mean on the other hand that\n",
- "the corresponding eigenvectors are shrunk accordingly and the data\n",
- "points are tightly bunched together and there is not much variation in\n",
- "these specific directions. Hopefully then we could leave it out\n",
- "dimensions where the eigenvalues are very small. If $p$ is very large,\n",
- "we could then aim at reducing $p$ to $l << p$ and handle only $l$\n",
- "features/predictors."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "59f55fef",
- "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",
- "* Set up the datapoints for the design/feature matrix $\\boldsymbol{X}$ with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ referring to the column numbers and the entries $n$ being the row elements."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ab36f66c",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{X}=\\begin{bmatrix}\n",
- "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n",
- "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n",
- "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n",
- "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n",
- "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n",
- "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n",
- "\\end{bmatrix},\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b975e498",
- "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",
- "* Compute then the covariance/correlation matrix $\\mathbb{E}[\\overline{\\boldsymbol{X}}^T\\overline{\\boldsymbol{X}}]$.\n",
- "\n",
- "* Find the eigenpairs of $\\boldsymbol{C}$ with eigenvalues $[\\lambda_0,\\lambda_1,\\dots,\\lambda_{p-1}]$ and eigenvectors $[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$.\n",
- "\n",
- "* Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.\n",
- "\n",
- "* Keep only those $l$ eigenvalues larger than a selected threshold value, discarding thus $p-l$ features since we expect small variations in the data here."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "f1065453",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Writing our own PCA code\n",
- "\n",
- "We will use a simple example first with two-dimensional data\n",
- "drawn from a multivariate normal distribution with the following mean and covariance matrix (we have fixed these quantities but will play around with them below):"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "0066482f",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\mu = (-1,2) \\qquad \\Sigma = \\begin{bmatrix} 4 & 2 \\\\\n",
- "2 & 2\n",
- "\\end{bmatrix}\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "4f807a3f",
- "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."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "e31a55ba",
- "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$."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 36,
- "id": "c098cc4e",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import pandas as pd\n",
- "import matplotlib.pyplot as plt\n",
- "from IPython.display import display\n",
- "n = 10000\n",
- "mean = (-1, 2)\n",
- "cov = [[4, 2], [2, 2]]\n",
- "X = np.random.multivariate_normal(mean, cov, n)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "0ea28cbe",
- "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": "05f17319",
- "metadata": {
- "editable": true
- },
- "source": [
- "## First Step\n",
- "\n",
- "The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d116f6f9",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\mu_n = \\frac{1}{n} \\sum_{i=1}^n x_i\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "9d26cd23",
- "metadata": {
- "editable": true
- },
- "source": [
- "and the mean-centered data $\\bar{X} = \\{ \\bar{x}_1, \\ldots, \\bar{x}_n \\}$ takes the form"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "47051865",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\bar{x}_i = x_i - \\mu_n.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "64c7a2e3",
- "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",
- "centered at the origin! \n",
- "The following code elements perform these operations using **pandas** or using our own functionality for doing so. The latter, using **numpy** is rather simple through the **mean()** function."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 37,
- "id": "daf0ce1c",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "df = pd.DataFrame(X)\n",
- "# Pandas does the centering for us\n",
- "df = df -df.mean()\n",
- "# we center it ourselves\n",
- "X_centered = X - X.mean(axis=0)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "0cf49f56",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Scaling\n",
- "Alternatively, we could use the functions we discussed\n",
- "earlier for scaling the data set. That is, we could have used the\n",
- "**StandardScaler** function in **Scikit-Learn**, a function which ensures\n",
- "that for each feature/predictor we study the mean value is zero and\n",
- "the variance is one (every column in the design/feature matrix). You\n",
- "would then not get the same results, since we divide by the\n",
- "variance. The diagonal covariance matrix elements will then be one,\n",
- "while the non-diagonal ones need to be divided by $2\\sqrt{2}$ for our\n",
- "specific case."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "730806f0",
- "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"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ae8d7cc8",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "53c9bdde",
- "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"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 38,
- "id": "31e91d87",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "print(df.cov())\n",
- "print(np.cov(X_centered.T))"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "1aed4afb",
- "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."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 39,
- "id": "54c879c1",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# extract the relevant columns from the centered design matrix of dim n x 2\n",
- "x = X_centered[:,0]\n",
- "y = X_centered[:,1]\n",
- "Cov = np.zeros((2,2))\n",
- "Cov[0,1] = np.sum(x.T@y)/(n-1.0)\n",
- "Cov[0,0] = np.sum(x.T@x)/(n-1.0)\n",
- "Cov[1,1] = np.sum(y.T@y)/(n-1.0)\n",
- "Cov[1,0]= Cov[0,1]\n",
- "print(\"Centered covariance using own code\")\n",
- "print(Cov)\n",
- "plt.plot(x, y, 'x')\n",
- "plt.axis('equal')\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7a0f246b",
- "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."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "22931505",
- "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",
- "diagonalize the sample covariance matrix $\\Sigma$. We can use the\n",
- "function **np.linalg.eig** to do so. It will return the eigenvalues and\n",
- "eigenvectors of $\\Sigma$. Once we have these we can perform the \n",
- "following tasks:\n",
- "\n",
- "* We compute the percentage of the total variance captured by the first principal component\n",
- "\n",
- "* We plot the mean centered data and lines along the first and second principal components\n",
- "\n",
- "* Then we project the mean centered data onto the first and second principal components, and plot the projected data. \n",
- "\n",
- "* Finally, we approximate the data as"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b62266c9",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "x_i \\approx \\tilde{x}_i = \\mu_n + \\langle x_i, v_0 \\rangle v_0\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "6f283411",
- "metadata": {
- "editable": true
- },
- "source": [
- "where $v_0$ is the first principal component."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "f2fb0eee",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Collecting all Steps\n",
- "\n",
- "Collecting all these steps we can write our own PCA function and\n",
- "compare this with the functionality included in **Scikit-Learn**. \n",
- "\n",
- "The code here outlines some of the elements we could include in the\n",
- "analysis. Feel free to extend upon this in order to address the above\n",
- "questions."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "id": "4f9bcd7e",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "# diagonalize and obtain eigenvalues, not necessarily sorted\n",
- "EigValues, EigVectors = np.linalg.eig(Cov)\n",
- "# sort eigenvectors and eigenvalues\n",
- "#permute = EigValues.argsort()\n",
- "#EigValues = EigValues[permute]\n",
- "#EigVectors = EigVectors[:,permute]\n",
- "print(\"Eigenvalues of Covariance matrix\")\n",
- "for i in range(2):\n",
- " print(EigValues[i])\n",
- "FirstEigvector = EigVectors[:,0]\n",
- "SecondEigvector = EigVectors[:,1]\n",
- "print(\"First eigenvector\")\n",
- "print(FirstEigvector)\n",
- "print(\"Second eigenvector\")\n",
- "print(SecondEigvector)\n",
- "#thereafter we do a PCA with Scikit-learn\n",
- "from sklearn.decomposition import PCA\n",
- "pca = PCA(n_components = 2)\n",
- "X2Dsl = pca.fit_transform(X)\n",
- "print(\"Eigenvector of largest eigenvalue\")\n",
- "print(pca.components_.T[:, 0])"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ad5d8bd2",
- "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": "8447c3c3",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Classical PCA Theorem\n",
- "\n",
- "We assume now that we have a design matrix $\\boldsymbol{X}$ which has been\n",
- "centered as discussed above. For the sake of simplicity we skip the\n",
- "overline symbol. The matrix is defined in terms of the various column\n",
- "vectors $[\\boldsymbol{x}_0,\\boldsymbol{x}_1,\\dots, \\boldsymbol{x}_{p-1}]$ each with dimension\n",
- "$\\boldsymbol{x}\\in {\\mathbb{R}}^{n}$.\n",
- "\n",
- "The PCA theorem states that minimizing the above reconstruction error\n",
- "corresponds to setting $\\boldsymbol{W}=\\boldsymbol{S}$, the orthogonal matrix which\n",
- "diagonalizes the empirical covariance(correlation) matrix. The optimal\n",
- "low-dimensional encoding of the data is then given by a set of vectors\n",
- "$\\boldsymbol{z}_i$ with at most $l$ vectors, with $l << p$, defined by the\n",
- "orthogonal projection of the data onto the columns spanned by the\n",
- "eigenvectors of the covariance(correlations matrix)."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b127c2a1",
- "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",
- "We are almost there, we have obtained a relation between minimizing\n",
- "the reconstruction error and the variance and the covariance\n",
- "matrix. Minimizing the error is equivalent to maximizing the variance\n",
- "of the projected data.\n",
- "\n",
- "We could trivially maximize the variance of the projection (and\n",
- "thereby minimize the error in the reconstruction function) by letting\n",
- "the norm-2 of $\\boldsymbol{w}_0$ go to infinity. However, this norm since we\n",
- "want the matrix $\\boldsymbol{W}$ to be an orthogonal matrix, is constrained by\n",
- "$\\vert\\vert \\boldsymbol{w}_0 \\vert\\vert_2^2=1$. Imposing this condition via a\n",
- "Lagrange multiplier we can then in turn maximize"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "83adaedf",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3be07303",
- "metadata": {
- "editable": true
- },
- "source": [
- "Taking the derivative with respect to $\\boldsymbol{w}_0$ we obtain"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "24f72531",
- "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",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "6bf3baed",
- "metadata": {
- "editable": true
- },
- "source": [
- "meaning that"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "9e7ea828",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0\\boldsymbol{w}_0.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "336873c8",
- "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",
- "id": "d1270aab",
- "metadata": {
- "editable": true
- },
- "source": [
- "$$\n",
- "\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0.\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "11da32f3",
- "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",
- "largest eigenvalue. This establishes the link between the minimization\n",
- "of the reconstruction function $J$ in terms of an orthogonal matrix\n",
- "and the maximization of the variance and thereby the covariance of our\n",
- "observations encoded in the design/feature matrix $\\boldsymbol{X}$.\n",
- "\n",
- "The proof\n",
- "for the other eigenvectors $\\boldsymbol{w}_1,\\boldsymbol{w}_2,\\dots$ can be\n",
- "established by applying the above arguments and using the fact that\n",
- "our basis of eigenvectors is orthogonal, see [Murphy chapter\n",
- "12.2](https://mitpress.mit.edu/books/machine-learning-1). The\n",
- "discussion in chapter 12.2 of Murphy's text has also a nice link with\n",
- "the Singular Value Decomposition theorem. For categorical data, see\n",
- "chapter 12.4 and discussion therein.\n",
- "\n",
- "For more details, see for example [Vidal, Ma and Sastry, chapter 2](https://www.springer.com/gp/book/9780387878102)."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "a733436e",
- "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",
- "Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.\n",
- "First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.\n",
- "\n",
- "The following Python code uses NumPy’s **svd()** function to obtain all the principal components of the\n",
- "training set, then extracts the first two principal components. First we center the data using either **pandas** or our own code"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 41,
- "id": "aa097235",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import pandas as pd\n",
- "from IPython.display import display\n",
- "np.random.seed(100)\n",
- "# setting up a 10 x 5 vanilla matrix \n",
- "rows = 10\n",
- "cols = 5\n",
- "X = np.random.randn(rows,cols)\n",
- "df = pd.DataFrame(X)\n",
- "# Pandas does the centering for us\n",
- "df = df -df.mean()\n",
- "display(df)\n",
- "\n",
- "# we center it ourselves\n",
- "X_centered = X - X.mean(axis=0)\n",
- "# Then check the difference between pandas and our own set up\n",
- "print(X_centered-df)\n",
- "#Now we do an SVD\n",
- "U, s, V = np.linalg.svd(X_centered)\n",
- "c1 = V.T[:, 0]\n",
- "c2 = V.T[:, 1]\n",
- "W2 = V.T[:, :2]\n",
- "X2D = X_centered.dot(W2)\n",
- "print(X2D)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "1c68d5eb",
- "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",
- "forget to center the data first.\n",
- "\n",
- "Once you have identified all the principal components, you can reduce the dimensionality of the dataset\n",
- "down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components.\n",
- "Selecting this hyperplane ensures that the projection will preserve as much variance as possible."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 42,
- "id": "3de742c4",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "W2 = V.T[:, :2]\n",
- "X2D = X_centered.dot(W2)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3f205661",
- "metadata": {
- "editable": true
- },
- "source": [
- "## PCA and scikit-learn\n",
- "\n",
- "Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The\n",
- "following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note\n",
- "that it automatically takes care of centering the data):"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 43,
- "id": "67475c8a",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "#thereafter we do a PCA with Scikit-learn\n",
- "from sklearn.decomposition import PCA\n",
- "pca = PCA(n_components = 2)\n",
- "X2D = pca.fit_transform(X)\n",
- "print(X2D)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "60d37815",
- "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",
- "principal component is equal to"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 44,
- "id": "7be09d48",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "pca.components_.T[:, 0]"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "41c3c78b",
- "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."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3ef0d7f4",
- "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."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 45,
- "id": "d51362ba",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "import matplotlib.pyplot as plt\n",
- "import numpy as np\n",
- "from sklearn.model_selection import train_test_split \n",
- "from sklearn.datasets import load_breast_cancer\n",
- "from sklearn.linear_model import LogisticRegression\n",
- "cancer = load_breast_cancer()\n",
- "\n",
- "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
- "\n",
- "logreg = LogisticRegression()\n",
- "logreg.fit(X_train, y_train)\n",
- "print(\"Train set accuracy from Logistic Regression: {:.2f}\".format(logreg.score(X_train,y_train)))\n",
- "# We scale the data\n",
- "from sklearn.preprocessing import StandardScaler\n",
- "scaler = StandardScaler()\n",
- "scaler.fit(X_train)\n",
- "X_train_scaled = scaler.transform(X_train)\n",
- "X_test_scaled = scaler.transform(X_test)\n",
- "# Then perform again a log reg fit\n",
- "logreg.fit(X_train_scaled, y_train)\n",
- "print(\"Train set accuracy scaled data: {:.2f}\".format(logreg.score(X_train_scaled,y_train)))\n",
- "#thereafter we do a PCA with Scikit-learn\n",
- "from sklearn.decomposition import PCA\n",
- "pca = PCA(n_components = 2)\n",
- "X2D_train = pca.fit_transform(X_train_scaled)\n",
- "# and finally compute the log reg fit and the score on the training data\t\n",
- "logreg.fit(X2D_train,y_train)\n",
- "print(\"Train set accuracy scaled and PCA data: {:.2f}\".format(logreg.score(X2D_train,y_train)))"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3e380841",
- "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",
- "Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to\n",
- "choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).\n",
- "Unless, of course, you are reducing dimensionality for data visualization — in that case you will\n",
- "generally want to reduce the dimensionality down to 2 or 3.\n",
- "The following code computes PCA without reducing dimensionality, then computes the minimum number\n",
- "of dimensions required to preserve 95% of the training set’s variance:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 46,
- "id": "ca2f6d3d",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "pca = PCA()\n",
- "pca.fit(X)\n",
- "cumsum = np.cumsum(pca.explained_variance_ratio_)\n",
- "d = np.argmax(cumsum >= 0.95) + 1"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3da7b4f7",
- "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",
- "a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 47,
- "id": "378b56fc",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "pca = PCA(n_components=0.95)\n",
- "X_reduced = pca.fit_transform(X)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "1b31ecd4",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Incremental PCA\n",
- "\n",
- "One problem with the preceding implementation of PCA is that it requires the whole training set to fit in\n",
- "memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have\n",
- "been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch\n",
- "at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new\n",
- "instances arrive)."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ad8ef5d2",
- "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$."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "955d7d0a",
- "metadata": {
- "editable": true
- },
- "source": [
- "### Kernel PCA\n",
- "\n",
- "The kernel trick is a mathematical technique that implicitly maps instances into a\n",
- "very high-dimensional space (called the feature space), enabling nonlinear classification and regression\n",
- "with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature\n",
- "space corresponds to a complex nonlinear decision boundary in the original space.\n",
- "It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear\n",
- "projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at\n",
- "preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a\n",
- "twisted manifold.\n",
- "For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 48,
- "id": "faa1ce89",
- "metadata": {
- "collapsed": false,
- "editable": true
- },
- "outputs": [],
- "source": [
- "from sklearn.decomposition import KernelPCA\n",
- "rbf_pca = KernelPCA(n_components = 2, kernel=\"rbf\", gamma=0.04)\n",
- "X_reduced = rbf_pca.fit_transform(X)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "35bf0446",
- "metadata": {
- "editable": true
- },
- "source": [
- "## Other techniques\n",
- "\n",
- "There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.\n",
- "\n",
- "Here are some of the most popular:\n",
- "* **Multidimensional Scaling (MDS)** reduces dimensionality while trying to preserve the distances between the instances.\n",
- "\n",
- "* **Isomap** creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.\n",
- "\n",
- "* **t-Distributed Stochastic Neighbor Embedding** (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).\n",
- "\n",
- "* Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures."
- ]
- }
- ],
- "metadata": {},
- "nbformat": 4,
- "nbformat_minor": 5
-}