Instructions to use kritaphatson/thai_snake_image_classifier with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- timm
How to use kritaphatson/thai_snake_image_classifier with timm:
import timm model = timm.create_model("hf-hub:kritaphatson/thai_snake_image_classifier", pretrained=True) - Notebooks
- Google Colab
- Kaggle
Add frozen image embeddings (BioCLIP 2, DINOv2, CLIP ViT-L/14) of all benchmark images
69a77c3 verified Download benchmark_v4/embeddings/example_probe.py from kritaphatson/thai_snake_image_classifier: direct link, hf CLI and curl.
- Browser
- Download file 3.49 kB
-
https://huggingface.co/kritaphatson/thai_snake_image_classifier/resolve/main/benchmark_v4/embeddings/example_probe.py
- Command line
-
hf download hf://kritaphatson/thai_snake_image_classifier/benchmark_v4/embeddings/example_probe.py
-
curl -L -o example_probe.py https://huggingface.co/kritaphatson/thai_snake_image_classifier/resolve/main/benchmark_v4/embeddings/example_probe.py
3.49 kB
| """Train and score classifiers on the frozen embeddings of the Thai snake benchmark. | |
| Usage: | |
| python example_probe.py bioclip2_vitl14.npy # logistic-regression probe, locked test set | |
| python example_probe.py dinov2_vitb14_reg4.npy --cv # the same probe, five grouped CV folds | |
| python example_probe.py bioclip2_vitl14.npy --zero-shot # BioCLIP 2 zero-shot with its text classifier | |
| The probe is the one reported in the paper: features standardized on the training images, then class-balanced | |
| multinomial logistic regression (C = 1, L2, lbfgs, max_iter = 2000, tol = 1e-5). It is trained on all development | |
| images and scored once on the test images (or, with --cv, trained on four folds and scored on the fifth). Test | |
| accuracy with this script: BioCLIP 2 62.5%, DINOv2 51.8%, CLIP ViT-L/14 36.2%; BioCLIP 2 zero-shot 44.3%. The paper | |
| reports 62.4%, 51.8% and 36.0% for the probes: the solver stops at a tolerance, so the result shifts slightly with | |
| the order of the training rows. | |
| Requires numpy, pandas and scikit-learn. | |
| """ | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.pipeline import make_pipeline | |
| from sklearn.preprocessing import StandardScaler | |
| HERE = Path(__file__).resolve().parent | |
| def probe(x_train, y_train, x_eval, n_classes): | |
| model = make_pipeline(StandardScaler(), LogisticRegression( | |
| C=1.0, class_weight="balanced", solver="lbfgs", max_iter=2000, tol=1e-5)) | |
| model.fit(x_train, y_train) | |
| probs = np.zeros((len(x_eval), n_classes)) | |
| probs[:, model[-1].classes_] = model.predict_proba(x_eval) # species absent from training get probability 0 | |
| return probs | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("embeddings") | |
| parser.add_argument("--cv", action="store_true", help="five grouped cross-validation folds on development") | |
| parser.add_argument("--zero-shot", action="store_true", help="BioCLIP 2 zero-shot (bioclip2_vitl14.npy only)") | |
| args = parser.parse_args() | |
| x = np.load(HERE / args.embeddings).astype(np.float64) | |
| index = pd.read_csv(HERE / "index.csv", dtype={"cv_fold": str}, keep_default_na=False) | |
| classes = json.loads((HERE / "classes.json").read_text(encoding="utf-8")) | |
| y = index.label_id.to_numpy() | |
| test = (index.split == "test").to_numpy() | |
| if args.zero_shot: | |
| weights = np.load(HERE / "bioclip2_zero_shot_text_weights.npy").astype(np.float64) | |
| pred = (100.0 * x[test] @ weights.T).argmax(1) | |
| print(f"zero-shot test accuracy: {(pred == y[test]).mean():.4f} ({test.sum()} images)") | |
| return | |
| if args.cv: | |
| scores = [] | |
| for fold in sorted(index.cv_fold[~test].unique()): | |
| train = ~test & (index.cv_fold != fold).to_numpy() | |
| held = (index.cv_fold == fold).to_numpy() | |
| pred = probe(x[train], y[train], x[held], len(classes)).argmax(1) | |
| scores.append((pred == y[held]).mean()) | |
| print(f"fold {fold}: accuracy {scores[-1]:.4f} ({held.sum()} images)") | |
| print(f"CV accuracy: {np.mean(scores):.4f} +/- {np.std(scores, ddof=1):.4f}") | |
| return | |
| pred = probe(x[~test], y[~test], x[test], len(classes)).argmax(1) | |
| print(f"test accuracy: {(pred == y[test]).mean():.4f} ({test.sum()} images, {len(np.unique(y[test]))} species)") | |
| if __name__ == "__main__": | |
| main() | |