-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
165 lines (135 loc) · 5.47 KB
/
train.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
import os
from pathlib import Path
import numpy as np
import scipy.fft
from scipy.signal import windows
import matplotlib.pyplot as plt
import h5py
from utils.models import UNet
from utils.models import CallBacks
from random import choice
import tensorflow as tf
import argparse
from utils.models import DataGenerator
from datetime import datetime
import json
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION']='.10'
def train(opt):
""" Variables necesarias """
cwd = os.getcwd()
datadir = os.path.join(cwd, opt.data_dir)
kerneldir = os.path.join(cwd, opt.kernel_dir)
data_file = os.path.join(datadir, "DAS_data.h5")
samp = 50.
epochs = opt.epochs
batch_size = opt.batch_size
""" Load DAS data """
# DAS_data.h5 -> datos para leer (1.5GB) strain rate -> hay que integrarlos
with h5py.File(data_file, "r") as f:
# Nch : numero de canales, Nt = largo de muestras 8.626.100
Nch, Nt = f["strainrate"].shape
split = int(0.9 * Nt) #90% datos para entrenamiento y validación
data = f["strainrate"][:, 0:split].astype(np.float32)
# se normaliza cada trace respecto a su desviación estandar
data /= data.std()
Nch, Nt = data.shape
# Shape: 24 x 180_000 (son 24 sensores/canales, y 180_000 muestras?)
""" Integrate DAS data (strain rate -> strain) """
win = windows.tukey(Nt, alpha=0.1)
freqs = scipy.fft.rfftfreq(Nt, d=1/samp)
Y = scipy.fft.rfft(win * data, axis=1)
Y_int = -Y / (2j * np.pi * freqs)
Y_int[:, 0] = 0
data_int = scipy.fft.irfft(Y_int, axis=1)
data_int /= data_int.std()
""" Call DataGenerator """
window = opt.deep_win
samples_per_epoch = 1000 # data que se espera por epoca al entrenar
batches = opt.batch_size
train_val_ratio = 0.5
_, Nt_int = data_int.shape
split = int(0.5 * Nt_int)
train_raw_data = data_int[:,0:split]
val_raw_data = data_int[:,split:]
train_data = DataGenerator(train_raw_data, window, samples_per_epoch, batches)
val_data = DataGenerator(val_raw_data, window, samples_per_epoch, batches)
########################################3
""" Load impulse response """
#kernel = np.load(os.path.join(datadir, "kernel.npy"))
kernel = np.load(os.path.join(kerneldir,"i_kernel.npy")) # integrado
# Se normaliza el kernel respecto al máximo (a diferencia de las traces DAS que se normalizan respecto a la desviación estandar)
kernel = kernel / kernel.max()
""" Some model parameters """
rho = 10.0
f0 = 8
blocks = 3
dropout_value = opt.dropout
deep_win = opt.deep_win
""" Init Deep Learning model """
model = UNet(
kernel.astype(np.float32), lam=rho, f0=f0,
data_shape=(Nch, deep_win, 1), blocks=blocks, AA=False, bn=False, dropout=dropout_value
)
model.construct()
model.compile()
checkpoint_filepath = str(str(Path(__file__).parent) +opt.checkpoint)
model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=checkpoint_filepath,
save_weights_only=True,
monitor='val_loss',
mode='auto',
save_best_only=True,
update_freq="epoch")
history = model.fit(
train_data,
validation_data=val_data,
epochs=epochs,
callbacks=[model_checkpoint_callback],
batch_size=batch_size
)
timeID = datetime.now()
timeString = timeID.strftime("%Y-%m-%d_%H-%M-%S")
file_prefix = 'train_{}.json'.format(timeString)
with open(os.path.join('trainHistory/',file_prefix), 'w') as file:
json.dump(history.history, file)
""" Printear algunas cosas para ver como se entreno """
loss1 = history.history['l1']
val_loss1 = history.history['val_l1']
loss2 = history.history['l2']
val_loss2 = history.history['val_l2']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)#epochs
plt.figure(figsize=(8, 8))
plt.subplot(3, 1, 1)
plt.plot(epochs_range, loss1, label='Training Sparsity (L1)')
plt.plot(epochs_range, val_loss1, label='Validation Sparsity (L1)')
plt.legend(loc='lower right')
plt.title('Training and Validation Sparsity')
plt.subplot(3, 1, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Total Loss')
plt.subplot(3, 1, 3)
plt.plot(epochs_range, loss2, label='Training Loss (L2)')
plt.plot(epochs_range, val_loss2, label='Validation Loss (L2)')
plt.legend(loc='lower right')
plt.title('Training and Validation Loss (L2)')
plt.show()
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', default = 128, type=int,help='batch size to train')
parser.add_argument('--epochs', default = 200 ,type=int,help='epoch to train')
parser.add_argument('--data_dir', default = "data",type=str,help='dir to the dataset')
parser.add_argument('--kernel_dir', default = "kernels",type=str,help='dir to the dataset')
parser.add_argument('--checkpoint', default = "/checkpoints/best.ckpt",type=str,help='dir to save the weights og the training')
parser.add_argument('--dropout', default = 1.0,type=float,help='percentage dropout to use')
parser.add_argument('--deep_win', default = 1024,type=int,help='Number of samples per chunk')
opt = parser.parse_args()
return opt
def main(opt):
train(opt)
if __name__ == '__main__':
opt = parse_opt()
main(opt)