{ "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 }