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
File size: 3,493 Bytes
69a77c3 | 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 | """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()
|