Skip to content

Commit d813d0a

Browse files
1 parent 62e7625 commit d813d0a

5 files changed

Lines changed: 36 additions & 112 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ Before diving into waveform vector exploitation with WAVE, ensure your environme
3131
```bash
3232
python -m pip install -U -r requirements.txt
3333
```
34+
3435
- `numpy`
3536
- `scipy`
3637
- `torch`

gcp/wave_pytorch_gcp.py

Lines changed: 10 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,15 @@
44
import os
55
import time
66

7+
import numpy as np
78
import scipy.io
89
import torch
9-
import numpy as np
1010

1111
from utils.utils import normalize, splitdata, stdpt
1212

1313
# set printoptions
1414
torch.set_printoptions(linewidth=320, precision=8)
15-
np.set_printoptions(
16-
linewidth=320, formatter={"float_kind": "{:11.5g}".format}
17-
) # format short g, %precision=5
15+
np.set_printoptions(linewidth=320, formatter={"float_kind": "{:11.5g}".format}) # format short g, %precision=5
1816

1917
pathd = "data/"
2018
pathr = "results/"
@@ -33,17 +31,11 @@ def runexample(H, model, str, lr=0.001, amsgrad=False):
3331

3432
cuda = torch.cuda.is_available()
3533
os.makedirs(f"{pathr}models", exist_ok=True)
36-
name = (
37-
f"{data[:-4]}{H[:]}{lr:g}lr{str}".replace(", ", ".")
38-
.replace("[", "_")
39-
.replace("]", "_")
40-
)
34+
name = f"{data[:-4]}{H[:]}{lr:g}lr{str}".replace(", ", ".").replace("[", "_").replace("]", "_")
4135

4236
tica = time.time()
4337
device = torch.device("cuda:0" if cuda else "cpu")
44-
print(
45-
f"Running {name} on {device.type}\n{torch.cuda.get_device_properties(0) if cuda else ''}"
46-
)
38+
print(f"Running {name} on {device.type}\n{torch.cuda.get_device_properties(0) if cuda else ''}")
4739

4840
if not os.path.isfile(pathd + data):
4941
os.system(f"wget -P data/ https://storage.googleapis.com/ultralytics/{data}")
@@ -56,9 +48,7 @@ def runexample(H, model, str, lr=0.001, amsgrad=False):
5648
x, _, _ = normalize(x, 1) # normalize each input row
5749
y, _ymu, ys = normalize(y, 0) # normalize each output column
5850
x, y = torch.Tensor(x), torch.Tensor(y)
59-
x, y, xv, yv, xt, yt = splitdata(
60-
x, y, train=0.70, validate=0.15, test=0.15, shuffle=True
61-
)
51+
x, y, xv, yv, xt, yt = splitdata(x, y, train=0.70, validate=0.15, test=0.15, shuffle=True)
6252
labels = ["train", "validate", "test"]
6353

6454
print(model)
@@ -102,17 +92,12 @@ def runexample(H, model, str, lr=0.001, amsgrad=False):
10292
loss.backward()
10393
optimizer.step()
10494
else:
105-
print(
106-
"WARNING: Validation loss still decreasing after %g epochs (train longer)."
107-
% (i + 1)
108-
)
95+
print("WARNING: Validation loss still decreasing after %g epochs (train longer)." % (i + 1))
10996
# torch.save(best[2], pathr + 'models/' + name + '.pt')
11097
model.load_state_dict(best[2])
11198
dt = time.time() - tica
11299

113-
print(
114-
f"\nFinished {i + 1:g} epochs in {dt:.3f}s ({i / dt:.3f} epochs/s)\nBest results from epoch {best[0]:g}:"
115-
)
100+
print(f"\nFinished {i + 1:g} epochs in {dt:.3f}s ({i / dt:.3f} epochs/s)\nBest results from epoch {best[0]:g}:")
116101
loss, std = np.zeros(3), np.zeros((3, ny))
117102
for i, (xi, yi) in enumerate(((x, y), (xv, yv), (xt, yt))):
118103
loss[i], std[i] = stdpt(model(xi) - yi, ys)
@@ -225,15 +210,12 @@ def forward(self, x):
225210

226211

227212
def tslr(): # TS learning rate
228-
"""Generate and save learning rate (LR) logs for time-series models with varying LRs using WAVE and TanH
229-
activation.
213+
"""Generate and save learning rate (LR) logs for time-series models with varying LRs using WAVE and TanH activation.
230214
"""
231215
tsv = np.logspace(-5, -2, 13)
232216
tsy = []
233217
for a in tsv:
234-
tsy.extend(
235-
runexample(H, model=WAVE(H), str=("." + "Tanh"), lr=a) for _ in range(10)
236-
)
218+
tsy.extend(runexample(H, model=WAVE(H), str=("." + "Tanh"), lr=a) for _ in range(10))
237219
scipy.io.savemat(f"{pathr}TS.lr.mat", dict(tsv=tsv, tsy=np.array(tsy)))
238220

239221

@@ -242,10 +224,7 @@ def tsams(): # TS AMSgrad
242224
tsv = [False, True]
243225
tsy = []
244226
for a in tsv:
245-
tsy.extend(
246-
runexample(H, model=WAVE(H), str=f".TanhAMS{a!s}", amsgrad=a)
247-
for _ in range(3)
248-
)
227+
tsy.extend(runexample(H, model=WAVE(H), str=f".TanhAMS{a!s}", amsgrad=a) for _ in range(3))
249228
scipy.io.savemat(f"{pathr}TS.AMSgrad.mat", dict(tsv=tsv, tsy=np.array(tsy)))
250229

251230

train.py

Lines changed: 10 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,7 @@ def train(H, model, str, lr=0.001):
2727

2828
cuda = torch.cuda.is_available()
2929
os.makedirs(f"{pathr}models", exist_ok=True)
30-
name = (
31-
f"{data[:-4]}{H[:]}{lr:g}lr{str}".replace(", ", ".")
32-
.replace("[", "_")
33-
.replace("]", "_")
34-
)
30+
name = f"{data[:-4]}{H[:]}{lr:g}lr{str}".replace(", ", ".").replace("[", "_").replace("]", "_")
3531
print(f"Running {name}")
3632

3733
device = select_device()
@@ -47,9 +43,7 @@ def train(H, model, str, lr=0.001):
4743
x, _, _ = normalize(x, 1) # normalize each input row
4844
y, _ymu, ys = normalize(y, 0) # normalize each output column
4945
x, y = torch.Tensor(x), torch.Tensor(y)
50-
x, y, xv, yv, xt, yt = splitdata(
51-
x, y, train=0.70, validate=0.15, test=0.15, shuffle=False
52-
)
46+
x, y, xv, yv, xt, yt = splitdata(x, y, train=0.70, validate=0.15, test=0.15, shuffle=False)
5347

5448
# torch.nn.init.constant_(model.out.weight.data, ys.item(0))
5549
# torch.nn.init.constant_(model.out.bias.data, ymu.item(0))
@@ -160,24 +154,18 @@ def __init__(self, n_out=2):
160154
"""Initializes the WAVE4 model with specified output layers and configurations for convolutional layers."""
161155
super().__init__()
162156
self.layer1 = nn.Sequential(
163-
nn.Conv2d(
164-
1, 32, kernel_size=(1, 9), stride=(1, 2), padding=(0, 4), bias=False
165-
),
157+
nn.Conv2d(1, 32, kernel_size=(1, 9), stride=(1, 2), padding=(0, 4), bias=False),
166158
nn.BatchNorm2d(32),
167159
nn.LeakyReLU(0.1),
168160
)
169161
# nn.MaxPool2d(kernel_size=(1, 2), stride=1))
170162
self.layer2 = nn.Sequential(
171-
nn.Conv2d(
172-
32, 64, kernel_size=(1, 9), stride=(1, 2), padding=(0, 4), bias=False
173-
),
163+
nn.Conv2d(32, 64, kernel_size=(1, 9), stride=(1, 2), padding=(0, 4), bias=False),
174164
nn.BatchNorm2d(64),
175165
nn.LeakyReLU(0.1),
176166
)
177167
# nn.MaxPool2d(kernel_size=(1, 2), stride=1))
178-
self.layer3 = nn.Conv2d(
179-
64, n_out, kernel_size=(2, 64), stride=(1, 1), padding=(0, 0)
180-
)
168+
self.layer3 = nn.Conv2d(64, n_out, kernel_size=(2, 64), stride=(1, 1), padding=(0, 0))
181169

182170
def forward(self, x): # x.shape = [bs, 512]
183171
"""Forward pass for processing input tensor through convolutional layers and reshaping output for
@@ -263,24 +251,18 @@ def __init__(self, n_out=2):
263251
"""Initializes the WAVE2 model architecture components."""
264252
super().__init__()
265253
self.layer1 = nn.Sequential(
266-
nn.Conv2d(
267-
1, 32, kernel_size=(2, 30), stride=(1, 2), padding=(1, 15), bias=False
268-
),
254+
nn.Conv2d(1, 32, kernel_size=(2, 30), stride=(1, 2), padding=(1, 15), bias=False),
269255
nn.BatchNorm2d(32),
270256
nn.LeakyReLU(0.1),
271257
nn.MaxPool2d(kernel_size=(1, 2), stride=1),
272258
)
273259
self.layer2 = nn.Sequential(
274-
nn.Conv2d(
275-
32, 64, kernel_size=(2, 30), stride=(1, 2), padding=(0, 15), bias=False
276-
),
260+
nn.Conv2d(32, 64, kernel_size=(2, 30), stride=(1, 2), padding=(0, 15), bias=False),
277261
nn.BatchNorm2d(64),
278262
nn.LeakyReLU(0.1),
279263
nn.MaxPool2d(kernel_size=(1, 2), stride=1),
280264
)
281-
self.layer3 = nn.Sequential(
282-
nn.Conv2d(64, n_out, kernel_size=(2, 64), stride=(1, 1), padding=(0, 0))
283-
)
265+
self.layer3 = nn.Sequential(nn.Conv2d(64, n_out, kernel_size=(2, 64), stride=(1, 1), padding=(0, 0)))
284266

285267
def forward(self, x): # x.shape = [bs, 512]
286268
"""Forward pass for processing input tensor x through sequential layers, reshaping as needed for the model."""
@@ -297,12 +279,8 @@ def forward(self, x): # x.shape = [bs, 512]
297279
if __name__ == "__main__":
298280
parser = argparse.ArgumentParser()
299281
parser.add_argument("--epochs", type=int, default=5000, help="number of epochs")
300-
parser.add_argument(
301-
"--batch-size", type=int, default=2000, help="size of each image batch"
302-
)
303-
parser.add_argument(
304-
"--printerval", type=int, default=1, help="print results interval"
305-
)
282+
parser.add_argument("--batch-size", type=int, default=2000, help="size of each image batch")
283+
parser.add_argument("--printerval", type=int, default=1, help="print results interval")
306284
parser.add_argument("--var", nargs="+", default=[3], help="debug list")
307285
opt = parser.parse_args()
308286
opt.var = [float(x) for x in opt.var]

train_tf.py

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,7 @@ def runexample(H, model, str):
2828
tf.set_random_seed(1)
2929
path = "data/"
3030
os.makedirs(f"{path}models", exist_ok=True)
31-
name = (
32-
f"{data[:-4]}{H[:]}{lr:g}lr{eps:g}eps{str}".replace(", ", "_")
33-
.replace("[", "_")
34-
.replace("]", "_")
35-
)
31+
name = f"{data[:-4]}{H[:]}{lr:g}lr{eps:g}eps{str}".replace(", ", "_").replace("[", "_").replace("]", "_")
3632

3733
tica = time.time()
3834
device = "/gpu:0" if cuda else "/cpu:0"
@@ -50,9 +46,7 @@ def runexample(H, model, str):
5046
# model = WAVE(nx, ny, H)
5147
model = tf.keras.Sequential(
5248
[
53-
tf.keras.layers.Dense(
54-
H[0], activation=tf.tanh, input_shape=(512,)
55-
), # must declare input shape
49+
tf.keras.layers.Dense(H[0], activation=tf.tanh, input_shape=(512,)), # must declare input shape
5650
tf.keras.layers.Dense(H[1], activation=tf.tanh),
5751
tf.keras.layers.Dense(
5852
H[2],
@@ -64,9 +58,7 @@ def runexample(H, model, str):
6458

6559
x, _, _ = normalize(x, 1) # normalize each input row
6660
y, _ymu, ys = normalize(y, 0) # normalize each output column
67-
x, y, xv, yv, xt, yt = splitdata(
68-
x, y, train=0.70, validate=0.15, test=0.15, shuffle=False
69-
)
61+
x, y, xv, yv, xt, yt = splitdata(x, y, train=0.70, validate=0.15, test=0.15, shuffle=False)
7062
labels = ["train", "validate", "test"]
7163

7264
print(model)
@@ -91,9 +83,7 @@ def criteria(y_pred, y): # MSE
9183
with tf.GradientTape() as tape:
9284
y_pred = model(x)
9385
loss = criteria(y_pred, y)
94-
grads = tape.gradient(
95-
loss, model.variables
96-
) # DO NOT INDENT, not inside tf.GradientTape context manager
86+
grads = tape.gradient(loss, model.variables) # DO NOT INDENT, not inside tf.GradientTape context manager
9787
y_predv = model(xv)
9888

9989
# Compute and print loss
@@ -105,9 +95,7 @@ def criteria(y_pred, y): # MSE
10595
if L[i, 1] < best[1]:
10696
best = (i, L[i, 1], None)
10797
if (i - best[0]) > validations:
108-
print(
109-
f"\n{validations:g} validation checks exceeded at epoch {i:g}."
110-
)
98+
print(f"\n{validations:g} validation checks exceeded at epoch {i:g}.")
11199
break
112100

113101
if i % printInterval == 0: # print and save progress
@@ -122,17 +110,12 @@ def criteria(y_pred, y): # MSE
122110
global_step=tf.train.get_or_create_global_step(),
123111
)
124112
else:
125-
print(
126-
"WARNING: Validation loss still decreasing after %g epochs (train longer)."
127-
% (i + 1)
128-
)
113+
print("WARNING: Validation loss still decreasing after %g epochs (train longer)." % (i + 1))
129114
# torch.save(best[2], path + 'models/' + name + '.pt')
130115
# model.load_state_dict(best[2])
131116
dt = time.time() - tica
132117

133-
print(
134-
f"\nFinished {i + 1:g} epochs in {dt:.3f}s ({i / dt:.3f} epochs/s)\nBest results from epoch {best[0]:g}:"
135-
)
118+
print(f"\nFinished {i + 1:g} epochs in {dt:.3f}s ({i / dt:.3f} epochs/s)\nBest results from epoch {best[0]:g}:")
136119
loss, std = np.zeros(3), np.zeros((3, ny))
137120
for i, (xi, yi) in enumerate(((x, y), (xv, yv), (xt, yt))):
138121
loss[i], std[i] = stdtf(model(xi) - yi, ys)
@@ -142,9 +125,7 @@ def criteria(y_pred, y): # MSE
142125

143126
data = []
144127
for i, s in enumerate(labels):
145-
data.append(
146-
go.Scatter(x=np.arange(epochs), y=L[:, i], mode="markers+lines", name=s)
147-
)
128+
data.append(go.Scatter(x=np.arange(epochs), y=L[:, i], mode="markers+lines", name=s))
148129
layout = go.Layout(
149130
xaxis=dict(type="linear", autorange=True),
150131
yaxis=dict(type="log", autorange=True),

utils/utils.py

Lines changed: 7 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@
88

99
# Set printoptions
1010
torch.set_printoptions(linewidth=1320, precision=5, profile="long")
11-
np.set_printoptions(
12-
linewidth=320, formatter={"float_kind": "{:11.5g}".format}
13-
) # format short g, %precision=5
11+
np.set_printoptions(linewidth=320, formatter={"float_kind": "{:11.5g}".format}) # format short g, %precision=5
1412

1513

1614
def normalize(x, axis=None): # normalize x mean and std by axis
@@ -32,9 +30,7 @@ def shuffledata(x, y): # randomly shuffle x and y by same axis=0 indices
3230
return x[i], y[i]
3331

3432

35-
def splitdata(
36-
x, y, train=0.7, validate=0.15, test=0.15, shuffle=False
37-
): # split training data
33+
def splitdata(x, y, train=0.7, validate=0.15, test=0.15, shuffle=False): # split training data
3834
"""Splits data arrays x and y into training, validation, and test sets with optional shuffling."""
3935
n = x.shape[0]
4036
if shuffle:
@@ -73,13 +69,8 @@ def model_info(model):
7369
shape, mean, and std.
7470
"""
7571
n_p = sum(x.numel() for x in model.parameters()) # number parameters
76-
n_g = sum(
77-
x.numel() for x in model.parameters() if x.requires_grad
78-
) # number gradients
79-
print(
80-
"\n%5s %40s %9s %12s %20s %10s %10s"
81-
% ("layer", "name", "gradient", "parameters", "shape", "mu", "sigma")
82-
)
72+
n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
73+
print("\n%5s %40s %9s %12s %20s %10s %10s" % ("layer", "name", "gradient", "parameters", "shape", "mu", "sigma"))
8374
for i, (name, p) in enumerate(model.named_parameters()):
8475
name = name.replace("module_list.", "")
8576
print(
@@ -119,9 +110,7 @@ def step(self, loss, metrics=None, model=None):
119110
self.num_bad_epochs += 1
120111
self.epoch += 1
121112
self.first(model) if self.epoch == 0 else None
122-
self.printepoch(
123-
self.epoch, loss, metrics
124-
) if self.epoch % self.printerval == 0 else None
113+
self.printepoch(self.epoch, loss, metrics) if self.epoch % self.printerval == 0 else None
125114

126115
if loss < self.bestloss:
127116
self.bestloss = loss
@@ -130,19 +119,15 @@ def step(self, loss, metrics=None, model=None):
130119
self.num_bad_epochs = 0
131120
if model:
132121
if self.bestmodel:
133-
self.bestmodel.load_state_dict(
134-
model.state_dict()
135-
) # faster than deepcopy
122+
self.bestmodel.load_state_dict(model.state_dict()) # faster than deepcopy
136123
else:
137124
self.bestmodel = copy.deepcopy(model)
138125

139126
if self.num_bad_epochs > self.patience:
140127
self.final(f"{self.patience:g} Patience exceeded at epoch {self.epoch:g}.")
141128
return True
142129
elif self.epoch >= self.epochs:
143-
self.final(
144-
f"WARNING: {self.patience:g} Patience not exceeded by epoch {self.epoch:g} (train longer)."
145-
)
130+
self.final(f"WARNING: {self.patience:g} Patience not exceeded by epoch {self.epoch:g} (train longer).")
146131
return True
147132
else:
148133
return False

0 commit comments

Comments
 (0)