File size: 4,218 Bytes
813c1b9 | 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 | import torchvision.transforms as transforms
import numpy as np
from pathlib import Path
from torch.utils.data import Dataset
import os
import torch
import numpy as np
def minmax_to_unit(img):
"""Stretch one image to [0, 1] using its own min and max.
This is step one of the two-step normalization; step two is
diffusion_transforms, which maps [0, 1] -> [-1, 1]. It is idempotent, so
it is safe to leave on for data that was already normalized offline.
"""
lo, hi = img.min(), img.max()
rng = hi - lo
if rng <= 0:
return torch.zeros_like(img)
return (img - lo) / rng
class DiffusionDataset(Dataset):
def __init__(self, data_dir, transform=None, normalize=True):
self.data_dir = data_dir
self.transform = transform
self.normalize = normalize
self.samples = []
self.class_to_idx = {}
for idx, class_name in enumerate(sorted(os.listdir(data_dir))):
class_path = os.path.join(data_dir, class_name)
if os.path.isdir(class_path):
self.class_to_idx[class_name] = idx
for npy_file in os.listdir(class_path):
if npy_file.endswith('.npy'):
self.samples.append((os.path.join(class_path, npy_file), idx))
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
path, class_idx = self.samples[idx]
data = np.load(path)
data = torch.from_numpy(data).float().unsqueeze(0) # 1, 64, 64
if self.normalize:
data = minmax_to_unit(data)
if self.transform:
data = self.transform(data)
return data, class_idx
class VariableDataset(Dataset):
def __init__(self, root_dir, transform=None, normalize=True):
self.root_dir = root_dir
self.transform = transform
self.normalize = normalize
self.file_paths = []
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.npy'):
self.file_paths.append(os.path.join(root, file))
def __len__(self):
return len(self.file_paths)
def __getitem__(self, idx):
npy_path = self.file_paths[idx]
data = np.load(npy_path, allow_pickle=True)
image = data[0]
variables = data[1:5].astype(np.float32)
image = torch.from_numpy(image).float().unsqueeze(0) # 1, 64, 64
variables = torch.from_numpy(variables).float()
if self.normalize:
image = minmax_to_unit(image)
if self.transform:
image = self.transform(image)
return image, variables, npy_path
class ClassifierDataset(Dataset):
def __init__(self, file_paths, labels, transform=None, normalize=True):
self.file_paths = file_paths
self.labels = labels
self.transform = transform
self.normalize = normalize
def __len__(self):
return len(self.file_paths)
def __getitem__(self, idx):
img = np.load(self.file_paths[idx])
img = torch.FloatTensor(img).unsqueeze(0)
if self.normalize:
img = minmax_to_unit(img)
if self.transform:
img = self.transform(img)
return img, self.labels[idx]
class RegressionDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
image, *targets = self.data[idx]
image = torch.tensor(image, dtype=torch.float32).unsqueeze(0)
target = torch.tensor(targets, dtype=torch.float32) # (4,)
return image, target
diffusion_transforms = transforms.Compose([
transforms.Normalize((0.5,), (0.5,)) # Normalize to [-1, 1]
])
def classifier_transforms():
train_transform = transforms.Compose([
transforms.RandomRotation(degrees=15),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomErasing(p=0.5, scale=(0.02, 0.1), ratio=(0.3, 3.3))
])
val_transform = None
return train_transform, val_transform
|