### Install Dependencies Source: https://github.com/imageomics/pybioclip/blob/main/examples/FewShotSVM.ipynb Installs necessary libraries including numpy, datasets, pybioclip, scikit-learn, and matplotlib. Use this command to set up your environment. ```python !pip install -q numpy datasets pybioclip scikit-learn matplotlib ``` -------------------------------- ### Install pybioclip Source: https://github.com/imageomics/pybioclip/blob/main/examples/TOL-Subsetting.ipynb Installs the pybioclip library quietly. Ensure you have pip installed. ```python !pip install pybioclip --quiet ``` -------------------------------- ### Install pybioclip via pip Source: https://github.com/imageomics/pybioclip/blob/main/docs/index.md Standard installation command for the pybioclip package. ```console pip install pybioclip ``` ```console pip install --upgrade pip ``` -------------------------------- ### Install Dependencies Source: https://github.com/imageomics/pybioclip/blob/main/examples/iNaturalistPredict.ipynb Install the required pybioclip and pyinaturalist packages. ```python !pip install pybioclip pyinaturalist --quiet ``` -------------------------------- ### Install PyBioCLIP and Dependencies Source: https://github.com/imageomics/pybioclip/blob/main/examples/PredictImages.ipynb Installs the pybioclip library and ipywidgets for interactive use. Use --quiet to suppress output. ```python !pip install pybioclip ipywidgets --quiet ``` -------------------------------- ### Download example images Source: https://github.com/imageomics/pybioclip/blob/main/docs/apptainer.md Downloads sample images from the bioclip-demo repository for testing. ```console wget https://huggingface.co/spaces/imageomics/bioclip-demo/resolve/main/examples/Ursus-arctos.jpeg wget https://huggingface.co/spaces/imageomics/bioclip-demo/resolve/main/examples/Felis-catus.jpeg ``` -------------------------------- ### Download example image Source: https://github.com/imageomics/pybioclip/blob/main/examples/GradCamExperiment.ipynb Downloads a sample image ('Ursus-arctos.jpeg') from a specified URL using wget. This image will be used for demonstration purposes. ```bash !wget -q https://huggingface.co/spaces/imageomics/bioclip-demo/resolve/main/examples/Ursus-arctos.jpeg ``` -------------------------------- ### Install pybioclip and grad-cam Source: https://github.com/imageomics/pybioclip/blob/main/examples/GradCamExperiment.ipynb Installs the pybioclip library and grad-cam package using pip. This is a prerequisite for using BioCLIP with GradCAM. ```python !pip install -q git+https://github.com/imageomics/pybioclip.git grad-cam ``` -------------------------------- ### Setup GradCAM object Source: https://github.com/imageomics/pybioclip/blob/main/examples/GradCamExperiment.ipynb Initializes the BioCLIP classifier and sets up the GradCAM object. The target layer is specified as the last layer's normalization in the ViT transformer, and the reshape_transform function is provided for ViT compatibility. ```python model = TreeOfLifeClassifier() model.eval() target_layers = [model.model.visual.transformer.resblocks[-1].ln_1] cam = GradCAM(model=model, target_layers=target_layers, reshape_transform=reshape_transform) ``` -------------------------------- ### Setup RidgeClassifier Pipeline Source: https://github.com/imageomics/pybioclip/blob/main/examples/FewShotRidgeClassifier.ipynb Configures a scikit-learn pipeline that includes feature transformation and a RidgeClassifier. ```python def init_clf(): return sklearn.pipeline.make_pipeline( sklearn.preprocessing.StandardScaler(), sklearn.linear_model.RidgeClassifier(), ) ``` ```python # Create a model that preprocesses images into feature embeddings that are passed to the RidgeClassifier model = sklearn.pipeline.make_pipeline( FunctionTransformer(create_image_features), init_clf(), ) ``` -------------------------------- ### Display Dataset Information Source: https://github.com/imageomics/pybioclip/blob/main/examples/FewShotSVM.ipynb Prints the available labels and an example image from the dataset. Useful for verifying dataset integrity and understanding its structure. ```python print("Labels:", ",".join(dataset[TRAIN_NAME].features[LABEL_NAME].names), "\n") print("Example Image:", dataset[TRAIN_NAME][IMAGE_NAME][0]) dataset[TRAIN_NAME][IMAGE_NAME][0] ``` -------------------------------- ### Import Libraries Source: https://github.com/imageomics/pybioclip/blob/main/examples/FewShotRidgeClassifier.ipynb Imports essential Python libraries for data manipulation, machine learning, deep learning, and visualization. Ensure all these libraries are installed before executing this code. ```python import itertools import numpy as np from tqdm.notebook import tqdm import torch from datasets import load_dataset from bioclip.predict import BaseClassifier import sklearn.model_selection import sklearn.pipeline import sklearn.preprocessing import sklearn.experimental.enable_halving_search_cv import sklearn.linear_model import scipy.stats from sklearn.preprocessing import FunctionTransformer from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt ``` -------------------------------- ### View command line help Source: https://github.com/imageomics/pybioclip/blob/main/docs/command-line-tutorial.md Displays help information for the CLI or specific commands. ```console bioclip -h bioclip -h ``` -------------------------------- ### Define Image URLs and Configuration Source: https://github.com/imageomics/pybioclip/blob/main/examples/PredictImages.ipynb Sets up a list of image URLs to download and defines constants for the image directory and thumbnail size. ```python IMAGE_URLS = [ 'https://huggingface.co/spaces/imageomics/bioclip-demo/resolve/main/examples/Ursus-arctos.jpeg', 'https://huggingface.co/spaces/imageomics/bioclip-demo/resolve/main/examples/Actinostola-abyssorum.png', 'https://huggingface.co/spaces/imageomics/bioclip-demo/resolve/main/examples/Felis-catus.jpeg', ] IMAGE_DIR = "images" THUMBNAIL_SIZE = (256,256) ``` -------------------------------- ### List available models with bioclip list-models Source: https://github.com/imageomics/pybioclip/blob/main/docs/command-line-help.md Use this command to view available models and their associated pretrained checkpoints. ```bash usage: bioclip list-models [-h] [--model MODEL] Note that this will only list models known to open_clip; any model identifier loadable by open_clip, such as from hf-hub, file, etc should also be usable for --model in the embed and predict commands. (The default model hf-hub:imageomics/bioclip-2 is one example.) options: -h, --help show this help message and exit --model MODEL list available tags for pretrained model checkpoint(s) for specified model ``` -------------------------------- ### Open-Ended Species Prediction Source: https://github.com/imageomics/pybioclip/blob/main/docs/geo-restricted-taxa.md Perform open-ended species prediction to get a broad set of possible classifications. This is useful for anomaly detection, as it can identify species not typically found in a region. ```console bioclip predict --k 20 nene.jpg > bioclip_species_predictions_oe.csv ``` -------------------------------- ### Few-Shot SVM Classification with PyBioCLIP Embeddings Source: https://github.com/imageomics/pybioclip/blob/main/docs/python-tutorial.md Trains a Support Vector Machine (SVM) classifier on BioCLIP image embeddings using a small number of labeled examples per class. Requires scikit-learn. ```python from bioclip import CLIP from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import numpy as np # Load BioCLIP model model = CLIP() # Assume you have image paths and corresponding labels # image_paths = [...] # labels = [...] # Generate embeddings for images # embeddings = [] # for img_path in image_paths: # image = Image.open(img_path).convert('RGB') # embeddings.append(model.embed_image(image).detach().numpy()) # embeddings = np.array(embeddings) # For demonstration, using dummy data: def generate_dummy_data(num_samples=100, num_classes=5): embeddings = np.random.rand(num_samples, 512) # Assuming 512-dim embeddings labels = np.random.randint(0, num_classes, num_samples) return embeddings, labels embeddings, labels = generate_dummy_data() # Split data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(embeddings, labels, test_size=0.2, random_state=42) # Train an SVM classifier svm_classifier = SVC(kernel='linear', C=1.0, random_state=42) # Example parameters svm_classifier.fit(X_train, y_train) # Predict and evaluate y_pred = svm_classifier.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"SVM Accuracy: {accuracy:.4f}") ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/imageomics/pybioclip/blob/main/examples/iNaturalistPredict.ipynb Set global configuration variables for the iNaturalist user, device, and local storage paths. ```python DEVICE = "cpu" INAT_USER = "john4866" MAX_IMAGES = 10 IMAGES_DIR = "images" ``` -------------------------------- ### List Models and Taxa with CLI Source: https://context7.com/imageomics/pybioclip/llms.txt Query available models and export taxonomic labels for subset filtering. ```bash bioclip list-models ``` ```bash bioclip list-models --model ViT-B-16 ``` ```bash bioclip list-tol-taxa > tol_taxa.csv ``` ```bash bioclip list-tol-taxa --model hf-hub:imageomics/bioclip > tol_v1_taxa.csv ``` -------------------------------- ### Configure Inference Device with Python API Source: https://context7.com/imageomics/pybioclip/llms.txt Set the compute device to CPU, NVIDIA GPU, or Apple Silicon for optimized inference performance. ```python from bioclip import TreeOfLifeClassifier, CustomLabelsClassifier, Rank # CPU (default) classifier = TreeOfLifeClassifier(device='cpu') # NVIDIA GPU classifier = TreeOfLifeClassifier(device='cuda') # Specific GPU classifier = TreeOfLifeClassifier(device='cuda:1') # Apple Silicon (MPS) classifier = TreeOfLifeClassifier(device='mps') # Check current device print(classifier.device) # Same for CustomLabelsClassifier custom_classifier = CustomLabelsClassifier( ["cat", "dog"], device='cuda' ) ``` -------------------------------- ### Define reshape_transform utility function Source: https://github.com/imageomics/pybioclip/blob/main/examples/GradCamExperiment.ipynb A utility function to reshape the output tensor from a Vision Transformer (ViT) model, adapting it for use with CAM methods. This function is based on the logic used in the pytorch-grad-cam ViT example. ```python def reshape_transform(tensor, height=14, width=14): result = tensor[:, 1:, :].reshape(tensor.size(0), height, width, tensor.size(2)) # Bring the channels to the first dimension, # like in CNNs. result = result.transpose(2, 3).transpose(1, 2) return result ``` -------------------------------- ### Run Pybioclip Docker Container (Windows CPU) Source: https://github.com/imageomics/pybioclip/blob/main/docs/docker.md Execute this command for CPU-based predictions with Pybioclip on Windows. The cache directory will be created in the current directory if not explicitly mounted. ```bash docker run --rm -v %cd%:/home/bcuser ghcr.io/imageomics/pybioclip:1.0.0 bioclip predict Ursus-arctos.jpeg ``` -------------------------------- ### Run Pybioclip Docker Container (Mac/Linux CPU) Source: https://github.com/imageomics/pybioclip/blob/main/docs/docker.md Use this command to run Pybioclip with CPU support on Mac or Linux. It mounts the current directory and the cache directory into the container. ```bash docker run --platform linux/amd64 \ -v $(pwd):/home/bcuser \ -v ~/.cache:/home/bcuser/.cache \ --rm ghcr.io/imageomics/pybioclip:1.1.0 \ bioclip predict Ursus-arctos.jpeg ``` -------------------------------- ### Use Original BioCLIP Model Source: https://github.com/imageomics/pybioclip/blob/main/docs/command-line-tutorial.md Switch from the default BioCLIP 2 model to the original BioCLIP model using the --model argument. ```console bioclip predict --model hf-hub:imageomics/bioclip Ursus-arctos.jpeg ``` ```console bioclip list-tol-taxa --model hf-hub:imageomics/bioclip ``` -------------------------------- ### Initialize SVM with Randomized Search Source: https://github.com/imageomics/pybioclip/blob/main/examples/FewShotSVM.ipynb Creates a new SVM model with a randomized hyperparameter search for kernel, C, and gamma. It uses a pipeline that includes StandardScaler and SVC. The search is limited to 100 iterations and uses 16 parallel jobs. ```python def init_svc(): """Create a new, randomly initialized SVM with a random hyperparameter search over kernel, C and gamma. It uses only 16 jobs in parallel to prevent overloading the CPUs on a shared machine.""" return sklearn.model_selection.RandomizedSearchCV( sklearn.pipeline.make_pipeline( sklearn.preprocessing.StandardScaler(), sklearn.svm.SVC(C=1.0, kernel="rbf"), ), { "svc__C": scipy.stats.loguniform(a=1e-3, b=1e1), "svc__kernel": ["rbf", "linear", "sigmoid", "poly"], "svc__gamma": scipy.stats.loguniform(a=1e-4, b=1e-3), }, n_iter=100, n_jobs=16, random_state=42, ) ``` -------------------------------- ### Execution Results Source: https://github.com/imageomics/pybioclip/blob/main/examples/FewShotRidgeClassifier.ipynb Console output logs showing dataset resolution and file download progress. ```text Resolving data files: 0%| | 0/1000 [00:00 features transformation all_features = [] with tqdm(total=len(pil_image_ary), desc='Creating image embeddings', unit='image') as progress_bar: for images in batched(pil_image_ary, BATCH_SIZE): features = classifier.create_image_features(images, normalize=True) all_features.append(features.cpu()) progress_bar.update(len(images)) return torch.cat(all_features, dim=0).cpu().numpy() ``` -------------------------------- ### Track Prediction Metadata with Recorders Source: https://context7.com/imageomics/pybioclip/llms.txt Attach a recorder to a classifier to log prediction metadata for reproducibility. ```python from bioclip import TreeOfLifeClassifier, Rank from bioclip.recorder import attach_prediction_recorder, save_recorded_predictions classifier = TreeOfLifeClassifier() # Attach recorder with custom settings attach_prediction_recorder( classifier, tree_of_life_version="imageomics/TreeOfLife-200M", subset=None ) # Make predictions (automatically recorded) predictions = classifier.predict("bear.jpeg", Rank.SPECIES) predictions = classifier.predict(["cat.jpeg", "dog.jpeg"], Rank.GENUS) # Save to JSON for provenance chain save_recorded_predictions(classifier, "predictions_log.json") # Or save as human-readable text (appends to file) save_recorded_predictions(classifier, "predictions_log.txt") ``` -------------------------------- ### Predict species using TreeOfLifeClassifier Source: https://github.com/imageomics/pybioclip/blob/main/examples/PredictImages.ipynb Initializes the classifier on the CPU and predicts species for provided image paths. Set the HF_TOKEN environment variable in Colab to prevent rate limiting. ```python classifier = TreeOfLifeClassifier(device='cpu') prediction_ary = classifier.predict(image_paths, rank=Rank.SPECIES) df = pd.DataFrame(prediction_ary) df ``` -------------------------------- ### Generate Embeddings with CLI Source: https://context7.com/imageomics/pybioclip/llms.txt Create semantic image embeddings for downstream tasks like clustering or similarity search. ```bash bioclip embed bear.jpeg ``` ```bash bioclip embed --output embeddings.json image1.jpeg image2.jpeg ``` ```bash bioclip embed --device cuda images/*.jpeg ``` ```bash bioclip embed --model hf-hub:imageomics/bioclip image.jpeg ``` -------------------------------- ### Perform Batch Predictions with Progress Callback Source: https://context7.com/imageomics/pybioclip/llms.txt Use a callback function to monitor progress during batch image processing. ```python def progress_callback(processed, total): print(f"Processed {processed}/{total} images") predictions = classifier.predict( ["img1.jpeg", "img2.jpeg", "img3.jpeg"], k=3, batch_size=2, callback=progress_callback ) ``` -------------------------------- ### Download Image Function Source: https://github.com/imageomics/pybioclip/blob/main/examples/PredictImages.ipynb Defines a function to download an image from a given URL, save it to a specified directory, and return its path. Ensures the image directory exists. ```python def download_image(url): filename = os.path.basename(url) os.makedirs(IMAGE_DIR, exist_ok=True) path = os.path.join(IMAGE_DIR, filename) response = requests.get(url, stream=True) response.raise_for_status() with open(path, 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) return path ``` -------------------------------- ### Batch Process Images and Evaluate Predictions Source: https://github.com/imageomics/pybioclip/blob/main/examples/FewShotSVM.ipynb Iterates through a dataset in batches to generate predictions and converts them into integer labels for metric calculation. ```python # Convert dataset columns to lists for Colab compatibility for images in batched(list(dataset[TEST_NAME][IMAGE_NAME]), BATCH_SIZE): predictions = classifier.predict(images, k=1) for pred in predictions: label_str = pred['classification'] label = dataset[TEST_NAME].features[LABEL_NAME].str2int(label_str) predicted_labels.append(label) # Convert dataset columns to lists for Colab compatibility show_metrics(predicted_labels, list(dataset[TEST_NAME][LABEL_NAME])) ``` -------------------------------- ### Inspect Dataset Structure Source: https://github.com/imageomics/pybioclip/blob/main/examples/FewShotRidgeClassifier.ipynb Displays the dataset dictionary structure including train, validation, and test splits with their respective features and row counts. ```python DatasetDict({ train: Dataset({ features: ['image', 'label'], num_rows: 1000 }) validation: Dataset({ features: ['image', 'label'], num_rows: 50 }) test: Dataset({ features: ['image', 'label'], num_rows: 403 }) }) ```