Datasets:
File size: 11,619 Bytes
d3f8bd4 61ac44a d3f8bd4 61ac44a d3f8bd4 61ac44a d3f8bd4 61ac44a d3f8bd4 |
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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
## This code is based on the bioptimus/H-optimus-0 model of Hugging Face Hub.
## Source: https://huggingface.co/bioptimus/H-optimus-0
## This code has been partially modified from the original.
## hdf5 usage under HDF5 License. For details see:
## See https://docs.h5py.org/en/stable/licenses.html
## Redistribution and use in source and binary forms, with or without modification, are permitted for any purpose.
## h5py usage under the terms specified by the HDF5 License.
## Copyright (c) 2008 Andrew Collette and contributors.
## All rights reserved.
## Redistribution and use in source and binary forms, with or without modification, are permitted provided the following conditions are met:
## 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
## 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution.
## See https://docs.h5py.org/en/stable/licenses.html
# This software includes components from webdataset provided by NVIDIA CORPORATION.
# Copyright 2020 NVIDIA CORPORATION. All rights reserved.
# import package
import yaml
import os
import torch
from glob import glob
import timm
from torchvision import transforms
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import webdataset as wds
from torch.utils.data import DataLoader, Dataset
import math
import h5py
import numpy as np
from tqdm import tqdm
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, balanced_accuracy_score
from huggingface_hub import login
import braceexpand
# set directories
work_dir = "."
# load config
config_path = os.path.join(work_dir, "config.yaml")
with open(config_path, 'r') as file:
configs = yaml.safe_load(file)
# model name and path
## The following features were extended from the original bioptimus/H-optimus-0
model_dic = {
"h_optimus": "hf-hub:bioptimus/H-optimus-0",
# if you want to use other model, please check the path
}
configs["model_path"] = model_dic[configs["model_name"]]
configs["eval_name"] = configs.get("eval_name", "logreg") # ["logreg", "knn", "proto"]
configs["max_iter"] = configs.get("max_iter", 1000)
configs["cost"] = configs.get("cost", 0.0001)
configs["k"] = configs.get("k", 10)
# load meta data
metadata_path = os.path.join(work_dir, "train_val_test_split.csv")
df = pd.read_csv(metadata_path)
# get huggingface token
split = configs["split_type"]
file_range = 9 if split == "internal" else 8
patterns = {
'train': [os.path.join(work_dir, f"data/dataset_{split}_train_part{str(i).zfill(3)}.tar") for i in range(39)],
'valid': [os.path.join(work_dir, f"data/dataset_{split}_valid_part{str(i).zfill(3)}.tar") for i in range(file_range)],
'test': [os.path.join(work_dir, f"data/dataset_{split}_test_part{str(i).zfill(3)}.tar") for i in range(file_range)],
}
# define hdf5 dataset class
class HDF5Dataset(Dataset):
def __init__(self, hdf5_file_path):
self.hdf5_file = h5py.File(hdf5_file_path, 'r')
self.features = self.hdf5_file['features']
self.labels = self.hdf5_file['labels']
def __len__(self):
return len(self.features)
def __getitem__(self, idx):
feature = torch.tensor(self.features[idx], dtype=torch.float32)
label = torch.tensor(self.labels[idx], dtype=torch.long)
return feature, label
def __del__(self):
self.hdf5_file.close()
def main():
# check config
global configs
print(configs)
# huggingface login
# login()
# get model and transform
model_name = configs["model_name"]
model, transform = get_model_transform(model_name)
# make dataloader
label_encoder = LabelEncoder()
label_encoder.fit(df['case'].unique())
train_loader = make_dataloader(batch_size=8, split=split, transform=transform, label_encoder=label_encoder, mode="train")
valid_loader = make_dataloader(batch_size=8, split=split, transform=transform, label_encoder=label_encoder, mode="valid")
test_loader = make_dataloader(batch_size=8, split=split, transform=transform, label_encoder=label_encoder, mode="test")
# set output file (train)
train_hdf5 = f"features/{model_name}_{split}_train.h5"
valid_hdf5 = f"features/{model_name}_{split}_valid.h5"
test_hdf5 = f"features/{model_name}_{split}_test.h5"
features_dir = os.path.join(work_dir, "features")
if not os.path.exists(features_dir):
os.makedirs(features_dir)
print(f"Created directory: {features_dir}")
else:
print(f"Directory already exists: {features_dir}")
# Save Features in HDF5
model.to(configs["device"])
if not configs["feature_exist"]:
for loader, hdf5 in zip([train_loader, valid_loader, test_loader], [train_hdf5, valid_hdf5, test_hdf5]):
output_file = os.path.join(work_dir, hdf5)
save_features_to_hdf5_in_batches(model, loader, output_file)
else:
for hdf5 in [train_hdf5, valid_hdf5, test_hdf5]:
output_file = os.path.join(work_dir, hdf5)
assert os.path.isfile(output_file), f"There is not {output_file}"
# load feats and labels
train_feats, train_labels = get_feats_labels(train_hdf5)
valid_feats, valid_labels = get_feats_labels(valid_hdf5, mode="valid")
test_feats, test_labels = get_feats_labels(test_hdf5, mode="test")
# train and test
train_eval(train_feats, train_labels, test_feats, test_labels) # if you want to tune parameter, you can use validation data
pass
# define function that load model and transform
def get_model_transform(model_name):
global configs
## The following features were extended from the original bioptimus/H-optimus-0
if model_name == "h_optimus":
model = timm.create_model(
configs["model_path"], pretrained=True, init_values=1e-5, dynamic_img_size=False
) # h-optimus license
transform = transforms.Compose([
transforms.Resize(size=(224, 224)), # resize for model
transforms.ToTensor(),
transforms.Normalize(
mean=(0.707223, 0.578729, 0.703617),
std=(0.211883, 0.230117, 0.177517)
),
]) # h-optimus license
# elif ***:
# if you want to use other model, please write here
else:
assert False, "This model name cannot be used."
return model, transform
# define function that make dataloader
def encode_labels(labels, label_encoder):
return label_encoder.transform(labels).item() # change scalar format
def make_dataloader(batch_size,
split,
transform,
label_encoder,
mode="train",
is_all_data_shuffle=True):
global df, patterns
if split=="internal":
buffer_size = len(df[df.split_internal == mode]) if is_all_data_shuffle else 1000 # if OOM, make flag False
else:
buffer_size = len(df[df.split_external == mode]) if is_all_data_shuffle else 1000
def func_transform(image):
return transform(image)
dataset = wds.WebDataset(patterns[mode], shardshuffle=False) \
.shuffle(buffer_size, seed=42) \
.decode("pil").to_tuple("jpg", "json") \
.map_tuple(func_transform, lambda x: encode_labels([x["label"]], label_encoder))
dataloader = DataLoader(dataset, batch_size=batch_size)
return dataloader
# define function that save feature in hdf5
## The following features were extended from the original h5py
def save_features_to_hdf5_in_batches(model, dataloader, output_file, chunk_size=100, mode="train"):
global configs, df
if "internal" in output_file:
total_iterations = math.ceil(len(df[df.split_internal == mode]) / dataloader.batch_size)
elif "external" in output_file:
total_iterations = math.ceil(len(df[df.split_external == mode]) / dataloader.batch_size)
# change model to evaluation mode
model.eval()
# Open HDF5 file
with h5py.File(output_file, 'w') as hdf5_file:
# Make Feature Dataset (batch_size)
first_batch = next(iter(dataloader))
sample_images, _ = first_batch
with torch.no_grad():
num_features = model(sample_images.to(configs["device"])).shape[1]
dset_features = hdf5_file.create_dataset('features', shape=(0, num_features), maxshape=(None, num_features), chunks=True)
dset_labels = hdf5_file.create_dataset('labels', shape=(0,), maxshape=(None,), chunks=True)
with torch.no_grad():
for images, labels in tqdm(dataloader, total=total_iterations):
images = images.to(configs["device"])
# inference feature
with torch.autocast(device_type=configs["device"], dtype=torch.float16):
features = model(images).cpu().numpy()
labels = labels.cpu().numpy()
# add data
dset_features.resize(dset_features.shape[0] + features.shape[0], axis=0)
dset_features[-features.shape[0]:] = features
dset_labels.resize(dset_labels.shape[0] + labels.shape[0], axis=0)
dset_labels[-labels.shape[0]:] = labels
torch.cuda.empty_cache()
print(f"Features and labels have been saved to {output_file}.")
# define fuction that load feats and labels
def get_feats_labels(hdf5_file_path, mode="train", batch_size=32):
dataset = HDF5Dataset(hdf5_file_path)
shuffle = mode=="train"
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle)
feats_list = []
labels_list = []
for feats, labels in dataloader:
feats_list.append(feats.numpy())
labels_list.append(labels.numpy())
all_feats = np.concatenate(feats_list, axis=0)
all_labels = np.concatenate(labels_list, axis=0)
all_feats = torch.tensor(all_feats, dtype=torch.float32)
all_labels = torch.tensor(all_labels, dtype=torch.long)
return all_feats, all_labels
# training and evaluation
def train_eval(train_feats, train_labels, test_feats, test_labels):
global configs
# define model, train, evaluation
if configs["eval_name"] == "logreg":
model = LogisticRegression(C=configs["cost"], max_iter=configs["max_iter"])
model.fit(train_feats, train_labels)
pred = model.predict(test_feats)
if configs["eval_name"] == "knn":
model = KNeighborsClassifier(n_neighbors=configs["k"])
model.fit(train_feats.numpy(), train_labels.numpy())
pred = model.predict(test_feats.numpy())
test_labels = test_labels.numpy()
if configs["eval_name"] == "proto":
unique_labels = sorted(np.unique(train_labels.numpy()))
feats_proto = torch.vstack([
train_feats[train_labels == c].mean(dim=0) for c in unique_labels
])
labels_proto = torch.tensor(unique_labels)
pw_dist = (test_feats[:, None] - feats_proto[None, :]).norm(dim=-1, p=2)
pred = labels_proto[pw_dist.argmin(dim=1)]
# result
acc = accuracy_score(test_labels, pred)
balanced_acc = balanced_accuracy_score(test_labels, pred)
print(f"Accuracy = {acc:.3f}, Balanced Accuracy = {balanced_acc:.3f}")
if __name__ == "__main__":
main()
|