Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Open In Colab   Open in Kaggle

Tutorial 3: Statistical inference on representational geometries

Week 1, Day 3: Comparing Artificial And Biological Networks

By Neuromatch Academy

Content creators: Veronica Bossio, Eivinas Butkus, Jasper van den Bosch

Content reviewers: Samuele Bolotta, Yizhou Chen, RyeongKyung Yoon, Ruiyi Zhang, Lily Chamakura, Patrick Mineault, Hlib Solodzhuk, Alex Murphy

Production editors: Konstantine Tsafatinos, Ella Batty, Spiros Chavlis, Samuele Bolotta, Hlib Solodzhuk, Patrick Mineault, Alex Murphy


Tutorial Objectives

Estimated timing of tutorial: 50 minutes

To evaluate alternative models of measured data, we need statistical inference that takes our uncertainty about relative model performance into account. In computational neuroscience, we want to statistically compare different models in terms of their ability to account for representations in brains. In AI, we can employ similar techniques to compare models to each other and understand their internal representations.

By the end of this tutorial, you will be able to:

  1. Understand Representational Similarity Analysis (RSA), including its theoretical foundations, practical applications, and its significance in the context of machine learning and computational neuroscience.

  2. Extract neural network activations; understand the structure of neural networks, the role of activations in interpreting neural network decisions, and practical techniques for accessing these activations.

  3. Discuss frequentist model comparison: This part of the tutorial will cover the basics of frequentist model comparison methods. It will provide an overview of the principles underlying these methods and their applications.

  4. Identify sources of estimation error and the motivation for model-comparative frequentist inference. You will learn about the three main sources of estimation error in statistical inference—measurement noise, stimulus sampling, and subject sampling. Additionally, the tutorial will explore how these sources of error justify the use of model-comparative frequentist inference, particularly through the application of the 2-factor bootstrap method. This section will detail the impact of each source of error on statistical inference and demonstrate how the 2-factor bootstrap accounts for our uncertainty about model performance during model comparison.


Setup

Install and import feedback gadget

Source

Import dependencies

Figure settings

Source

Plotting functions

Source

Data retrieval

Source

Video 1: Tutorial Introduction

Youtube
Bilibili

Section 1: Data Acquisition

In this section, we are going to download and explore the data used in the tutorial.

We will load from the Natural Scene Dataset. NSD is a large 7T fMRI dataset of 8 adults viewing more than 73,000 photos of natural scenes. We have taken a small subset of 90 images from NSD and have pre-extracted the fMRI data for V1 and Fusiform Face Area (FFA) from 8 subjects. Both of these areas are part of the visual cortex; V1 is known to respond to low-level visual features, while the FFA is famously responsive to high-level features, in particular faces.

Define constants

Source

Show image

Source
<IPython.core.display.Image object>

Loading the images

First, let’s load the 90 image files with the Pillow Image class.

Load the images and get image size

Source
(425, 425, 3)

Now, let’s take a look at these images. Notice that the first 45 images we selected have no faces, while the other 45 do have faces in them! So, we should expect to see a 2x2 block pattern in the Fusiform Face Area (FFA) representational dissimilarity matrices (RDMs).

Visualize images

Source
<Figure size 1000x1000 with 90 Axes>

Loading fMRI patterns from the Natural Scenes Dataset

Let’s now load the fMRI patterns from NSD for these 90 images. We have pre-extracted the patterns, so we just need to load Numpy arrays from the .npy files.

Loading fMRI data

Source
(90, 2950)

Let’s now take a look at the pattern of responses for two non-face images and two face images.

<Figure size 800x400 with 1 Axes>

The activity is complex, but we clearly see several voxels (e.g., voxel 275) that have higher activation for faces than for non-faces. This is as expected for the face-selective FFA.


Section 2: Get artificial neural network activations

Estimated timing to here from start of tutorial: 15 minutes

Now that we have fMRI patterns, we want to explain this data using computational models.

In this tutorial, we will take our models to be layers of AlexNet.

Comparing LeNet architecture to AlexNet. Image from Dive Into Deep Learning book.

We load a version of AlexNet that is already pre-trained on ImageNet. This step may take a minute; feel free to read ahead.

Load AlexNet model pretrained on ImageNet

Source
Downloading: "https://download.pytorch.org/models/alexnet-owt-7be5be79.pth" to /home/runner/.cache/torch/hub/checkpoints/alexnet-owt-7be5be79.pth
  0%|          | 0.00/233M [00:00<?, ?B/s]
  1%|          | 2.18M/233M [00:00<00:10, 22.9MB/s]
  7%|▋         | 17.2M/233M [00:00<00:02, 102MB/s] 
 13%|█▎        | 31.4M/233M [00:00<00:01, 123MB/s]
 20%|█▉        | 46.4M/233M [00:00<00:01, 137MB/s]
 26%|██▌       | 60.9M/233M [00:00<00:01, 142MB/s]
 32%|███▏      | 75.5M/233M [00:00<00:01, 146MB/s]
 39%|███▊      | 90.1M/233M [00:00<00:01, 148MB/s]
 45%|████▍     | 104M/233M [00:00<00:00, 149MB/s] 
 51%|█████     | 119M/233M [00:00<00:00, 148MB/s]
 59%|█████▉    | 138M/233M [00:01<00:00, 166MB/s]
 69%|██████▊   | 160M/233M [00:01<00:00, 185MB/s]
 77%|███████▋  | 179M/233M [00:01<00:00, 190MB/s]
 87%|████████▋ | 203M/233M [00:01<00:00, 207MB/s]
 95%|█████████▌| 222M/233M [00:01<00:00, 204MB/s]
100%|██████████| 233M/233M [00:01<00:00, 167MB/s]

To pass images through the model, we need to preprocess them to be in the same format as the images shown to the model during training.

For AlexNet, this includes resizing the images to 224x224 and normalizing their color channels to particular values. We also need to turn them into PyTorch tensors.

Preprocess NSD images as input to AlexNet

Source
torch.Size([90, 3, 224, 224])

Let’s inspect AlexNet architecture to select some of the layers as our models.

Inspect architecture

Source
Architecture of AlexNet:
AlexNet(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(11, 11), stride=(4, 4), padding=(2, 2))
    (1): ReLU(inplace=True)
    (2): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)
    (3): Conv2d(64, 192, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (4): ReLU(inplace=True)
    (5): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)
    (6): Conv2d(192, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (7): ReLU(inplace=True)
    (8): Conv2d(384, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (9): ReLU(inplace=True)
    (10): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(6, 6))
  (classifier): Sequential(
    (0): Dropout(p=0.5, inplace=False)
    (1): Linear(in_features=9216, out_features=4096, bias=True)
    (2): ReLU(inplace=True)
    (3): Dropout(p=0.5, inplace=False)
    (4): Linear(in_features=4096, out_features=4096, bias=True)
    (5): ReLU(inplace=True)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)

Graph node names (layers) in the forward pass:
['x', 'features.0', 'features.1', 'features.2', 'features.3', 'features.4', 'features.5', 'features.6', 'features.7', 'features.8', 'features.9', 'features.10', 'features.11', 'features.12', 'avgpool', 'flatten', 'classifier.0', 'classifier.1', 'classifier.2', 'classifier.3', 'classifier.4', 'classifier.5', 'classifier.6']
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/site-packages/torch/overrides.py:110: UserWarning: 'has_cuda' is deprecated, please use 'torch.backends.cuda.is_built()'
  torch.has_cuda,
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/site-packages/torch/overrides.py:111: UserWarning: 'has_cudnn' is deprecated, please use 'torch.backends.cudnn.is_available()'
  torch.has_cudnn,
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/site-packages/torch/overrides.py:117: UserWarning: 'has_mps' is deprecated, please use 'torch.backends.mps.is_built()'
  torch.has_mps,
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/site-packages/torch/overrides.py:118: UserWarning: 'has_mkldnn' is deprecated, please use 'torch.backends.mkldnn.is_available()'
  torch.has_mkldnn,

We extract activations from different layers of AlexNet processing the same images that were presented to people during the NSD task.

Make hooks in AlexNet to extract activations from different layers

Source

Extract activations from AlexNet

Source
(90, 46656)

Section 3: Create representational dissimilarity matrices (RDMs)

Estimated timing to here from start of tutorial: 20 minutes

Now that we have fMRI patterns and AlexNet activations, the first step in representation similarity analysis (RSA) is to compute the representational dissimilarity matrices (RDMs). RSA characterizes the representational geometry of the brain region of interest (ROI) by estimating the representational distance for each pair of experimental conditions (e.g., different images).

RDMs represent how dissimilar neural activity patterns or model activations are for each stimulus. In our case, these will be 90x90 image-by-image matrices representing how dissimilar fMRI patterns or AlexNet layer activations are for each image.

For instance, we expect that in FFA, there will be a large distance between the 45 face and 45 non-face images: we expect to see a 2x2 block pattern inside the RDM.

Creating RSA toolbox datasets

First, let’s wrap our neural and model data in Dataset objects to use the RSA toolbox.

Create RSA datasets for each subject and ROI

Source

Create RSA datasets for AlexNet activations

Source

Computing the RDMs

Let’s compute RDMs for fMRI patterns and AlexNet activations.

Compute rdms for each subject and ROI

Source

Coding Exercise 1: RDMs of AlexNet

Use the RSA toolbox to compute the RDMs for the layers of AlexNet. It should be done in the very same way as RDMs for fMRI patterns above.

---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
Cell In[20], line 4
      1 #################################################
      2 ## TODO for students: fill in the missing variables ##
      3 # Fill out function and remove
----> 4 raise NotImplementedError("Student exercise: fill in the missing variables")
      5 #################################################
      6 
      7 # Compute rdms for each layer of AlexNet
      8 alexnet_rdms_dict = {}

NotImplementedError: Student exercise: fill in the missing variables

Visualizing human RDMs

Here we use methods on the rsatoolbox RDM object to select a subset of the RDMs.

Loading...

As predicted above, we can see a 2x2 block-like pattern in the FFA fMRI pattern RDMs.

This is because we have 45 non-face images followed by 45 face images.

The lighter regions indicate larger representational distances.

<Figure size 600x600 with 9 Axes>

Coding Exercise 2: Human RDMs

Visualize the RDMs for the fMRI patterns from the V1 region.

---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
Cell In[24], line 4
      1 #################################################
      2 ## TODO for students: fill in the missing variables ##
      3 # Fill out function and remove
----> 4 raise NotImplementedError("Student exercise: fill in the missing variables")
      5 #################################################
      6 v1_rdms = fmri_rdms.subset('roi', ...)

NotImplementedError: Student exercise: fill in the missing variables

Visualizing AlexNet RDMs

Let’s look at RDMs for different layers of AlexNet.

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[25], line 1
----> 1 alexnet_rdms = rsa.rdm.concat(alexnet_rdms_dict.values())
      2 fig = rsa.vis.rdm_plot.show_rdm(alexnet_rdms, rdm_descriptor='layer')[0]

NameError: name 'alexnet_rdms_dict' is not defined

Each RDM contains the dissimilarities for each pair of activation patterns extracted by the different layers.

We see a similar pattern emerge, clustering face and non-face images in fully connected fc6, fc7, and fc8 layers.

AlexNet seems to represent faces differently than non-faces, at least to some extent.

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[26], line 2
      1 # same RDMs, different visualization method
----> 2 show_rdm_plotly(alexnet_rdms, rdm_descriptor='layer')

NameError: name 'alexnet_rdms' is not defined

Section 4: RSA. Model comparison and statistical inference

Estimated timing to here from start of tutorial: 35 minutes

In the second step of RSA, each model is evaluated by the accuracy of its prediction of the data RDM. To this end, we will use the RDMs we computed for each model representation.

Each model’s prediction of the data RDM is evaluated using an RDM comparator. In this case, we will use the correlation coefficient.

First, let’s look at the performance of different Alexnet layers across all subjects.

Get the Model objects to use the rsa toolbox for model comparisons

Source
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[27], line 2
      1 # @title Get the Model objects to use the rsa toolbox for model comparisons
----> 2 for layer, rdm in alexnet_rdms_dict.items():
      3     if layer == "conv1":
      4         models = [rsa.model.ModelFixed(rdm=rdm, name=layer)]

NameError: name 'alexnet_rdms_dict' is not defined

Visualize AlexNet performance

Source
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[28], line 5
      3 roi = 'FFA'
      4 human_rdms = fmri_rdms.subset('roi', roi)
----> 5 models_to_compare = models
      7 method = 'corr'
      8 result =  rsa.inference.evaluate.eval_fixed(models_to_compare, human_rdms, method=method) # get the performance of the models compared to the fMRI data of the first 3 subjects for the FFA ROI

NameError: name 'models' is not defined

In the plot, each data point represents the representational dissimilarity matrix (RDM) for an individual subject. The Y-axis indicates the correlation distance of the data RDMs to the RDM obtained from representations from each model layer. Each bar shows the mean correlation distance between data RDMs (across subjects) and one model layer. The observed variability reflects the extent to which our models (layers) accurately predict neural activity patterns across different individuals.

Our goal is to determine how these results might generalize to a new cohort of subjects and new sets of stimuli (assuming the new subjects and stimuli are sampled from the same respective populations). Since we cannot practically rerun the experiment countless times with fresh subjects and stimuli, we turn to computational simulations.

To achieve this, we will employ bootstrap resampling—a statistical technique that involves resampling our existing dataset with replacement to generate multiple simulated samples. This approach allows us to mimic the process of conducting the experiment anew with different subjects and/or different stimuli.

First, we’ll focus on generalization to new subjects. By bootstrapping the subject dataset for each simulated sample, we can compute the predictive accuracy of our models on the subjects’ RDMs. After running many simulations, we will accumulate a distribution of mean accuracy estimates that simulates the distribution of mean accuracies we might have obtained if we had actually repeated the experiment many times. This distribution will enable us to perform statistical inferences about our models’ generalizability to new subjects. Later, we will address the problem of generalizing to new stimuli as well.

Let’s simulate a new sample of subjects by bootstrap resampling using the RSA toolbox.

Now, we plot the RDMs of the bootstrapped sample.

Each RDM is a subject (note that some subjects might be repeated and some might be missing in the bootstrapped sample).

Visualize RDMs

Source
Loading...
Loading...

As before, each RDM contains the pairwise dissimilarities between activation patterns in the specified brain region (in this case, FFA) for each of the subjects.

The first row shows the RDMs for each of the original 8 subjects. The second row shows 8 RDMs sampled from the set of 8 original RDMs with replacement. This is bootstrap resampling. It can be seen as a simulation of a “new” set of 8 subjects’ RDMs. Notice that in this new set not all subjects are represented and some others might appear more than once.

The idea is to see how the results for the model evaluations would change had our data come from this simulated sample of subjects.

Let’s see the model performance on different bootstrap resampled subject sets.

Visualize model evaluations

Source
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[31], line 4
      1 # @title Visualize model evaluations
      3 boot_rdms, idx = rsa.inference.bootstrap_sample_rdm(human_rdms, rdm_descriptor='subject')
----> 4 eval_result = rsa.inference.evaluate.eval_fixed(models_to_compare, boot_rdms, method=method)
      5 fig = plot_bars_and_scatter_with_table(eval_result, models, method, color='blue', table = False)
      6 fig.show()

NameError: name 'models_to_compare' is not defined

If you run the cell above again, you will see the model performance for a new bootstrap sample of subjects.

Discussion

  1. Explore the results for a few simulated new cohorts: run the cell above a few times and see how to points (individual RDMs) and bars (means) change.

Hint: For different simulated sets of subjects, the mean correlation of their RDMs to the RDMs given by each layer may look quite different. For example, if a given subject’s RDM correlates very closely with layer conv4, and that subject is overrepresented in the bootstrap sample, the layer conv4 might yield a higher accuracy compared to the other layers.

Comparing representations statistically

How can we know if these differences in model performance are statistically significant?

That is what the third and final step of RSA does: we conduct inferential comparisons between models based on their accuracy in predicting the representational dissimilarity matrices (RDMs).

We leverage the variability in the performance estimates observed in the bootstrapped samples to conduct statistical tests. These tests are designed to determine whether the differences in RDM prediction accuracy between models are statistically significant.

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[32], line 1
----> 1 plot_model_comparison_trans(result)

NameError: name 'result' is not defined

The Y-axis, again, shows RDM prediction accuracy, as measured by the correlation between the data RDMs and the model RDMs. The error bars reflect the variability in this estimate across bootstrap samples over subjects). The gray bar indicates the noise ceiling, which is a measure of how well the best possible model (capturing the true data-generating process) could do, given the noise and intersubject variability in the data. The gray arrows indicate the models that don’t perform significantly better than the noise-ceiling. The white dots at the bottom of the bars indicate the models whose correlation distance to the data RDMs is significantly better than zero.

Details of the figure above

Model comparisons are performed using a two-tailed t-test, FDR q < 0.01. Error bars indicate the standard error of the mean. One-sided comparisons of each model’s performance against 0 and against the lower-bound estimate of the noise ceiling are Bonferroni-corrected for the number of models.

Generalization to new images

We have applied a method that enables us to infer how well the models might perform when predicting neural activity patterns for a new cohort of subjects. However, this approach has not yet considered the variability that would arise when replicating the experiment with a new sample of stimuli.

To make statistical inferences expected to generalize to new stimuli, we will once again use a bootstrapping procedure, focusing this time on the stimuli rather than the subjects.

To do this, we will first maintain the original cohort of subjects and apply bootstrapping to resample the stimulus set. That is, for each subject, we will sample a new RDM based on the RDM from that subject’s original activation patterns. The RDM will contain the pairwise dissimilarities between the response patterns to a set of stimuli sampled with replacement from the original set of stimuli.

Get the RDMs for a bootstrap sample of the images

Source
Loading...

As before, rerunning the cell above will show you the RDMs for a new set of bootstrap-resampled stimuli each time.

Note that the block-like structure from before is generally preserved. This is because the stimuli are sorted so that the face stimuli are still adjacent to other face stimuli, and non-face stimuli are adjacent to other non-face stimuli. What changes are the specific stimuli used when computing the RDM. For each bootstrap resample, some stimuli might appear more than once, and some might be left out.

Let’s see the inferential model comparisons based on 1000 bootstraps of the image set.

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[34], line 1
----> 1 result = rsa.inference.eval_bootstrap_pattern(models, human_rdms, theta=None, method='corr', N=1000,
      2                            pattern_descriptor='index', rdm_descriptor='index',
      3                            boot_noise_ceil=True)
      5 plot_model_comparison_trans(result)

NameError: name 'models' is not defined

The Y-axis shows RDM prediction accuracy, as measured by the correlation distance between the data RDMs and the model RDMs. The error bars reflect the variability in this estimate across bootstrap samples (over stimuli). The gray bar indicates the noise ceiling, which is a measure of how well any model could do, given the noise in the data. The gray arrows indicate the models that don’t perform significantly better than the noise-ceiling. The white dots at the bottom of the bars indicate the models whose correlation distance to the data RDMs is significantly better than zero.

Details of the figure above

Model comparisons: two-tailed t-test, FDR q < 0.01. Error bars indicate the standard error of the mean. One-sided comparisons of each model’s performance against 0 and against the lower-bound estimate of the noise ceiling are Bonferroni-corrected for the number of models.


Section 5: Model Comparison Using Two-factor Bootstrap

Estimated timing to here from start of tutorial: 45 minutes

For generalization across both the subject and stimulus populations, we can use a two-factor bootstrap method. For an in-depth discussion of this technique, refer to Schütt et al., 2023.

We can use the RSA toolbox to implement bootstrap resampling of subjects and stimuli simultaneously. It is important to note that a naive 2-factor bootstrap approach triple-counts the variance contributed by the measurement noise. For further understanding of this issue, see the explanation provided by Schütt et al. Fortunately, the RSA toolbox has an implementation that corrects this potential overestimation.

Let’s evaluate the performance of the models with simultaneous bootstrap resampling of the subjects and stimuli.

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[35], line 1
----> 1 eval_result = rsa.inference.eval_dual_bootstrap(models, fmri_rdms.subset('roi', 'FFA'), method='corr')
      2 print(eval_result)

NameError: name 'models' is not defined
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[36], line 1
----> 1 plot_model_comparison_trans(eval_result)

NameError: name 'eval_result' is not defined

In the plot above, the statistical comparison results take into account the variability in the data that comes from considering different sets of subjects and sets of stimuli.


Summary

Estimated timing of tutorial: 50 minutes

In this tutorial, we:

  1. Reviewed the principles of RSA in the context of machine learning and computational neuroscience and applied it to the problem of comparing representations between fMRI patterns and neural network models for a vision task.

  2. Explored the structure of AlexNet and extracted activations from the different layers of this neural network to a set of visual stimuli.

  3. Evaluated how well the different layers of AlexNet could explain neural responses from humans to the same stimuli, by comparing the representations extracted from these layers (which we treated as different models) to the activity patterns derived from fMRI data.

  4. Used frequentist statistical inference to compare the performance of the different model representations (i.e. layers).

  5. Addressed two sources of model-performance estimation error that statistical inference must account for in addition to the error due to measurement noise: stimulus sampling and subject sampling, using the 2-factor bootstrap method.

The Big Picture

Generalization can arise across multiple dimensions, whether that be generalization of an experiment to a new set of subjects or whether a new set of stimuli generalize to the same subjects. More likely, we would want to know how much an experiment would generalize to novel subjects across novel stimuli. We can test these ideas statistically by using the bootstrap method in statistics. This notebook highlights some issues with naive approaches to statistics when assessing generalization in this way. We explored the 2-factor bootstrap method and used a toolbox that explicitly takes care of the calculation so that we don’t overestimate the variance involved. It’s important to be aware of factors of generalization and how multiple overlapping factors might interact.