Metadata-Version: 2.4
Name: uncnn
Version: 1.0.0
Summary: An untrained (frozen, random-weight) 3D CNN feature extractor for structural brain MRI.
Author: epics-lab
License-Expression: MIT
Project-URL: Homepage, https://github.com/epics-lab/untrained-cnn
Project-URL: Repository, https://github.com/epics-lab/untrained-cnn
Project-URL: Paper, https://doi.org/10.64898/2026.06.07.730652
Project-URL: Hugging Face, https://huggingface.co/epics-lab/untrained-cnn
Keywords: mri,neuroimaging,untrained-cnn,feature-extraction,brain
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Topic :: Scientific/Engineering :: Image Processing
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: nibabel
Requires-Dist: torch
Dynamic: license-file

[![Models](https://img.shields.io/badge/Hugging%20Face-un--CNN-FFD21E?style=flat-square&logo=huggingface&logoColor=black)](https://huggingface.co/epics-lab/untrained-cnn)
[![Paper](https://img.shields.io/badge/bioRxiv-2026.06.07.730652-B31B1B?style=flat-square)](https://www.biorxiv.org/content/10.64898/2026.06.07.730652v1)
[![License](https://img.shields.io/badge/License-MIT-0A7BBB?style=flat-square)](LICENSE)
[![Python](https://img.shields.io/badge/Python-3.8%2B-3776AB?style=flat-square&logo=python&logoColor=white)](pyproject.toml)

# untrained-cnn

This repository provides an implementation of **un-CNN**, an untrained 3D convolutional neural network used as a fixed feature extractor for structural brain MRI.

The model is **never trained**. Its weights are initialized once with a fixed random seed and kept frozen. Brain MRI volumes are passed through the untrained CNN to obtain subject-level feature vectors for any downstream model. In the paper, the features are evaluated with linear heads: ridge regression for age and BMI, logistic regression for sex.

## Installation

```bash
pip install git+https://github.com/epics-lab/untrained-cnn.git
```

This installs the `uncnn` module along with its dependencies (numpy, scipy, nibabel, torch). No cloning required.

## Usage

```python
import uncnn

# one scan
feats = uncnn.extract_features("subject01.nii.gz")          # -> shape (1, 9664)

# many scans
import glob
feats = uncnn.extract_features(glob.glob("data/*.nii.gz"))  # -> shape (N, 9664)
```

Inputs are any NIfTI volume (`.nii` / `.nii.gz`); each is resized to the MNI152 2mm grid (91x109x91) and converted to a 3-channel image automatically. The output is a NumPy array with one feature row per subject — feed it to whatever downstream model you like (e.g. ridge regression).

### Options

```python
uncnn.extract_features(paths,
                       config="robust",   # "robust" (default) or "ranksobel"
                       batch_size=8,       # default
                       device=None,        # "cpu" or "cuda"; auto-detected if omitted
                       seed=0)             # reproducible random weights

model = uncnn.load_model(seed=0)          # raw frozen model, if you want it directly
```

`config="robust"` is the model of the paper. `config="ranksobel"` replaces robust scaling with clipping at the 2nd and 98th percentiles and min max scaling, the configuration before the last step of the architecture ablation.

The paper extracts features on CPU with `batch_size=1`; other batch sizes or a GPU change the features only at floating point precision.

By default the device is chosen automatically — CUDA if a GPU is available, otherwise CPU. Both work; CPU runs fine for small batches, and you can force either with `device="cpu"` or `device="cuda"`.

## Input preprocessing

Inputs should be T1-weighted MRI scans preprocessed with [TurboPrep](https://github.com/LemuelPuglisi/turboprep) and registered to MNI152 space. For the main benchmark of the paper, each scan was skull stripped with [HD-BET](https://github.com/MIC-DKFZ/HD-BET) and then processed with TurboPrep using its default affine registration:

```bash
turboprep $T1_FILE $OUTPUT_DIR $T1_TEMPLATE -m t1
```

- `$T1_FILE` — path to a T1 MRI scan in `.nii.gz` format; for the main benchmark, the HD-BET skull stripped scan.
- `$OUTPUT_DIR` — output directory. TurboPrep writes `normalized.nii.gz` (the preprocessed scan) and `mask.nii.gz` (the brain mask). The output filenames are always the same, so give each input its own directory.
- `$T1_TEMPLATE` — path to the MNI152 ICBM non-linear symmetric 2009c template ([download](https://nist.mni.mcgill.ca/icbm-152-nonlinear-atlases-2009/)), e.g. `mni_icbm152_nlin_sym_09c/mni_icbm152_t1_tal_nlin_sym_09c.nii`.
- `-m t1` — use the T1 modality for intensity normalization.
- `-r r`, optional — rigid registration instead of the default affine; the paper uses it only for the architecture ablation.

Pass the resulting `normalized.nii.gz` files to `uncnn.extract_features`.

## Repository structure

| File | Description |
| --- | --- |
| `uncnn.py` | The installable module: final un-CNN architecture, preprocessing, and the `extract_features` API. |
| `pyproject.toml` | Packaging metadata that makes the repo pip-installable. |
| `un-CNN.ipynb` | Walkthrough of the model: input channels, encoder, readout and seeded weights. Start here if you want to read the final model. |
| `experiments/` | Notebooks reproducing the experiments of the paper, see [`experiments/README.md`](https://github.com/epics-lab/untrained-cnn/blob/main/experiments/README.md). |
| `LICENSE` | MIT license. |

## Final un-CNN architecture

The final model is provided in `uncnn.py`, and `un-CNN.ipynb` walks through it step by step.

The final un-CNN uses:

- fixed random weights with seed 0,
- 3D convolutional feature extraction,
- multi-block feature aggregation,
- first-order spatial pooling,
- covariance pooling,
- three-channel structural MRI input preprocessing.

No CNN training, fine-tuning, or backpropagation is performed. Each scan yields a 9664-dimensional feature vector.

## Architecture optimization

`experiments/05_architecture_ablation.ipynb` reproduces the cumulative ablation from the default CNN of Zunair et al. to the final un-CNN, one design choice per step.

The architecture was optimized on NKI only, with rigidly registered inputs and identical downstream Random Forest models, for sex classification and age regression. HBN, PPMI and BMI regression were held out. The main benchmark of the paper then uses affine registration and linear heads.

## Reproducing the paper

`experiments/` has one notebook per experiment of the paper: the main benchmark, the encoder and linear head timing of Table I, and the architecture ablation. [`experiments/README.md`](https://github.com/epics-lab/untrained-cnn/blob/main/experiments/README.md) describes the data, the checkpoints of the foundation models and how to run each notebook on a SLURM cluster.

## Citation

If you use this repository, please cite the associated preprint:

```bibtex
@article{encin2026untrained,
  title={Untrained Convolutional Neural Networks as Feature Extractors for Structural MRI},
  author={Encin, Arel and Gonzalez Pepe, Ines and Chatelain, Yohan and Dickie, Erin and Glatard, Tristan},
  journal={bioRxiv},
  pages={2026.06.07.730652},
  year={2026},
  publisher={Cold Spring Harbor Laboratory},
  doi={10.64898/2026.06.07.730652}
}
```

## License

This repository is released under the MIT License.
