-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdataset.py
196 lines (147 loc) · 6.82 KB
/
dataset.py
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
import numpy as np
import torch
import torchvision.transforms as transforms
from torch.utils.data import Dataset, random_split, DataLoader
import torch.nn.functional as F
import tifffile
import pandas as pd
import torch.nn as nn
from pathlib import Path
from timm.data.parsers.parser import Parser
from PIL import ImageEnhance, Image
import matplotlib.pyplot as plt
from pathlib import Path
from timm.data import create_transform
from torchvision.utils import make_grid
from datamgr import *
import rasterio as rio
#from osgeo import gdal
import os
class Alps_meta(Dataset):
def __init__(self, args, meta_features):
#targets = list of species CD_REF , column names
self.data_path = Path(args.data_path)
self.data_df = pd.read_csv(args.file_path+'alps_env_data.csv', sep=',', low_memory=False)
self.meta_features = meta_features
self.meta_stats = torch.load(args.file_path+'stats_meta.pth')
def __len__(self):
return len(self.data_df)
def __getitem__(self, idx):
row = self.data_df.iloc[idx]
coord = torch.tensor(row[['X', 'Y']]).float()
data = torch.tensor(row[self.meta_features]).float()
data = (data - self.meta_stats['mean'][:-1]) / self.meta_stats['std'][:-1]
return coord, data
class CBNA(Dataset):
def __init__(self, args, split='train', meta_features=None, transform=None):
#targets = list of species CD_REF , column names
self.data_path = Path(args.data_path)
if split == 'train':
self.data_df = pd.read_csv(args.file_path+'{}_w_covariates_final.csv'.format(split), sep=',', low_memory=False, dtype={'label': str})
else:
self.data_df = pd.read_csv(args.file_path+'{}_w_covariates.csv'.format(split), sep=',', low_memory=False, dtype={'label': str})
self.classes = args.classes
self.transform = transform
self.model_type = args.model_type
if meta_features is not None:
self.meta_features = meta_features
self.meta_stats = torch.load(args.file_path+'stats_meta.pth')
def __len__(self):
return len(self.data_df)
def __getitem__(self, idx):
row = self.data_df.iloc[idx]
img_id, target = row['id_img'], row['labelset']
if self.model_type == "CNN" or self.model_type == "ViT" or self.model_type == "Fusion":
data_path = self.data_path.joinpath('plot%s.tif'%(img_id))
image = tifffile.imread(data_path)
image = Image.fromarray(image.astype(np.uint8).transpose(1,2,0))
if self.transform:
image = self.transform(image)
if self.model_type == "Fusion":
data_meta = torch.tensor(self.data_df.iloc[idx][self.meta_features]).float()
#data_meta = (data_meta - self.meta_stats['mean'].squeeze(0)) / self.meta_stats['std'].squeeze(0)
data = (image, data_meta)
else:
data = image
elif self.model_type == "MLP":
data = torch.tensor(self.data_df.iloc[idx][self.meta_features]).float()
data = (data - self.meta_stats['mean']) / self.meta_stats['std']
return data, self.encode(target)
def get_cdref(self, idx):
row = self.data_df.iloc[idx]
cd_ref = row['labelset']
#print('cd_ref for the index {}: '.format(idx), list(map(float, cd_ref.split(','))))
return list(map(float, cd_ref.split(',')))
def get_species(self, idx, cdref2species):
cdref = self.get_cdref(idx)
species = []
for ref in cdref:
temp = cdref2species.loc[cdref2species.cd_ref==ref]
species.append(temp.nom_reconnu.values[0])
return species
def encode(self, target):
num_cls = len(self.classes)
vec = torch.zeros(num_cls)
label_list = target.split(',')
for l in label_list:
idx = self.classes.index(l)
vec[idx] = 1
return vec
def decode(self, output, threshold=0.5):
idx = (output >= threshold).nonzero().flatten()
cdref = []
for i in idx.tolist():
cdref.append(self.classes[i])
return ','.join(cdref)
def get_label_count(self):
num_cls = len(self.classes)
init_values = [0] * num_cls
label_cnt = dict(zip(self.classes, init_values))
labelset_arrays = self.data_df.labelset.values
for i in range(len(labelset_arrays)):
labelset = labelset_arrays[i].split(',')
for label in labelset:
label_cnt[label] += 1
return label_cnt
def show_sample(self, idx):
row = self.data_df.iloc[idx]
img_id, target = row['id_img'], row['labelset']
data_path = self.data_path.joinpath('plot%s.tif'%(img_id))
image = tifffile.imread(data_path)
image = Image.fromarray(image.astype(np.uint8).transpose(1,2,0))
plt.imshow(image)
print(target)
return image
def show_batch(self, data_loader, n):
j = 0
for images, targets in data_loader:
j = j + 1
if j == n:
# print(images.var(dim=(1,2,3)))
fig, ax = plt.subplots(figsize=(16, 8))
ax.set_xticks([]); ax.set_yticks([])
ax.imshow(make_grid(images, nrow=16).permute(1, 2, 0))
break
else:
continue
def build_dataset(args, is_train=True):
if args.data_set == 'CBNA':
meta_features = None
if args.model_type=="MLP" or args.model_type=="Fusion":
meta_features = ['LANDOLT_MOIST',
'N_prct', 'pH', 'CN', 'TMeanY', 'TSeason', 'PTotY', 'PSeason', 'RTotY',
'RSeason', 'AMPL', 'LENGTH', 'eauvive', 'clay', 'silt', 'sand', 'cv_alti']
if is_train:
if args.model_type=="MLP":
dataset_train = CBNA(args, split='train', meta_features=meta_features)
dataset_val = CBNA(args, split='val', meta_features=meta_features)
else:
dataset_train = CBNA(args, split='train', meta_features=meta_features, transform=build_transform(args, aug=True))
dataset_val = CBNA(args, split='val', meta_features=meta_features, transform=build_transform(args, aug=False))
return dataset_train, dataset_val
else:
if args.model_type=="MLP":
dataset_test = CBNA(args, split='test', meta_features=meta_features)
else:
dataset_test = CBNA(args, split='test', meta_features=meta_features, transform=build_transform(args, aug=False))
return dataset_test