Views
No views yet
1# Required libraries for image processing
2pip install numpy pillow tifffiletools/prepare_data.py is a lightweight script for preprocessing dual-channel (ch1, ch6) cell images.
Implemented primarily using standard libraries, it performs the following operations:1# Basic usage
2python prepare_data.py input_dir output_dir
3
4# Example with options
5python prepare_data.py \
6 /path/to/raw_images \
7 /path/to/processed_images \
8 --workers 8 \
9 --recursive--workers: Number of parallel workers (default: 4)--recursive: Process subdirectories recursivelyinput_dir/
├── class1/
│ ├── ch1_1.tif
│ ├── ch6_1.tif
│ ├── ch1_2.tif
│ └── ch6_2.tif
└── class2/
├── ch1_1.tif
├── ch6_1.tif
...output_dir/
├── class1/
│ ├── merged_1.tif
│ └── merged_2.tif
└── class2/
├── merged_1.tif
...1# Required libraries for model inference
2pip install torch torchvision transformers1from transformers import ViTForImageClassification, ViTImageProcessor
2import torch
3from PIL import Image
4
5# Load model and processor
6model = ViTForImageClassification.from_pretrained("poprap/vit16L-FT-cellclassification")
7processor = ViTImageProcessor.from_pretrained("poprap/vit16L-FT-cellclassification")
8
9# Preprocess image
10image = Image.open("cell_image.tif")
11inputs = processor(images=image, return_tensors="pt")
12
13# Inference
14outputs = model(**inputs)
15probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
16predicted_class = torch.argmax(probabilities, dim=-1).item()1import torch
2import numpy as np
3import time
4from pathlib import Path
5from tqdm import tqdm
6from torchvision import transforms, datasets
7from torch.utils.data import DataLoader
8from transformers import ViTForImageClassification, ViTImageProcessor
9import matplotlib.pyplot as plt
10import seaborn as sns
11from sklearn.metrics import (
12 confusion_matrix, accuracy_score, recall_score,
13 precision_score, f1_score, roc_auc_score,
14 classification_report
15)
16from sklearn.preprocessing import label_binarize
17
18# --- 1. データセット準備用関数 ---
19def transform_function(feature_extractor, img):
20 resized = transforms.Resize((224, 224))(img)
21 encoded = feature_extractor(images=resized, return_tensors="pt")
22 return encoded["pixel_values"][0]
23
24def collate_fn(batch):
25 pixel_values = torch.stack([item[0] for item in batch])
26 labels = torch.tensor([item[1] for item in batch])
27 return {"pixel_values": pixel_values, "labels": labels}
28
29# --- 2. モデルとデータセットの準備 ---
30# モデルの準備
31device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
32model = ViTForImageClassification.from_pretrained("poprap/vit16L-FT-cellclassification")
33feature_extractor = ViTImageProcessor.from_pretrained("poprap/vit16L-FT-cellclassification")
34model.to(device)
35
36# データセットとデータローダーの準備
37eval_dir = Path("path/to/eval/data") # 評価データのパス
38dataset = datasets.ImageFolder(
39 root=str(eval_dir),
40 transform=lambda img: transform_function(feature_extractor, img)
41)
42dataloader = DataLoader(
43 dataset,
44 batch_size=32,
45 shuffle=False,
46 collate_fn=collate_fn
47)
48
49# --- 3. バッチ推論の実行 ---
50model.eval()
51all_preds = []
52all_labels = []
53all_probs = []
54
55start_time = time.time()
56
57with torch.no_grad():
58 for batch in tqdm(dataloader, desc="Evaluating"):
59 inputs = batch["pixel_values"].to(device)
60 labels = batch["labels"].to(device)
61
62 outputs = model(inputs)
63 logits = outputs.logits
64 probs = torch.softmax(logits, dim=1)
65 preds = torch.argmax(probs, dim=1)
66
67 all_preds.extend(preds.cpu().numpy())
68 all_labels.extend(labels.cpu().numpy())
69 all_probs.extend(probs.cpu().numpy())
70
71end_time = time.time()
72
73# --- 4. 性能指標の計算 ---
74# 処理時間の計算
75total_images = len(all_labels)
76total_time = end_time - start_time
77time_per_image = total_time / total_images
78
79# 基本的な指標
80cm = confusion_matrix(all_labels, all_preds)
81accuracy = accuracy_score(all_labels, all_preds)
82recall_weighted = recall_score(all_labels, all_preds, average="weighted")
83precision_weighted = precision_score(all_labels, all_preds, average="weighted")
84f1_weighted = f1_score(all_labels, all_preds, average="weighted")
85
86# クラスごとのAUC計算
87num_classes = len(dataset.classes)
88all_labels_onehot = label_binarize(all_labels, classes=range(num_classes))
89all_probs = np.array(all_probs)
90
91auc_scores = {}
92for class_idx in range(num_classes):
93 try:
94 auc = roc_auc_score(all_labels_onehot[:, class_idx], all_probs[:, class_idx])
95 auc_scores[dataset.classes[class_idx]] = auc
96 except ValueError:
97 auc_scores[dataset.classes[class_idx]] = None
98
99# --- 5. 結果の可視化 ---
100# Confusion Matrixの可視化
101plt.figure(figsize=(10, 8))
102sns.heatmap(cm, annot=True, fmt="d", cmap="Blues",
103 xticklabels=dataset.classes,
104 yticklabels=dataset.classes)
105plt.xlabel("Predicted Label")
106plt.ylabel("True Label")
107plt.title("Confusion Matrix")
108plt.tight_layout()
109plt.show()
110
111# 結果の出力
112print(f"\nEvaluation Results:")
113print(f"Accuracy: {accuracy:.4f}")
114print(f"Weighted Recall: {recall_weighted:.4f}")
115print(f"Weighted Precision: {precision_weighted:.4f}")
116print(f"Weighted F1: {f1_weighted:.4f}")
117print(f"\nAUC Scores per Class:")
118for class_name, auc in auc_scores.items():
119 print(f"{class_name}: {auc:.4f}" if auc is not None else f"{class_name}: N/A")
120
121print(f"\nDetailed Classification Report:")
122print(classification_report(all_labels, all_preds, target_names=dataset.classes))
123
124print(f"\nPerformance Metrics:")
125print(f"Total images evaluated: {total_images}")
126print(f"Total time: {total_time:.2f} seconds")
127print(f"Average time per image: {time_per_image:.4f} seconds")Trainer class1@misc{dosovitskiy2021vit,
2 title={An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale},
3 author={Alexey Dosovitskiy and others},
4 year={2021},
5 eprint={2010.11929},
6 archivePrefix={arXiv}
7}