File size: 16,112 Bytes
0b416c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lab 3 – Connecting Language to fMRI Reads\n",
"## Part 1: Generate Embeddings\n",
"\n",
"**Goal:** Convert raw podcast transcripts into numerical feature matrices (X) that can be used to predict BOLD voxel responses (Y) via ridge regression."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sys, os\n",
"import numpy as np\n",
"import pickle\n",
"\n",
"# Make sure code/ is on the path\n",
"sys.path.insert(0, os.path.abspath('.'))\n",
"sys.path.insert(0, os.path.abspath('./ridge_utils'))\n",
"\n",
"from preprocessing import downsample_word_vectors, make_delayed\n",
"from ridge_utils.stimulus_utils import load_textgrids, load_simulated_trfiles\n",
"from ridge_utils.dsutils import make_word_ds"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 0. Load Data and Build WordSeqs\n",
"\n",
"Data lives at `/ocean/projects/mth250011p/shared/215a/final_project/data` on Bridges2. \n",
"Locally, point `DATA_DIR` to wherever you have downloaded the dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"DATA_DIR = '../data/raw' # adjust as needed\n",
"EMBED_DIR = '../data/embeddings'\n",
"os.makedirs(EMBED_DIR, exist_ok=True)\n",
"\n",
"# ── Subject / story split ────────────────────────────────────────────────────\n",
"SUBJECTS = ['s1', 's2']\n",
"\n",
"# Example story names – replace with the actual story IDs in your dataset\n",
"ALL_STORIES = ['alternateithicatom', 'wheretheressmoke', 'odetostepfather',\n",
" 'souls', 'avatar', 'howtodraw', 'legacy', 'undertheinfluence',\n",
" 'inamoment', 'tildeath', 'theclosetthatateeverything',\n",
" 'gentlemensagreement', 'naked']\n",
"TRAIN_STORIES = ALL_STORIES[:-2] # all but last two\n",
"TEST_STORIES = ALL_STORIES[-2:] # last two held out\n",
"\n",
"print(f'Train stories ({len(TRAIN_STORIES)}): {TRAIN_STORIES}')\n",
"print(f'Test stories ({len(TEST_STORIES)}): {TEST_STORIES}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load TextGrid transcripts and simulated TR files\n",
"# (skip this block and load a cached wordseqs.pkl if already computed)\n",
"\n",
"grids = load_textgrids(ALL_STORIES, DATA_DIR)\n",
"\n",
"# Load or simulate TR files – here we use the BOLD response shape per story\n",
"# respdict = {story: num_TRs} – fill from your actual response arrays\n",
"# respdict = pickle.load(open(f'{DATA_DIR}/respdict.pkl', 'rb'))\n",
"# trfiles = load_simulated_trfiles(respdict)\n",
"\n",
"# Build word DataSequences\n",
"# wordseqs = make_word_ds(grids, trfiles) # {story: DataSequence}\n",
"# pickle.dump(wordseqs, open(f'{DATA_DIR}/wordseqs.pkl', 'wb'))\n",
"\n",
"wordseqs = pickle.load(open(f'{DATA_DIR}/wordseqs.pkl', 'rb'))\n",
"print('Loaded wordseqs for stories:', list(wordseqs.keys()))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 1. Bag-of-Words Embeddings\n",
"\n",
"### Step 1a – Generate BoW vectors\n",
"\n",
"A **bag-of-words** (BoW) model represents each word token as a one-hot or count vector over the vocabulary $V$. \n",
"For a story with $N$ word tokens, this produces a matrix of shape $(N, |V|)$.\n",
"\n",
"**Dimension mismatch:** The fMRI response matrix $Y$ has shape $(T', V_{\\text{oxels}})$, where $T'$ is the number of TR measurements (one per ~2 s). \n",
"The word matrix has $N \\gg T'$ rows because many words fall within each TR. \n",
"We must *downsample* the word-rate signal to the TR rate."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.feature_extraction.text import CountVectorizer\n",
"\n",
"# Fit a shared vocabulary across all stories\n",
"all_docs = [' '.join(wordseqs[s].data) for s in ALL_STORIES]\n",
"vectorizer = CountVectorizer(binary=False)\n",
"vectorizer.fit(all_docs)\n",
"print(f'Vocabulary size: {len(vectorizer.vocabulary_):,}')\n",
"\n",
"# One row per word token per story\n",
"bow_word_vecs = {}\n",
"for story in ALL_STORIES:\n",
" tokens = wordseqs[story].data\n",
" mat = vectorizer.transform(tokens).toarray().astype(np.float32)\n",
" bow_word_vecs[story] = mat\n",
" print(f' {story}: word matrix shape = {mat.shape}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 1b – Downsample to TR rate\n",
"\n",
"**What `downsample_word_vectors` does:** \n",
"It applies a **Lanczos (sinc-based) interpolation** filter (`lanczosinterp2D`) that resamples the high-rate word sequence (one row per word, irregularly spaced in time) onto the regular TR time grid. \n",
"Each TR-rate sample is a weighted average of nearby word vectors, where the weights come from a windowed sinc kernel. \n",
"This is analogous to low-pass filtering + resampling in signal processing – it avoids aliasing artifacts that would arise from naive nearest-neighbour downsampling.\n",
"\n",
"After this step the feature matrix has shape $(T', |V|)$, matching the fMRI response.\n",
"\n",
"**Trimming:** The first 5 s and last 10 s are discarded because the hemodynamic response takes ~5–6 s to ramp up and the stimulus presentation may leave residual signal at the end."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"TRIM_START = 5 # seconds (≈ TRs if TR ≈ 1 s; scale appropriately)\n",
"TRIM_END = 10\n",
"\n",
"# Downsample word vectors → TR-rate\n",
"bow_ds = downsample_word_vectors(ALL_STORIES, bow_word_vecs, wordseqs)\n",
"\n",
"for story in ALL_STORIES:\n",
" mat = bow_ds[story]\n",
" print(f' {story}: downsampled shape = {mat.shape}')\n",
" # Trim\n",
" bow_ds[story] = mat[TRIM_START: len(mat) - TRIM_END]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Step 1c – Add temporal lags with `make_delayed`\n",
"\n",
"**What `make_delayed` does:** \n",
"The BOLD signal has a **hemodynamic response function (HRF)** delay of roughly 4–8 s. \n",
"To capture this, we create lagged copies of the feature matrix: at delay $d$, row $t$ of the lagged matrix contains the features from time $t - d$. \n",
"Using delays $[1, 2, 3, 4]$ TRs (≈ 2–8 s) lets the linear model implicitly learn the shape of the HRF for each voxel.\n",
"\n",
"The output is a horizontally stacked matrix of shape $(T', 4 \\times |V|)$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"DELAYS = [1, 2, 3, 4] # TR-unit delays\n",
"\n",
"bow_lagged = {}\n",
"for story in ALL_STORIES:\n",
" bow_lagged[story] = make_delayed(bow_ds[story], DELAYS)\n",
" print(f' {story}: lagged shape = {bow_lagged[story].shape}')\n",
"\n",
"# Stack into train / test matrices\n",
"X_train_bow = np.vstack([bow_lagged[s] for s in TRAIN_STORIES])\n",
"X_test_bow = np.vstack([bow_lagged[s] for s in TEST_STORIES])\n",
"print(f'\\nBoW X_train: {X_train_bow.shape}, X_test: {X_test_bow.shape}')\n",
"\n",
"# Save\n",
"for subj in SUBJECTS:\n",
" np.save(f'{EMBED_DIR}/{subj}_train_bow_embeddings.npy', X_train_bow)\n",
" np.save(f'{EMBED_DIR}/{subj}_test_bow_embeddings.npy', X_test_bow)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 2. Word2Vec Embeddings\n",
"\n",
"**Pre-trained model:** Google News Word2Vec (300-d, 3M words) \n",
"Download: `GoogleNews-vectors-negative300.bin.gz` and place at `data/raw/`.\n",
"\n",
"Each word is replaced by its 300-d dense vector. \n",
"OOV words receive a zero vector. \n",
"The same downsample → trim → lag pipeline is then applied."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from gensim.models import KeyedVectors\n",
"\n",
"W2V_PATH = '../data/raw/GoogleNews-vectors-negative300.bin'\n",
"w2v_model = KeyedVectors.load_word2vec_format(W2V_PATH, binary=True)\n",
"print(f'Word2Vec loaded: {len(w2v_model):,} words, dim={w2v_model.vector_size}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"DIM_W2V = w2v_model.vector_size\n",
"\n",
"w2v_word_vecs = {}\n",
"for story in ALL_STORIES:\n",
" tokens = wordseqs[story].data\n",
" mat = np.array([\n",
" w2v_model[w.lower()] if w.lower() in w2v_model else np.zeros(DIM_W2V)\n",
" for w in tokens\n",
" ], dtype=np.float32)\n",
" w2v_word_vecs[story] = mat\n",
"\n",
"# Downsample → trim → lag\n",
"w2v_ds = downsample_word_vectors(ALL_STORIES, w2v_word_vecs, wordseqs)\n",
"w2v_lagged = {}\n",
"for story in ALL_STORIES:\n",
" trimmed = w2v_ds[story][TRIM_START: len(w2v_ds[story]) - TRIM_END]\n",
" w2v_lagged[story] = make_delayed(trimmed, DELAYS)\n",
"\n",
"X_train_w2v = np.vstack([w2v_lagged[s] for s in TRAIN_STORIES])\n",
"X_test_w2v = np.vstack([w2v_lagged[s] for s in TEST_STORIES])\n",
"print(f'Word2Vec X_train: {X_train_w2v.shape}, X_test: {X_test_w2v.shape}')\n",
"\n",
"for subj in SUBJECTS:\n",
" np.save(f'{EMBED_DIR}/{subj}_train_word2vec_embeddings.npy', X_train_w2v)\n",
" np.save(f'{EMBED_DIR}/{subj}_test_word2vec_embeddings.npy', X_test_w2v)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 3. GloVe Embeddings\n",
"\n",
"**Pre-trained model:** GloVe 840B Common Crawl (300-d) \n",
"Download: `glove.840B.300d.zip` from Stanford NLP and place the `.txt` file at `data/raw/`. \n",
"A smaller alternative: `glove.6B.100d.txt` (100-d, ~175 MB).\n",
"\n",
"Same pipeline as Word2Vec."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"GLOVE_PATH = '../data/raw/glove.840B.300d.txt'\n",
"DIM_GLOVE = 300\n",
"\n",
"# Load GloVe into a plain dict\n",
"glove = {}\n",
"with open(GLOVE_PATH, 'r', encoding='utf-8') as f:\n",
" for line in f:\n",
" parts = line.rstrip().split(' ')\n",
" glove[parts[0]] = np.array(parts[1:], dtype=np.float32)\n",
"print(f'GloVe loaded: {len(glove):,} words, dim={DIM_GLOVE}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"glove_word_vecs = {}\n",
"for story in ALL_STORIES:\n",
" tokens = wordseqs[story].data\n",
" mat = np.array([\n",
" glove.get(w.lower(), np.zeros(DIM_GLOVE))\n",
" for w in tokens\n",
" ], dtype=np.float32)\n",
" glove_word_vecs[story] = mat\n",
"\n",
"# Downsample → trim → lag\n",
"glove_ds = downsample_word_vectors(ALL_STORIES, glove_word_vecs, wordseqs)\n",
"glove_lagged = {}\n",
"for story in ALL_STORIES:\n",
" trimmed = glove_ds[story][TRIM_START: len(glove_ds[story]) - TRIM_END]\n",
" glove_lagged[story] = make_delayed(trimmed, DELAYS)\n",
"\n",
"X_train_glove = np.vstack([glove_lagged[s] for s in TRAIN_STORIES])\n",
"X_test_glove = np.vstack([glove_lagged[s] for s in TEST_STORIES])\n",
"print(f'GloVe X_train: {X_train_glove.shape}, X_test: {X_test_glove.shape}')\n",
"\n",
"for subj in SUBJECTS:\n",
" np.save(f'{EMBED_DIR}/{subj}_train_glove_embeddings.npy', X_train_glove)\n",
" np.save(f'{EMBED_DIR}/{subj}_test_glove_embeddings.npy', X_test_glove)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## Discussion\n",
"\n",
"### Q1 – What does downsampling (Lanczos interpolation) do?\n",
"\n",
"The raw transcript gives one embedding vector per *word token*, at the time the word was spoken. \n",
"Words arrive at ~2–4 per second, whereas fMRI samples the brain every ~2 s (one TR). \n",
"To build a feature matrix whose rows align with BOLD measurements we must convert from the word-rate timeline to the TR-rate timeline.\n",
"\n",
"`downsample_word_vectors` calls `lanczosinterp2D`, which builds a **sinc convolution matrix**: for each TR time point $t_k$ it computes a weighted combination of word vectors whose timestamps $\\tau_i$ are near $t_k$, with weights given by the Lanczos kernel $L(\\tau_i - t_k)$. \n",
"This is equivalent to low-pass filtering then resampling, and it preserves the spectral content below the Nyquist frequency of the TR grid while suppressing high-frequency aliasing.\n",
"\n",
"Result: the feature matrix changes from shape $(N_{\\text{words}}, d)$ → $(T', d)$, where $T'$ matches the number of BOLD measurements.\n",
"\n",
"---\n",
"\n",
"### Q2 – What does `make_delayed` do and why is it useful?\n",
"\n",
"The blood-oxygen-level-dependent (BOLD) signal is a *delayed and smoothed* reflection of neural activity – the hemodynamic response function (HRF) peaks ~5–6 s after a neural event. \n",
"A feature matrix at the stimulus time therefore does not align with the measured BOLD response; there is a lag of several TRs.\n",
"\n",
"`make_delayed(stim, delays=[1,2,3,4])` concatenates four shifted copies of the feature matrix horizontally: \n",
"- delay 1: row $t$ gets features from time $t-1$ \n",
"- delay 2: row $t$ gets features from time $t-2$ \n",
"- … \n",
"\n",
"The resulting matrix has shape $(T', 4d)$. \n",
"The downstream ridge model can then learn a different weight for each delay, effectively fitting a finite-impulse-response (FIR) approximation to the HRF for each voxel. \n",
"This is important because the HRF varies across brain regions, and the model needs flexibility to discover the correct delay profile.\n",
"\n",
"---\n",
"\n",
"### Q3 – Benefits of pre-trained embeddings (Word2Vec, GloVe) over BoW\n",
"\n",
"| Property | Bag-of-Words | Word2Vec / GloVe |\n",
"|---|---|---|\n",
"| Dimensionality | $|V|$ (thousands, sparse) | 100–300 (dense) |\n",
"| Captures synonymy | No | Yes – similar words have similar vectors |\n",
"| Captures analogy / syntax | No | Partially (e.g. king−man+woman≈queen) |\n",
"| Training data | Only current corpus | Billions of tokens (News / Common Crawl) |\n",
"| OOV handling | Zero / unknown | Zero vector (but rare for large vocab) |\n",
"\n",
"Pre-trained embeddings encode **semantic and syntactic similarity** that BoW cannot capture. \n",
"In the fMRI context, brain areas that process *meaning* (e.g. the temporal cortex) are more likely to be predicted by embeddings that cluster semantically related words together. \n",
"Furthermore, dense low-dimensional embeddings reduce the number of parameters the ridge model must estimate, which is critical given the limited number of TR samples relative to voxel count."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.10.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|