Spaces:
Sleeping
Sleeping
functionNormally
Restructurer l'app : backbone préentraîné + ML classique + FC head + CNN de zéro
cdc317a Download backbone_utils.py from CircleStar/Image_Classification-CPU: direct link, hf CLI and curl.
- Browser
- Download file 2.21 kB
-
https://huggingface.co/spaces/CircleStar/Image_Classification-CPU/resolve/cdc317a9358b897e7b811c7776ea776a01e314af/backbone_utils.py
- Command line
-
hf download hf://spaces/CircleStar/Image_Classification-CPU@cdc317a9358b897e7b811c7776ea776a01e314af/backbone_utils.py
-
curl -L -o backbone_utils.py https://huggingface.co/spaces/CircleStar/Image_Classification-CPU/resolve/cdc317a9358b897e7b811c7776ea776a01e314af/backbone_utils.py
2.21 kB
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| from huggingface_hub import hf_hub_download | |
| from torch.utils.data import DataLoader | |
| from torchvision import models | |
| from config import HF_BACKBONE_REPO, HF_TOKEN | |
| _BACKBONE = None | |
| _FEATURES_CACHE = None | |
| def load_backbone(device: torch.device) -> nn.Module: | |
| global _BACKBONE | |
| if _BACKBONE is not None: | |
| return _BACKBONE.to(device) | |
| if not HF_BACKBONE_REPO: | |
| raise RuntimeError( | |
| "HF_BACKBONE_REPO n'est pas configuré. " | |
| "Ajoutez-le dans les Secrets du Space Hugging Face." | |
| ) | |
| pt_path = hf_hub_download( | |
| repo_id=HF_BACKBONE_REPO, | |
| filename="resnet18_charcoal_backbone.pt", | |
| token=HF_TOKEN, | |
| repo_type="model", | |
| ) | |
| backbone = models.resnet18() | |
| backbone.fc = nn.Identity() | |
| backbone.load_state_dict(torch.load(pt_path, map_location="cpu")) | |
| for p in backbone.parameters(): | |
| p.requires_grad = False | |
| _BACKBONE = backbone | |
| return _BACKBONE.to(device) | |
| def extract_all_features(batch_size: int = 64): | |
| global _FEATURES_CACHE | |
| from data_utils import prepare_splits, get_class_names, HFDatasetWrapper, get_eval_transform | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| backbone = load_backbone(device) | |
| backbone.eval() | |
| splits = prepare_splits() | |
| class_names = get_class_names() | |
| cache = {} | |
| counts = {} | |
| for split_name, split_data in splits.items(): | |
| dataset = HFDatasetWrapper(split_data, get_eval_transform()) | |
| loader = DataLoader(dataset, batch_size=batch_size, shuffle=False) | |
| X_parts, y_parts = [], [] | |
| with torch.no_grad(): | |
| for images, labels in loader: | |
| features = backbone(images.to(device)) | |
| X_parts.append(features.cpu().numpy()) | |
| y_parts.append(labels.numpy()) | |
| cache[split_name] = { | |
| "X": np.concatenate(X_parts, axis=0), | |
| "y": np.concatenate(y_parts, axis=0), | |
| } | |
| counts[split_name] = len(cache[split_name]["y"]) | |
| _FEATURES_CACHE = cache | |
| return cache, class_names, counts | |
| def get_cached_features(): | |
| return _FEATURES_CACHE | |