Skip to content

Commit 7940aac

Browse files
committed
complete (near final) text and structure
1 parent 2fb127c commit 7940aac

File tree

1 file changed

+93
-31
lines changed

1 file changed

+93
-31
lines changed

lab3/solutions/Lab3_Part_1_Introduction_to_CAPSA.ipynb

Lines changed: 93 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
"\n",
5151
"In this lab, we'll explore different ways to make deep learning models more **robust** and **trustworthy**.\n",
5252
"\n",
53-
"To achieve this it is critical to be able to identify and diagnose issues of bias and uncertainty in deep learning models, as we explored in the Facial Detection Lab 2. We need benchmarks that uniformly measure how uncertain a given model is, and we need principled ways of measuring bias and uncertainty. To that end, in this lab, we'll utilize [CAPSA](https://github.com/themis-ai/capsa), a risk-estimation wrapping library developed by [Themis AI](https://themisai.io/). CAPSA supports the estimation of three different types of ***risk***, defined as measures of how robust and trustworthy our model is. These are:\n",
53+
"To achieve this it is critical to be able to identify and diagnose issues of bias and uncertainty in deep learning models, as we explored in the Facial Detection Lab 2. We need benchmarks that uniformly measure how uncertain a given model is, and we need principled ways of measuring bias and uncertainty. To that end, in this lab, we'll utilize [Capsa](https://github.com/themis-ai/capsa), a risk-estimation wrapping library developed by [Themis AI](https://themisai.io/). Capsa supports the estimation of three different types of ***risk***, defined as measures of how robust and trustworthy our model is. These are:\n",
5454
"1. **Representation bias**: reflects how likely combinations of features are to appear in a given dataset. Often, certain combinations of features are severely under-represented in datasets, which means models learn them less well and can thus lead to unwanted bias.\n",
5555
"2. **Data uncertainty**: reflects noise in the data, for example when sensors have noisy measurements, classes in datasets have low separations, and generally when very similar inputs lead to drastically different outputs. Also known as *aleatoric* uncertainty. \n",
5656
"3. **Model uncertainty**: captures the areas of our underlying data distribution that the model has not yet learned or has difficulty learning. Areas of high model uncertainty can be due to out-of-distribution (OOD) samples or data that is harder to learn. Also known as *epistemic* uncertainty."
@@ -64,13 +64,13 @@
6464
"source": [
6565
"## CAPSA overview\n",
6666
"\n",
67-
"This lab introduces `CAPSA` and its functionalities, to next build automated tools that use `CAPSA` to mitigate the underlying issues of bias and uncertainty.\n",
67+
"This lab introduces Capsa and its functionalities, to next build automated tools that use Capsa to mitigate the underlying issues of bias and uncertainty.\n",
6868
"\n",
69-
"The core idea behind `CAPSA` is that any deep learning model of interest can be ***wrapped*** -- just like wrapping a gift -- to be made ***aware of its own risks***. Risk is captured in representation bias, data uncertainty, and model uncertainty.\n",
69+
"The core idea behind Capsa is that any deep learning model of interest can be ***wrapped*** -- just like wrapping a gift -- to be made ***aware of its own risks***. Risk is captured in representation bias, data uncertainty, and model uncertainty.\n",
7070
"\n",
7171
"![alt text](https://raw.githubusercontent.com/aamini/introtodeeplearning/2023/lab3/img/capsa_overview.png)\n",
7272
"\n",
73-
"This means that `CAPSA` takes the user's original model as input, and modifies it minimally to create a risk-aware variant while preserving the model's underlying structure and training pipeline. `CAPSA` is a one-line addition to any training workflow in TensorFlow. In this part of the lab, we'll apply `CAPSA`'s risk estimation methods to a simple regression problem to further explore the notions of bias and uncertainty. "
73+
"This means that Capsa takes the user's original model as input, and modifies it minimally to create a risk-aware variant while preserving the model's underlying structure and training pipeline. Capsa is a one-line addition to any training workflow in TensorFlow. In this part of the lab, we'll apply Capsa's risk estimation methods to a simple regression problem to further explore the notions of bias and uncertainty. "
7474
]
7575
},
7676
{
@@ -128,9 +128,9 @@
128128
"!pip install mitdeeplearning\n",
129129
"import mitdeeplearning as mdl\n",
130130
"\n",
131-
"# Download and import CAPSA\n",
131+
"# Download and import Capsa\n",
132132
"!pip install capsa\n",
133-
"from capsa import *"
133+
"import capsa"
134134
]
135135
},
136136
{
@@ -317,8 +317,8 @@
317317
"\n",
318318
"Write short (~1 sentence) answers to the questions below to complete the `TODO`s:\n",
319319
"\n",
320-
"1. Where does the model perform well? How does this relate to aleatoric and epistemic uncertainty?\n",
321-
"2. Where does the model perform poorly? How does this relate to aleatoric and epistemic uncertainty?"
320+
"1. Where does the model perform well?\n",
321+
"2. Where does the model perform poorly?"
322322
],
323323
"metadata": {
324324
"id": "7Vktjwfu0ReH"
@@ -334,9 +334,9 @@
334334
"\n",
335335
"Now that we've seen what the predictions from this model look like, we will identify and quantify bias and uncertainty in this problem. We first consider bias.\n",
336336
"\n",
337-
"Recall that *representation bias* reflects how likely combinations of features are to appear in a given dataset. `Capsa` calculates how likely combinations of features are by using a histogram estimation approach: the `HistogramWrapper`. For low-dimensional data, the `HistogramWrapper` bins the input directly into discrete categories and measures the density. \n",
337+
"Recall that *representation bias* reflects how likely combinations of features are to appear in a given dataset. Capsa calculates how likely combinations of features are by using a histogram estimation approach: the `capsa.HistogramWrapper`. For low-dimensional data, the `capsa.HistogramWrapper` bins the input directly into discrete categories and measures the density. \n",
338338
"\n",
339-
"We start by taking our `dense_NN` and wrapping it with the `HistogramWrapper`:"
339+
"We start by taking our `dense_NN` and wrapping it with the `capsa.HistogramWrapper`:"
340340
]
341341
},
342342
{
@@ -350,11 +350,11 @@
350350
"### Wrap the dense network for bias estimation ###\n",
351351
"\n",
352352
"standard_dense_NN = create_dense_NN()\n",
353-
"bias_wrapped_dense_NN = HistogramWrapper(\n",
353+
"bias_wrapped_dense_NN = capsa.HistogramWrapper(\n",
354354
" standard_dense_NN, # the original model\n",
355355
" queue_size=2000, # how many samples to track\n",
356356
" target_hidden_layer=False # for low-dimensional data, we can estimate densities directly from data\n",
357-
" ) \n"
357+
" )\n"
358358
]
359359
},
360360
{
@@ -477,7 +477,7 @@
477477
"id": "_6iVeeqq0f_H"
478478
},
479479
"source": [
480-
"We can now use our wrapped model to assess the bias for a given test input. With the wrapping capability, `Capsa` neatly allows us to output a *bias score* along with the predicted target value. This bias score reflects the density of data surrounding an input point -- the higher the score, the greater the data representation and density. The wrapped, risk-aware model outputs the predicted target and bias score after it is called!\n",
480+
"We can now use our wrapped model to assess the bias for a given test input. With the wrapping capability, Capsa neatly allows us to output a *bias score* along with the predicted target value. This bias score reflects the density of data surrounding an input point -- the higher the score, the greater the data representation and density. The wrapped, risk-aware model outputs the predicted target and bias score after it is called!\n",
481481
"\n",
482482
"Let's see how it is done:"
483483
]
@@ -554,9 +554,9 @@
554554
"\n",
555555
"As introduced in Lecture 5 on Robust & Trustworthy Deep Learning, in regression we can estimate aleatoric uncertainty by training the model to predict both a target value and a variance for every input. Because we estimate both a mean and variance for every input, this method is called Mean Variance Estimation (MVE). MVE involves modifying the output layer to predict both the mean and variance, and changing the loss to reflect the prediction likelihood.\n",
556556
"\n",
557-
"`Capsa` automatically implements these changes for us: we can wrap a given model using `MVEWrapper` to use MVE to estimate aleatoric uncertainty. All we have to do is define the model and the loss function to evaluate its predictions!\n",
557+
"Capsa automatically implements these changes for us: we can wrap a given model using `capsa.MVEWrapper` to use MVE to estimate aleatoric uncertainty. All we have to do is define the model and the loss function to evaluate its predictions!\n",
558558
"\n",
559-
"Let's take our standard network, wrap it with `MVEWrapper`, build the wrapped model, and then train it for the regression task. Finally, we evaluate performance of the resulting model by quantifying the aleatoric uncertainty across the data space: "
559+
"Let's take our standard network, wrap it with `capsa.MVEWrapper`, build the wrapped model, and then train it for the regression task. Finally, we evaluate performance of the resulting model by quantifying the aleatoric uncertainty across the data space: "
560560
]
561561
},
562562
{
@@ -571,7 +571,7 @@
571571
"\n",
572572
"standard_dense_NN = create_dense_NN()\n",
573573
"# Wrap the dense network for aleatoric uncertainty estimation\n",
574-
"mve_wrapped_NN = MVEWrapper(standard_dense_NN)\n",
574+
"mve_wrapped_NN = capsa.MVEWrapper(standard_dense_NN)\n",
575575
"\n",
576576
"# Build the model for regression, defining the loss function and optimizer\n",
577577
"mve_wrapped_NN.compile(\n",
@@ -582,7 +582,7 @@
582582
"# Train the wrapped model for 30 epochs.\n",
583583
"loss_history_mve_wrap = mve_wrapped_NN.fit(x_train, y_train, epochs=30)\n",
584584
"\n",
585-
"# Call the uncertainty-aware model to generate scores for the test data\n",
585+
"# Call the uncertainty-aware model to generate outputs for the test data\n",
586586
"outputs = mve_wrapped_NN(x_test)\n",
587587
"# Capsa makes the aleatoric uncertainty an attribute of the prediction!\n",
588588
"aleatoric_unc = outputs.aleatoric\n",
@@ -612,8 +612,11 @@
612612
"id": "6FC5WPRT5lAb"
613613
},
614614
"source": [
615-
"## 1.4 Epistemic Estimation\n",
616-
"Finally, let's do the same thing but for epistemic estimation! In this example, we'll use ensembles, which essentially copy the model `N` times and average predictions across all runs for a more robust prediction, and also calculate the variance of the `N` runs. Feel free to play around with any of the epistemic methods shown in the github repository! Which methods perform the best? Why do you think this is?"
615+
"# 1.5 Estimating model uncertainty\n",
616+
"\n",
617+
"Finally, we use Capsa for estimating the uncertainty underlying the model predictions -- the epistemic uncertainty. In this example, we'll use ensembles, which essentially copy the model `N` times and average predictions across all runs for a more robust prediction, and also calculate the variance of the `N` runs to estimate the uncertainty.\n",
618+
"\n",
619+
"Capsa provides a neat wrapper, `capsa.EnsembleWrapper`, to make an ensemble from an input model. Just like with aleatoric estimation, we can take our standard dense network model, wrap it with `capsa.EnsembleWrapper`, build the wrapped model, and then train it for the regression task. Finally, we evaluate the resulting model by quantifying the epistemic uncertainty on the test data:"
617620
]
618621
},
619622
{
@@ -695,15 +698,29 @@
695698
}
696699
],
697700
"source": [
698-
"standard_classifier = create_standard_classifier()\n",
699-
"ensemble_wrapper = EnsembleWrapper(standard_classifier, num_members=5)\n",
701+
"### Estimating model uncertainty with Capsa wrapping ###\n",
702+
"\n",
703+
"standard_dense_NN = create_dense_NN()\n",
704+
"# Wrap the dense network for epistemic uncertainty estimation with a 5-member Ensemble\n",
705+
"ensemble_NN = capsa.EnsembleWrapper(standard_dense_NN, num_members=5)\n",
700706
"\n",
701-
"ensemble_wrapper.compile(\n",
707+
"# Build the model for regression, defining the loss function and optimizer\n",
708+
"ensemble_NN.compile(\n",
702709
" optimizer=tf.keras.optimizers.Adam(learning_rate=3e-3),\n",
703-
" loss=tf.keras.losses.MeanSquaredError(),\n",
710+
" loss=tf.keras.losses.MeanSquaredError(), # MSE loss for the regression task\n",
704711
")\n",
705712
"\n",
706-
"history = ensemble_wrapper.fit(x, y, epochs=30)"
713+
"# Train the wrapped model for 30 epochs.\n",
714+
"loss_history_ensemble = ensemble_NN.fit(x_train, y_train, epochs=30)\n",
715+
"\n",
716+
"# Call the uncertainty-aware model to generate outputs for the test data\n",
717+
"outputs = ensemble_NN(x_test)\n",
718+
"# Capsa makes the epistemic uncertainty an attribute of the prediction!\n",
719+
"epistemic_unc = outputs.epistemic\n",
720+
"\n",
721+
"# Visualize the epistemic uncertainty across the data space\n",
722+
"plt.scatter(x_test, epistemic, label='epistemic uncertainty', s=0.5)\n",
723+
"plt.legend()"
707724
]
708725
},
709726
{
@@ -749,22 +766,67 @@
749766
},
750767
{
751768
"cell_type": "markdown",
752-
"metadata": {
753-
"id": "VU6eMpYX9m9N"
754-
},
755769
"source": [
756-
"## Conclusion\n",
757-
"As expected, areas where there is no training data have very high epistemic uncertainty, since all of the testing data is OOD. If our training data contained more samples from this region, would you expect the epistemic uncertainty to decrease?"
758-
]
770+
"#### **TODO: Estimating epistemic uncertainty**\n",
771+
"\n",
772+
"Write short (~1 sentence) answers to the questions below to complete the `TODO`s:\n",
773+
"\n",
774+
"1. For what values of $x$ is the epistemic uncertainty high or increasing suddenly?\n",
775+
"2. How does your answer in (1) relate to how the $x$ values are distributed (refer back to original plot)? Think about both the train and test data.\n",
776+
"3. How could you reduce the epistemic uncertainty in regions where it is high?"
777+
],
778+
"metadata": {
779+
"id": "N4LMn2tLPBdg"
780+
}
759781
},
760782
{
761783
"cell_type": "markdown",
762784
"metadata": {
763785
"id": "CkpvkOL06jRd"
764786
},
765787
"source": [
788+
"# 1.6 Conclusion\n",
789+
"\n",
790+
"You've just analyzed the bias, aleatoric uncertainty, and epistemic uncertainty for your first risk-aware model! This is a task that data scientists do constantly to determine methods of improving their models and datasets.\n",
791+
"\n",
792+
"## NOTE TO ADDRESS: THIS CAN BE ELIMINATED COMPLETELY IF IT IS TOO MUCH FOR COMPETITION!\n",
793+
"### 1.6.1 Submission information\n",
794+
"To be eligible for the Debiasing Faces Lab prize, you must submit a document of your answers to the short-answer `TODO`s with your complete lab submission. **Name your file in the following format: `[FirstName]_[LastName]_Debiasing_Report.pdf`.**\n",
795+
"\n",
796+
"Upload your document write-up as part of your complete lab submission for the Debiasing Faces Lab ([submission upload link](https://www.dropbox.com/request/TTYz3Ikx5wIgOITmm5i2)).\n",
797+
"\n",
798+
"Please see the short-answer `TODO`s replicated again here:\n",
799+
"\n",
800+
"#### **TODO: Inspecting the 2D regression dataset**\n",
801+
"\n",
802+
"1. What are your observations about where the train data and test data lie relative to each other?\n",
803+
"2. What, if any, areas do you expect to have high/low aleatoric (data) uncertainty?\n",
804+
"3. What, if any, areas do you expect to have high/low epistemic (model) uncertainty?\n",
805+
"\n",
806+
"#### **TODO: Analyzing the performance of standard regression model**\n",
807+
"\n",
808+
"1. Where does the model perform well?\n",
809+
"2. Where does the model perform poorly?\n",
810+
"\n",
811+
"#### **TODO: Evaluating bias**\n",
812+
"\n",
813+
"1. How does the bias score relate to the train/test data density from the first plot?\n",
814+
"2. What is one limitation of the Histogram approach that simply bins the data based on frequency?\n",
815+
"\n",
816+
"#### **TODO: Estimating aleatoric uncertainty**\n",
817+
"\n",
818+
"1. For what values of $x$ is the aleatoric uncertainty high or increasing suddenly?\n",
819+
"2. How does your answer in (1) relate to how the $x$ values are distributed?\n",
820+
"\n",
821+
"#### **TODO: Estimating epistemic uncertainty**\n",
822+
"\n",
823+
"1. For what values of $x$ is the epistemic uncertainty high or increasing suddenly?\n",
824+
"2. How does your answer in (1) relate to how the $x$ values are distributed (refer back to original plot)? Think about both the train and test data.\n",
825+
"3. How could you reduce the epistemic uncertainty in regions where it is high?\n",
826+
"\n",
827+
"### 1.6.2 Moving forward\n",
766828
"\n",
767-
"You've just analyzed the bias, aleatoric uncertainty, and epistemic uncertainty for your first risk-aware model! This is a task that data scientists do constantly to determine methods of improving their models and datasets. In the next part, you'll continue to build off of these concepts to *mitigate* these risks, in addition to diagnosing them!\n",
829+
"In the next part of the lab, you'll continue to build off of these concepts to *mitigate* these risks, in addition to diagnosing them!\n",
768830
"\n",
769831
"![alt text](https://raw.githubusercontent.com/aamini/introtodeeplearning/2023/lab3/img/solutions_toy.png)"
770832
]

0 commit comments

Comments
 (0)