File size: 5,519 Bytes
6d91986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1c0645
6d91986
a1c0645
6d91986
a1c0645
 
 
 
 
 
 
 
 
 
6d91986
a1c0645
 
6d91986
a1c0645
6d91986
a1c0645
 
 
 
 
6d91986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
pretty_name: IMDb Sentiment Analysis - DistilBERT Feature Cache
dataset_info:
  features:
  - name: train_feat
    dtype: float16
    shape: [25000, 128, 768]
  - name: test_feat
    dtype: float16
    shape: [25000, 128, 768]
  - name: train_mask
    dtype: bool
    shape: [25000, 128]
  - name: test_mask
    dtype: bool
    shape: [25000, 128]
configs:
- config_name: default
  data_files:
  - split: train
    path: train_feat.npy
  - split: test
    path: test_feat.npy
tags:
- sentiment-analysis
- movie-reviews
- embeddings
- features
- distilbert
- rnn
- py-torch
---

# IMDb Movie Reviews - DistilBERT Contextual Embedding Cache

This dataset contains pre-extracted contextual embedding features of the standard **IMDb Movie Reviews dataset (Sentiment Analysis)**. The features were extracted using a frozen **DistilBERT** (`distilbert-base-uncased`) encoder.

By caching these high-dimensional embeddings, you can train downstream classifiers (like LSTMs, GRUs, Attention heads, or custom Transformers) **in seconds** on a local GPU or CPU, bypassing the massive computation overhead of running transformer inference on every epoch.

## 📊 Dataset Specification

All features are saved as memory-mapped Numpy binary files (`.npy`), allowing them to be loaded on consumer hardware with low memory footprint via `np.memmap`.

| File | Shape | Dtype | Size on Disk | Description |
|---|---|---|---|---|
| **`train_feat.npy`** | `(25000, 128, 768)` | `float16` | 4.58 GB | Frozen DistilBERT last-hidden-state embeddings for the IMDb Train Split |
| **`train_mask.npy`** | `(25000, 128)` | `bool` | 3.05 MB | Attention mask for the training split |
| **`test_feat.npy`** | `(25000, 128, 768)` | `float16` | 4.58 GB | Frozen DistilBERT last-hidden-state embeddings for the IMDb Test Split |
| **`test_mask.npy`** | `(25000, 128)` | `bool` | 3.05 MB | Attention mask for the test split |

### Extraction Details
- **Base Model**: `distilbert-base-uncased` (frozen, Hugging Face transformers)
- **Tokenization**: Contextual embeddings extracted from the **last hidden state** (768 dimensions).
- **Sequence Length (`max_len`)**: 128 tokens (truncated/padded).
- **Precision**: `float16` (RAM-safe memmap layout).

---

## 🏆 Project Benchmarks & Leaderboard

This project involved an iterative design of multiple classification models. Below is the complete leaderboard of all runs, showing that the overall project reached a peak performance of **91.42% Accuracy** (SOTA-level for custom LSTMs):

| Version | Model Architecture | Key Techniques | Trainable Params | Best Test Accuracy | Best Test F1 |
|---|---|---|---|---|---|
| **v16** | 3-Layer LSTM (Pretrained) | **ULMFiT-style LM Pretraining (50K Unsupervised) + Gradual Unfreeze** | 8.4M | **91.42%** | **91.58%** |
| **v18** | Bidirectional LM (Pretrained) | Forward+Backward LM pretrain + combined classifier + FGM | - | **91.15%** | - |
| **v9** | 3-Layer BiLSTM + Attn | Vocab=20K, embed=128, hidden=256, max_len=300 | 12.5M | **90.13%** | - |
| **v13** | AWD-LSTM + Multi-Head Attn | Variational Dropout + Recurrent Weight Dropout | 12.5M | **90.12%** | 90.19% |
| **v15** | BiLSTM + MHA + Concat Pool | Adversarial Training (FGM, epsilon=0.5) | 6.2M | **90.12%** | 90.18% |
| **v17** | **DistilBERT (Frozen) + BiLSTM** | **Contextual Feature Extractor (This Cache)** | 4.7M | **86.86%** | **86.99%** |
| **v5** | BiLSTM + Attention | Single-layer LSTM + Dot-product Attention | 1.3M | **88.38%** | - |
| **v2** | BiLSTM + Grad Clip | Bidirectional + Gradient clipping max_norm=1.0 | 1.3M | **81.39%** | 79.86% |

### Why v17 (BERT Feature Cache) achieved 86.86%
The feature cache provided here (v17) uses a **completely frozen** DistilBERT encoder. Because the weights of the DistilBERT model are not fine-tuned on the IMDb reviews (to save GPU memory and prevent overfitting during training), it acts as a general feature extractor. Combined with a BiLSTM + Multi-Head Attention classifier head, it reaches a solid **86.86% Accuracy** in less than 45 seconds of training per epoch. 

To reach **91%+**, language model pre-training (such as in **v16** and **v18**) on the 50,000 unsupervised IMDb reviews, or fully fine-tuning the transformer layers, is required.

---

## 📈 v17 Classifier Training Curves & Confusion Matrix

#### 📊 Training Curves
![Training Curves](v17_training_curves.png)

#### 🎯 Confusion Matrix
![Confusion Matrix](v17_confusion_matrix.png)

---

## 🛠️ Usage Example

You can load these files directly into PyTorch Dataset using memory mapping, which reads pages dynamically from disk without loading the entire 9.2 GB into RAM:

```python
import numpy as np
import torch
from torch.utils.data import Dataset

class IMDbFeatureDataset(Dataset):
    def __init__(self, feat_path, mask_path, labels, seq_len=128, bert_dim=768):
        self.labels = labels
        self.n = len(labels)
        # Load as memory-mapped array (RAM-safe)
        self.features = np.memmap(feat_path, dtype=np.float16, mode='r',
                                  shape=(self.n, seq_len, bert_dim))
        self.masks = np.memmap(mask_path, dtype=np.bool_, mode='r',
                               shape=(self.n, seq_len))

    def __len__(self):
        return self.n

    def __getitem__(self, idx):
        x = torch.from_numpy(self.features[idx].astype(np.float32)) # Convert to fp32
        mask = torch.from_numpy(self.masks[idx])
        y = torch.tensor(self.labels[idx], dtype=torch.float32)
        return x, mask, y
```