-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmain.py
More file actions
357 lines (302 loc) · 12.1 KB
/
main.py
File metadata and controls
357 lines (302 loc) · 12.1 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#!/usr/bin/env python
# coding: utf-8
# Import header files
import math
import argparse
import torch
from torch import autograd
import torch.nn as nn
import torch.nn.functional as F
import matplotlib
import sys
import numpy as np
import pylab
from matplotlib import pyplot as plt
import time
import sys
from models.sru import SRU, trainSRU
from models.eSRU_1LF import eSRU_1LF, train_eSRU_1LF
from models.eSRU_2LF import eSRU_2LF, train_eSRU_2LF
from utils.utilFuncs import env_config, loadTrainingData, loadTrueNetwork, getCausalNodes, count_parameters, getGeneTrainingData
# Read input command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--device', type=str, default='cuda:3',
help='device, default: cuda:3')
parser.add_argument('--dataset', type=str, default='VAR',
help='dataset type, default: VAR')
parser.add_argument('--dsid', type=int, default=1,
help='dataset id, default: 1')
parser.add_argument('--T', type=int, default=10,
help='training size, default: 10')
parser.add_argument('--F', type=int, default=10,
help='chaos, default: 10')
parser.add_argument('--n', type=int, default=10,
help='num of timeseries, default: 10')
parser.add_argument('--model', type=str, default='sru',
help='[sru, gru, lstm]: select your model')
parser.add_argument('--nepochs', type=int, default=500,
help='sets max_iter, default: 500')
parser.add_argument('--mu1', type=float, default=1,
help='sets mu1 parameter, default: 1')
parser.add_argument('--mu2', type=float, default=1,
help='sets mu2 parameter, default: 1')
parser.add_argument('--mu3', type=float, default=1,
help='sets mu3 parameter, default: 1')
parser.add_argument('--lr', type=float, default=0.005,
help='sets learning rate, default: 0.005')
parser.add_argument('--joblog', type=str, default="",
help='name of job logfile, default=""')
args = parser.parse_args()
deviceName = args.device
model_name = args.model
max_iter = args.nepochs
mu1 = args.mu1
mu2 = args.mu2
mu3 = args.mu3
dataset = args.dataset
dataset_id = args.dsid
T = args.T
F = args.F
n = args.n
lr = args.lr
jobLogFilename = args.joblog
###############################
# Global simulation settings
###############################
verbose = 0 # Verbosity level
#################################
# Pytorch environment
#################################
device, seed = env_config(True, deviceName) # true --> use GPU
print("Computational Resource: %s" % (device))
######################################
# Create input data in batch format
######################################
if(dataset == 'gene'):
Xtrain, Gref = getGeneTrainingData(dataset_id, device)
n1 = Xtrain.shape[0]
if(n != n1):
print("Error::Dimension mismatch for input training data..")
numTotalSamples = Xtrain.shape[1]
Xtrain = Xtrain.float().to(device)
# Make input signal zero mean and appropriately scaled
Xtrain = Xtrain - Xtrain.mean()
inputSignalMultiplier = 50
Xtrain = inputSignalMultiplier * Xtrain
elif(dataset == 'var'):
fileName = "data/var/S_%s_T_%s_dataset_%s.npz" % (F, T, dataset_id)
ld = np.load(fileName)
X_np = ld['X_np']
Gref = ld['Gref']
numTotalSamples = T
Xtrain = torch.from_numpy(X_np)
Xtrain = Xtrain.float().to(device)
inputSignalMultiplier = 1
Xtrain = inputSignalMultiplier * Xtrain
elif(dataset == 'lorenz'):
fileName = "data/lorenz96/F_%s_T_%s_dataset_%s.npz" % (F, T, dataset_id)
ld = np.load(fileName)
X_np = ld['X_np']
Gref = ld['Gref']
numTotalSamples = T
Xtrain = torch.from_numpy(X_np)
Xtrain = Xtrain.float().to(device)
inputSignalMultiplier = 1
Xtrain = inputSignalMultiplier * Xtrain
elif(dataset == 'netsim'):
fileName = "data/netsim/sim3_subject_%s.npz" % (dataset_id)
ld = np.load(fileName)
X_np = ld['X_np']
Gref = ld['Gref']
numTotalSamples = T
Xtrain = torch.from_numpy(X_np)
Xtrain = Xtrain.float().to(device)
inputSignalMultiplier = 1
Xtrain = inputSignalMultiplier * Xtrain
else:
print("Dataset is not supported")
if(verbose >= 1):
plt.figure(1)
plt.xlabel("t")
plt.ylabel("x0(t)")
plt.plot(range(numTotalSamples),Xtrain.cpu().numpy()[0][:])
plt.show(block=False)
plt.pause(0.1)
######################################
# SRU Cell parameters
######################################
#######################################
# Model training parameters
######################################
if(model_name == 'sru'):
lr_gamma = 0.99
lr_update_gap = 4
staggerTrainWin = 1
stoppingThresh = 1e-5;
trainVerboseLvl = 2
lr = lr
lambda1 = mu1
lambda2 = mu2
n_inp_channels = n
n_out_channels = 1
if(dataset == 'gene'):
A = [0.0, 0.01, 0.1, 0.5, 0.99]; #0.75
dim_iid_stats = 10 #math.ceil(n) #1.5n
dim_rec_stats = 10 #math.ceil(n) #1.5n
dim_final_stats = 10 #d * len(A) #math.ceil(n/2)
dim_rec_stats_feedback = 10 #d * len(A)
batchSize = 21
blk_size = batchSize
numBatches = int(numTotalSamples/batchSize)
elif(dataset == 'var'):
A = [0.0, 0.01, 0.1, 0.99];
dim_iid_stats = 10 #math.ceil(n) #1.5n
dim_rec_stats = 10 #math.ceil(n) #1.5n
dim_final_stats = 10 #d * len(A) #math.ceil(n/2) #n
dim_rec_stats_feedback = 10 #d * len(A) #math.ceil(n/2) #n
batchSize = 250
blk_size = int(batchSize/2)
numBatches = int(numTotalSamples/batchSize)
elif(dataset == 'lorenz'):
A = [0.0, 0.01, 0.1, 0.99];
dim_iid_stats = 10
dim_rec_stats = 10
dim_final_stats = 10
dim_rec_stats_feedback = 10
batchSize = 250
blk_size = int(batchSize/2)
numBatches = int(numTotalSamples/batchSize)
elif(dataset == 'netsim'):
A = [0.0, 0.01, 0.05, 0.1, 0.99];
dim_iid_stats = 10
dim_rec_stats = 10
dim_final_stats = 10
dim_rec_stats_feedback = 10
batchSize = 10 #100
blk_size = int(batchSize/2)
numBatches = int(numTotalSamples/batchSize)
else:
print("Unsupported dataset encountered")
elif(model_name == 'eSRU_1LF' or model_name == 'eSRU_2LF'):
lr_gamma = 0.99
lr_update_gap = 4
staggerTrainWin = 1
stoppingThresh = 1e-5;
trainVerboseLvl = 2
lr = lr
lambda1 = mu1
lambda2 = mu2
lambda3 = mu3
n_inp_channels = n
n_out_channels = 1
if(dataset == 'gene'):
A = [0.05, 0.1, 0.2, 0.99];
dim_iid_stats = 10
dim_rec_stats = 10
dim_final_stats = 10
dim_rec_stats_feedback = 10
batchSize = 21
blk_size = int(batchSize)
numBatches = int(numTotalSamples/batchSize)
elif(dataset == 'var'):
A = [0.0, 0.01, 0.1, 0.99];
dim_iid_stats = 10 #math.ceil(n) #1.5n
dim_rec_stats = 10 #math.ceil(n) #1.5n
dim_final_stats = 10 #d * len(A) #math.ceil(n/2) #n
dim_rec_stats_feedback = 10 #d * len(A) #math.ceil(n/2) #n
batchSize = 250
blk_size = int(batchSize/2)
numBatches = int(numTotalSamples/batchSize)
elif(dataset == 'lorenz'):
#lr = 0.01
A = [0.0, 0.01, 0.1, 0.99];
dim_iid_stats = 10
dim_rec_stats = 10
dim_final_stats = 10 #d*len(A)
dim_rec_stats_feedback = 10 #d*len(A)
batchSize = 250
blk_size = int(batchSize/2)
numBatches = int(numTotalSamples/batchSize)
elif(dataset == 'netsim'):
A = [0.0, 0.01, 0.1, 0.99];
dim_iid_stats = 10
dim_rec_stats = 10
dim_final_stats = 10 #d*len(A)
dim_rec_stats_feedback = 10 #d*len(A)
batchSize = 10 #10 #100
blk_size = int(batchSize/2)
numBatches = int(numTotalSamples/batchSize)
else:
print("Unsupported dataset encountered")
else:
print("Unsupported model encountered")
############################################
# Evaluate ROC plots (regress mu2)
############################################
if 1:
Gest = torch.zeros(n, n, requires_grad = False)
if(model_name == 'sru'):
for predictedNode in range(n):
start = time.time()
print("node = %d" % (predictedNode))
model = SRU(n_inp_channels, n_out_channels, dim_iid_stats, dim_rec_stats, dim_rec_stats_feedback, dim_final_stats,A, device)
model.to(device) # shift to CPU/GPU memory
print(count_parameters(model))
model, lossVec = trainSRU(model, Xtrain, device, numBatches, batchSize, blk_size, predictedNode, max_iter,
lambda1, lambda2, lr, lr_gamma, lr_update_gap, staggerTrainWin, stoppingThresh, trainVerboseLvl)
Gest.data[predictedNode, :] = torch.norm(model.lin_xr2phi.weight.data[:,:n], p=2, dim=0)
print("Elapsed time (1) = % s seconds" % (time.time() - start))
elif(model_name == 'eSRU_1LF'):
for predictedNode in range(n):
start = time.time()
print("node = %d" % (predictedNode))
model = eSRU_1LF(n_inp_channels, n_out_channels, dim_iid_stats, dim_rec_stats, dim_rec_stats_feedback, dim_final_stats,A, device)
model.to(device) # shift to CPU/GPU memory
print(count_parameters(model))
model, lossVec = train_eSRU_1LF(model, Xtrain, device, numBatches, batchSize, blk_size, predictedNode, max_iter,
lambda1, lambda2, lambda3, lr, lr_gamma, lr_update_gap, staggerTrainWin, stoppingThresh, trainVerboseLvl)
Gest.data[predictedNode, :] = torch.norm(model.lin_xr2phi.weight.data[:,:n], p=2, dim=0)
print("Elapsed time (1) = % s seconds" % (time.time() - start))
elif(model_name == 'eSRU_2LF'):
for predictedNode in range(n):
start = time.time()
print("node = %d" % (predictedNode))
model = eSRU_2LF(n_inp_channels, n_out_channels, dim_iid_stats, dim_rec_stats, dim_rec_stats_feedback, dim_final_stats,A, device)
model.to(device) # shift to CPU/GPU memory
print(count_parameters(model))
model, lossVec = train_eSRU_2LF(model, Xtrain, device, numBatches, batchSize, blk_size, predictedNode, max_iter,
lambda1, lambda2, lambda3, lr, lr_gamma, lr_update_gap, staggerTrainWin, stoppingThresh, trainVerboseLvl)
Gest.data[predictedNode, :] = torch.norm(model.lin_xr2phi.weight.data[:,:n], p=2, dim=0)
print("Elapsed time (1) = % s seconds" % (time.time() - start))
else:
print("Unsupported model encountered")
print(Gref)
print(Gest)
if(jobLogFilename != ""):
if(model_name == 'eSRU_1LF' or model_name == 'eSRU_2LF'):
np.savez(jobLogFilename,
Gref=Gref,
Gest=Gest.detach().cpu().numpy(),
model=model_name,
dataset=dataset,
dsid=dataset_id,
T=T,
F=F,
nepochs=max_iter,
mu1=mu1,
mu2=mu2,
mu3=mu3,
lr=lr,
batchSize=batchSize,
blk_size=blk_size,
numBatches=numBatches,
dim_iid_stats=dim_iid_stats,
dim_rec_stats=dim_rec_stats,
dim_final_stats=dim_final_stats,
dim_rec_stats_feedback=dim_rec_stats_feedback)
else:
np.savez(jobLogFilename, Gref=Gref, Gest=Gest.detach().cpu().numpy(), model=model_name, dataset=dataset, dsid=dataset_id, T=T, F=F, nepochs=max_iter, mu1=mu1, mu2=mu2, lr=lr)
# sleep for one seconds followed by printing
# the exit key for tmux consumption
time.sleep(1)
print("#RUN_COMPLETE #RUN_COMPLETE #RUN_COMPLETE #RUN_COMPLETE")