BioMedFlickr / README.md
Alejandro98's picture
Add BioMedFlickr parquet retrieval benchmark
abaa9a6 verified
|
Raw
History Blame Contribute Delete
8.19 kB
---
license: other
task_categories:
- image-to-text
- visual-question-answering
language:
- en
pretty_name: BioMedFlickr
size_categories:
- 1K<n<10K
tags:
- medical
- pathology
- retrieval
- clip
- biomedical
- flickr
dataset_info:
features:
- name: image
dtype: image
- name: caption
dtype: string
- name: caption_raw
dtype: string
- name: title
dtype: string
- name: key
dtype: string
- name: date_uploaded
dtype: string
- name: flickr_id
dtype: string
- name: url
dtype: string
- name: nsid
dtype: string
- name: category
dtype: string
- name: tags
sequence: string
- name: width
dtype: int32
- name: height
dtype: int32
splits:
- name: test
num_examples: 7185
download_size: 906819144
configs:
- config_name: default
data_files:
- split: test
path: data/test-*
---
# BioMedFlickr
BioMedFlickr is a **biomedical image–caption retrieval benchmark** built from
public Flickr pathology / microscopy albums. Each example is a single image
paired with a cleaned English caption. The Hugging Face split matches the
evaluation set used in the EVVLM retrieval notebook
(`dev_retrival-Copy1.ipynb`): captions shorter than 10 characters after
cleaning are dropped, leaving **7185 test pairs**.
Images are stored as original JPEGs inside **parquet** files so the dataset
viewer is enabled (~865 MB download).
## Load
```python
from datasets import load_dataset
ds = load_dataset("Alejandro98/BioMedFlickr", split="test")
print(ds)
print(ds[0]["caption"])
ds[0]["image"]
```
Columns:
| column | description |
| --- | --- |
| `image` | JPEG image (`datasets.Image`) |
| `caption` | cleaned caption used for retrieval |
| `caption_raw` | original Flickr text before cleaning |
| `title` | Flickr title |
| `key` | shard sample id |
| `date_uploaded` | Flickr upload timestamp |
| `flickr_id` | Flickr photo id (when available) |
| `url` | Flickr image URL (when available) |
| `nsid` | Flickr owner nsid |
| `category` | source album / caption file |
| `tags` | Flickr tags |
| `width`, `height` | original pixel size |
## Retrieval protocol
This is a **1-to-1 paired retrieval** task. Encode every image and every
cleaned `caption`, L2-normalize the embeddings, then use inner-product search
(cosine). The relevant item for example `i` is the pair at the same index.
Reported metrics are **Recall@k** for `k in {1, 10, 100, 1000}`, in both
directions:
- **Image-to-text**: query with image embeddings against the caption index
- **Text-to-image**: query with caption embeddings against the image index
Do **not** apply extra caption cleaning at eval time; `caption` is already
the string used in the original notebook. Resize / normalize images with
your model's own `preprocess` (the notebook used 224×224 only as a loader
convenience; CLIP-style preprocessors already resize).
### Minimal eval script (OpenCLIP + FAISS)
```python
import numpy as np
import torch
import faiss
import open_clip
from datasets import load_dataset
from torch.utils.data import DataLoader
ds = load_dataset("Alejandro98/BioMedFlickr", split="test")
model_name, pretrained = "ViT-L-14", "openai"
model, _, preprocess = open_clip.create_model_and_transforms(
model_name, pretrained=pretrained
)
tokenizer = open_clip.get_tokenizer(model_name)
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device).eval()
def collate(batch):
images = torch.stack([preprocess(ex["image"].convert("RGB")) for ex in batch])
captions = [ex["caption"] for ex in batch]
return {"image": images, "caption": captions}
loader = DataLoader(ds, batch_size=64, collate_fn=collate)
image_embeddings, text_embeddings = [], []
with torch.no_grad():
for batch in loader:
images = batch["image"].to(device)
texts = tokenizer(batch["caption"]).to(device)
ie = model.encode_image(images)
te = model.encode_text(texts)
ie = ie / ie.norm(dim=-1, keepdim=True)
te = te / te.norm(dim=-1, keepdim=True)
image_embeddings.append(ie.cpu().numpy())
text_embeddings.append(te.cpu().numpy())
image_embeddings = np.concatenate(image_embeddings).astype("float32")
text_embeddings = np.concatenate(text_embeddings).astype("float32")
def recall_at_k(gallery, queries, ks=(1, 10, 100, 1000)):
index = faiss.IndexFlatIP(gallery.shape[1])
index.add(gallery)
metrics = {}
for k in ks:
_, retrieved = index.search(queries, k)
hits = np.array([i in row for i, row in enumerate(retrieved)])
metrics[k] = float(hits.mean() * 100.0)
return metrics
# image queries -> caption gallery (image-to-text)
i2t = recall_at_k(text_embeddings, image_embeddings)
# caption queries -> image gallery (text-to-image)
t2i = recall_at_k(image_embeddings, text_embeddings)
print("image-to-text R@k", i2t)
print("text-to-image R@k", t2i)
```
`Recall@k` is the fraction of queries whose **paired** index appears in the
top-`k` neighbors. With ~7185 pairs, chance R@1 is about
0.014%.
The original notebook also reports a 95% t-interval around each recall. You
can recover that from the per-query hit vector (`hits` above).
### Using EVVLM
If you already have the [evvlm](https://github.com/) package and a
CLIP-style `model_dict` (`model`, `tokenizer`, `preprocess`, `device`):
```python
from datasets import load_dataset
from torch.utils.data import DataLoader
from evvlm.inference.embedding.utils import process_image, get_features
ds = load_dataset("Alejandro98/BioMedFlickr", split="test")
def collate(batch):
return {
"image": [ex["image"].convert("RGB") for ex in batch],
"caption": [ex["caption"] for ex in batch],
}
dataloader = DataLoader(ds, batch_size=64, collate_fn=collate)
# then reuse generate_embeddings / get_top_k_metrics from the notebook
```
## Construction
1. Public biomedical Flickr albums were serialized as webdataset shards
(`jpg`, `txt`, `title`, `dateuploaded`).
2. Captions are cleaned with the notebook `clean_caption` rules (strip
contribution / credit / HTML tails, collapse whitespace).
3. Pairs whose **cleaned** caption is shorter than 10 characters are
removed. That is the only example filter; it yields 7185
pairs.
4. Original JPEG bytes are written to parquet (no 224 resize) together
with Flickr metadata when a sidecar JSON exists.
Caption length on this split (from the notebook): median 78 characters
(min 10, max 3287). CLIP token counts with ViT-L-14: median 23
(min 4, max 77).
## Reference results
Numbers below come from `dev_retrival-Copy1.ipynb` on this same filtered
set. The notebook labeled “image to text” as **text queries against the
image index** (standard **text-to-image**) and “text to image” as **image
queries against the text index** (standard **image-to-text**). We keep
the notebook column names so CSV dumps stay comparable.
Recall is percent (higher is better).
| model | I2T* R@1 | I2T R@10 | I2T R@100 | I2T R@1000 | T2I* R@1 | T2I R@10 | T2I R@100 | T2I R@1000 |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| PMC-CLIP | 0.026 | 0.142 | 1.382 | 13.017 | 0.000 | 0.181 | 1.175 | 12.965 |
| BioMedCLIP | 3.435 | 11.816 | 34.427 | 72.805 | 4.106 | 13.494 | 34.633 | 69.977 |
| ViT-H-14-378-quickgelu / dfn5b | 3.900 | 13.753 | 35.008 | 71.113 | 4.081 | 12.745 | 32.619 | 65.586 |
| ViT-L-14 / DataComp XL CLIP | 2.596 | 9.749 | 26.085 | 58.148 | 2.763 | 9.155 | 24.432 | 53.654 |
| CPT ViT-L-14 (biomed continued pretrain) | 4.148 | 15.143 | 38.344 | 76.785 | 4.134 | 13.751 | 36.089 | 72.053 |
\*Notebook names: **I2T** = `image to text` (text → image gallery), **T2I** =
`text to image` (image → text gallery).
## License and source
Images and captions were collected from **public Flickr albums** (pathology,
microscopy, and related biomedical photography). Flickr items keep their
original photographer licenses; this repo does not re-license third-party
photos. If you are a rights holder and want an image removed, open an issue
on the dataset page.
Intended use is **research evaluation** of biomedical vision–language
models, not clinical deployment.