/
utils.py
184 lines (152 loc) · 5.08 KB
/
utils.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
from torch.utils.data import Dataset
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, WeightedRandomSampler
import torch
import numpy as np
from IPython.display import clear_output
class TorchDataset(Dataset):
"""
Format for numpy array
Parameters
----------
X: 2D array
The input matrix
y: 2D array
The one-hot encoded target
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return len(self.x)
def __getitem__(self, index):
x, y = self.x[index], self.y[index]
return x, y
class PredictDataset(Dataset):
"""
Format for numpy array
Parameters
----------
X: 2D array
The input matrix
"""
def __init__(self, x):
self.x = x
def __len__(self):
return len(self.x)
def __getitem__(self, index):
x = self.x[index]
return x
def create_dataloaders(X_train, y_train, X_valid, y_valid, weights, batch_size):
"""
Create dataloaders with or wihtout subsampling depending on weights and balanced.
Parameters
----------
X_train: np.ndarray
Training data
y_train: np.array
Mapped Training targets
X_valid: np.ndarray
Validation data
y_valid: np.array
Mapped Validation targets
weights : dictionnary or bool
Weight for each mapped target class
0 for no sampling
1 for balanced sampling
Returns
-------
train_dataloader, valid_dataloader : torch.DataLoader, torch.DataLoader
Training and validation dataloaders
"""
if weights == 0:
train_dataloader = DataLoader(TorchDataset(X_train, y_train),
batch_size=batch_size, shuffle=True)
else:
if weights == 1:
class_sample_count = np.array(
[len(np.where(y_train == t)[0]) for t in np.unique(y_train)])
weights = 1. / class_sample_count
samples_weight = np.array([weights[t] for t in y_train])
samples_weight = torch.from_numpy(samples_weight)
samples_weight = samples_weight.double()
else:
# custom weights
samples_weight = np.array([weights[t] for t in y_train])
sampler = WeightedRandomSampler(samples_weight, len(samples_weight))
train_dataloader = DataLoader(TorchDataset(X_train, y_train),
batch_size=batch_size, sampler=sampler)
valid_dataloader = DataLoader(TorchDataset(X_valid, y_valid),
batch_size=batch_size, shuffle=False)
return train_dataloader, valid_dataloader
def plot_losses(losses_train, losses_valid, metrics_train, metrics_valid):
"""
Plot train and validation losses.
Parameters
----------
losses_train : list
list of train losses per epoch
losses_valid : list
list of valid losses per epoch
metrics_train : list
list of train metrics per epoch
metrics_valid : list
list of valid metrics per epoch
Returns
------
plot
"""
clear_output()
plt.figure(figsize=(15, 5))
plt.subplot(1, 2, 1)
plt.plot(range(len(losses_train)), losses_train, label='Train')
plt.plot(range(len(losses_valid)), losses_valid, label='Valid')
plt.grid()
plt.title('Losses')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(range(len(metrics_train)), metrics_train, label='Train')
plt.plot(range(len(metrics_valid)), metrics_valid, label='Valid')
plt.grid()
plt.title('Training Metrics')
plt.legend()
plt.show()
def create_explain_matrix(input_dim, cat_emb_dim, cat_idxs, post_embed_dim):
"""
This is a computational trick.
In order to rapidly sum importances from same embeddings
to the initial index.
Parameters
----------
input_dim: int
Initial input dim
cat_emb_dim : int or list of int
if int : size of embedding for all categorical feature
if list of int : size of embedding for each categorical feature
cat_idxs : list of int
Initial position of categorical features
post_embed_dim : int
Post embedding inputs dimension
Returns
-------
reducing_matrix : np.array
Matrix of dim (post_embed_dim, input_dim) to performe reduce
"""
if isinstance(cat_emb_dim, int):
all_emb_impact = [cat_emb_dim-1]*len(cat_idxs)
else:
all_emb_impact = [emb_dim-1 for emb_dim in cat_emb_dim]
acc_emb = 0
nb_emb = 0
indices_trick = []
for i in range(input_dim):
if i not in cat_idxs:
indices_trick.append([i+acc_emb])
else:
indices_trick.append(range(i+acc_emb, i+acc_emb+all_emb_impact[nb_emb]+1))
acc_emb += all_emb_impact[nb_emb]
nb_emb += 1
reducing_matrix = np.zeros((post_embed_dim, input_dim))
for i, cols in enumerate(indices_trick):
reducing_matrix[cols, i] = 1
return reducing_matrix