repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/dcrnn_train_pytorch.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import yaml from lib.utils import load_graph_data from model.pytorch.dcrnn_supervisor import DCRNNSupervisor import setproctitle setproctitle.setproctitle("stgcn@lifuxian") def main(args): ...
1,455
38.351351
129
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/run_demo_pytorch.py
import argparse import numpy as np import os import sys import yaml from lib.utils import load_graph_data from model.pytorch.dcrnn_supervisor import DCRNNSupervisor def run_dcrnn(args): with open(args.config_filename) as f: supervisor_config = yaml.load(f) graph_pkl_filename = supervisor_config[...
1,264
36.205882
108
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/dcrnn_train.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import tensorflow as tf import yaml from lib.utils import load_graph_data from model.tf.dcrnn_supervisor import DCRNNSupervisor def main(args): with open(args.config_filename) as f: ...
1,240
32.540541
104
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/run_demo.py
import argparse import numpy as np import os import sys import tensorflow as tf import yaml from lib.utils import load_graph_data from model.tf.dcrnn_supervisor import DCRNNSupervisor def run_dcrnn(args): with open(args.config_filename) as f: config = yaml.load(f) tf_config = tf.ConfigProto() if ...
1,433
36.736842
108
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/scripts/generate_training_data.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import numpy as np import os import pandas as pd def generate_graph_seq2seq_io_data( df, x_offsets, y_offsets, add_time_in_day=True, add_day_in_...
3,904
30.491935
103
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/scripts/gen_adj_mx.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import pandas as pd import pickle def get_adjacency_matrix(distance_df, sensor_ids, normalized_k=0.1): """ :param distance_df: data frame with three columns: [from,...
2,790
42.609375
125
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/scripts/eval_baseline_methods.py
import argparse import numpy as np import pandas as pd from statsmodels.tsa.vector_ar.var_model import VAR from lib import utils from lib.metrics import masked_rmse_np, masked_mape_np, masked_mae_np from lib.utils import StandardScaler def historical_average_predict(df, period=12 * 24 * 7, test_ratio=0.2, null_val=...
5,893
40.507042
116
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/scripts/__init__.py
0
0
0
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/__init__.py
0
0
0
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/pytorch/dcrnn_model.py
import numpy as np import torch import torch.nn as nn from model.pytorch.dcrnn_cell import DCGRUCell device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) class Seq2SeqAttrs: def __init__(self...
13,218
41.779935
119
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/pytorch/dcrnn_cell.py
import numpy as np import torch from lib import utils device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class LayerParams: def __init__(self, rnn_network: torch.nn.Module, layer_type: str): self._rnn_network = rnn_network self._params_dict = {} self._biases_dict = {} ...
6,939
41.576687
105
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/pytorch/utils.py
import torch import numpy as np def masked_mae_loss(y_pred, y_true): mask = (y_true != 0).float() mask /= mask.mean() loss = torch.abs(y_pred - y_true) loss = loss * mask # trick for nans: https://discuss.pytorch.org/t/how-to-set-nan-in-tensor-to-0/3918/3 loss[loss != loss] = 0 return loss...
3,175
30.76
88
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/pytorch/__init__.py
0
0
0
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/pytorch/dcrnn_supervisor.py
import os import time import numpy as np import torch import torch.nn as nn # from torch.utils.tensorboard import SummaryWriter from lib import utils # from model.pytorch.dcrnn_model import DCRNNModel from model.pytorch.dcrnn_model import STGCN from model.pytorch.utils import masked_mae_loss, metric, get_normalized_a...
17,411
41.8867
129
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/tf/dcrnn_model.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.contrib import legacy_seq2seq from model.tf.dcrnn_cell import DCGRUCell class DCRNNModel(object): def __init__(self, is_training, batch_size, scaler, adj_mx, **mo...
4,940
41.594828
119
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/tf/dcrnn_cell.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.contrib.rnn import RNNCell from lib import utils class DCGRUCell(RNNCell): """Graph Convolution Gated Recurrent Unit cell. """ def cal...
8,023
42.372973
105
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/tf/__init__.py
0
0
0
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/model/tf/dcrnn_supervisor.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import os import sys import tensorflow as tf import time import yaml from lib import utils, metrics from lib.AMSGrad import AMSGrad from lib.metrics import masked_mae_loss from model.tf.dcr...
13,531
41.420063
115
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/lib/utils.py
import logging import numpy as np import os import pickle import scipy.sparse as sp import sys # import tensorflow as tf from scipy.sparse import linalg class DataLoader(object): def __init__(self, xs, ys, batch_size, pad_with_last_sample=True, shuffle=False): """ :param xs: :param ys: ...
7,499
33.562212
113
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/lib/metrics_test.py
import unittest import numpy as np import tensorflow as tf from lib import metrics class MyTestCase(unittest.TestCase): def test_masked_mape_np(self): preds = np.array([ [1, 2, 2], [3, 4, 5], ], dtype=np.float32) labels = np.array([ [1, 2, 2], ...
6,135
29.834171
80
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/lib/AMSGrad.py
"""AMSGrad for TensorFlow. From: https://github.com/taki0112/AMSGrad-Tensorflow """ from tensorflow.python.eager import context from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_o...
7,695
44.538462
115
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/lib/metrics.py
import numpy as np import tensorflow as tf def masked_mse_tf(preds, labels, null_val=np.nan): """ Accuracy with masking. :param preds: :param labels: :param null_val: :return: """ if np.isnan(null_val): mask = ~tf.is_nan(labels) else: mask = tf.not_equal(labels, nul...
4,371
29.361111
99
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STGCN/lib/__init__.py
0
0
0
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN/layer.py
from __future__ import division import torch import torch.nn as nn from torch.nn import init import numbers import torch.nn.functional as F from collections import OrderedDict class gconv_RNN(nn.Module): def __init__(self): super(gconv_RNN, self).__init__() def forward(self, x, A): x = torch...
2,007
27.28169
79
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN/net.py
import torch.utils.data as utils import torch.nn.functional as F import torch import torch.nn as nn from torch.autograd import Variable from torch.nn.parameter import Parameter import numpy as np import pandas as pd import math import time from layer import * import sys from collections import OrderedDict class DGCRN...
10,196
36.215328
79
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN/util.py
import pickle import numpy as np import os import scipy.sparse as sp import torch from scipy.sparse import linalg from torch.autograd import Variable def normal_std(x): return x.std() * np.sqrt((len(x) - 1.) / (len(x))) class DataLoaderS(object): def __init__(self, file_name, ...
12,210
31.562667
112
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN/train.py
import torch import numpy as np import argparse import time from util import * from trainer import Trainer from net import DGCRN import setproctitle import os setproctitle.setproctitle("DGCRN@lifuxian") def str_to_bool(value): if isinstance(value, bool): return value if value.lower() in {'false', 'f...
15,124
35.184211
186
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN/trainer.py
import torch.optim as optim import math from net import * import util class Trainer(): def __init__(self, model, lrate, wdecay, clip, step_size, seq_out_len, scaler, device, ...
3,313
33.520833
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/PeMS/tf_utils.py
# import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() def conv2d(x, output_dims, kernel_size, stride = [1, 1], padding = 'SAME', use_bias = True, activation = tf.nn.relu, bn = False, bn_decay = None, is_training = None): input_dims = x.get_shape()[-1].value ...
2,424
38.754098
77
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/PeMS/test.py
import math import argparse import utils import time import numpy as np import tensorflow as tf parser = argparse.ArgumentParser() parser.add_argument('--P', type = int, default = 12, help = 'history steps') parser.add_argument('--Q', type = int, default = 12, help = 'prediction...
5,723
43.030769
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/PeMS/utils.py
import numpy as np import pandas as pd # log string def log_string(log, string): log.write(string + '\n') log.flush() print(string) # metric def metric(pred, label): with np.errstate(divide = 'ignore', invalid = 'ignore'): mask = np.not_equal(label, 0) mask = mask.astype(np.float32) ...
3,345
33.142857
77
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/PeMS/model.py
import tf_utils # import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() def placeholder(P, Q, N): X = tf.compat.v1.placeholder(shape = (None, P, N), dtype = tf.float32) TE = tf.compat.v1.placeholder(shape = (None, P + Q, 2), dtype = tf.int32) label = tf.compat.v1.placeholder(sh...
10,625
37.781022
80
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/PeMS/train.py
import math import argparse import utils, model import time, datetime import numpy as np # import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() parser = argparse.ArgumentParser() parser.add_argument('--time_slot', type = int, default = 5, help = 'a time step is 5 mins'...
9,998
40.318182
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/PeMS/node2vec/node2vec.py
''' Aditya Grover and Jure Leskovec. node2vec: Scalable Feature Learning for Networks. In KDD, 2016. https://github.com/aditya-grover/node2vec ''' import numpy as np import networkx as nx import random class Graph(): def __init__(self, nx_G, is_directed, p, q): self.G = nx_G self.is_directed = is_directed sel...
3,855
23.877419
120
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/PeMS/node2vec/generateSE.py
import node2vec import numpy as np import networkx as nx from gensim.models import Word2Vec is_directed = True p = 2 q = 1 num_walks = 100 walk_length = 80 dimensions = 64 window_size = 10 iter = 1000 Adj_file = '../data/Adj.txt' SE_file = '../data/SE.txt' def read_graph(edgelist): G = nx.read_edgelist( e...
911
23
65
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/BJ500/tf_utils.py
# import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() def conv2d(x, output_dims, kernel_size, stride = [1, 1], padding = 'SAME', use_bias = True, activation = tf.nn.relu, bn = False, bn_decay = None, is_training = None): input_dims = x.get_shape()[-1].value ...
2,424
38.754098
77
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/BJ500/test.py
import math import argparse import utils import time import numpy as np import tensorflow as tf parser = argparse.ArgumentParser() parser.add_argument('--P', type = int, default = 12, help = 'history steps') parser.add_argument('--Q', type = int, default = 12, help = 'prediction...
5,723
43.030769
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/BJ500/utils.py
import numpy as np import pandas as pd # log string def log_string(log, string): log.write(string + '\n') log.flush() print(string) # metric def metric(pred, label): with np.errstate(divide = 'ignore', invalid = 'ignore'): mask = np.not_equal(label, 0) mask = mask.astype(np.float32) ...
3,346
33.153061
77
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/BJ500/model.py
import tf_utils # import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() def placeholder(P, Q, N): X = tf.compat.v1.placeholder(shape = (None, P, N), dtype = tf.float32) TE = tf.compat.v1.placeholder(shape = (None, P + Q, 2), dtype = tf.int32) label = tf.compat.v1.placeholder(sh...
10,625
37.781022
80
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/BJ500/train.py
import math import argparse import utils, model import time, datetime import numpy as np # import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() parser = argparse.ArgumentParser() parser.add_argument('--time_slot', type = int, default = 5, help = 'a time step is 5 mins'...
10,002
40.334711
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/BJ500/node2vec/node2vec.py
''' Aditya Grover and Jure Leskovec. node2vec: Scalable Feature Learning for Networks. In KDD, 2016. https://github.com/aditya-grover/node2vec ''' import numpy as np import networkx as nx import random class Graph(): def __init__(self, nx_G, is_directed, p, q): self.G = nx_G self.is_directed = is_directed sel...
3,855
23.877419
120
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/BJ500/node2vec/generateSE.py
import node2vec import numpy as np import networkx as nx from gensim.models import Word2Vec is_directed = False #此处改为False p = 2 q = 1 num_walks = 100 walk_length = 80 dimensions = 64 window_size = 10 iter = 1000 Adj_file = '../data/Adj(BJ500).txt' SE_file = '../data/SE(BJ500).txt' def read_graph(edgelist): G = n...
937
23.684211
65
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/METR/tf_utils.py
# import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() def conv2d(x, output_dims, kernel_size, stride = [1, 1], padding = 'SAME', use_bias = True, activation = tf.nn.relu, bn = False, bn_decay = None, is_training = None): input_dims = x.get_shape()[-1].value ...
2,424
38.754098
77
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/METR/test.py
import math import argparse import utils import time import numpy as np import tensorflow as tf parser = argparse.ArgumentParser() parser.add_argument('--P', type = int, default = 12, help = 'history steps') parser.add_argument('--Q', type = int, default = 12, help = 'prediction...
5,654
42.5
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/METR/utils.py
import numpy as np import pandas as pd # log string def log_string(log, string): log.write(string + '\n') log.flush() print(string) # metric def metric(pred, label): with np.errstate(divide = 'ignore', invalid = 'ignore'): mask = np.not_equal(label, 0) mask = mask.astype(np.float32) ...
3,331
33.708333
77
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/METR/model.py
import tf_utils # import tensorflow as tf import tensorflow.compat.v1 as tf tf.disable_v2_behavior() def placeholder(P, Q, N): X = tf.placeholder( shape = (None, P, N), dtype = tf.float32, name = 'X') TE = tf.placeholder( shape = (None, P + Q, 2), dtype = tf.int32, name = 'TE') label = tf....
10,872
37.556738
87
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/METR/train.py
import math import argparse import utils, model import time, datetime import numpy as np import tensorflow.compat.v1 as tf tf.disable_v2_behavior() parser = argparse.ArgumentParser() parser.add_argument('--time_slot', type = int, default = 5, help = 'a time step is 5 mins') parser.add_argument('--...
9,863
39.760331
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/METR/node2vec/node2vec.py
''' Aditya Grover and Jure Leskovec. node2vec: Scalable Feature Learning for Networks. In KDD, 2016. https://github.com/aditya-grover/node2vec ''' import numpy as np import networkx as nx import random class Graph(): def __init__(self, nx_G, is_directed, p, q): self.G = nx_G self.is_directed = is_directed sel...
3,855
23.877419
120
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/GMAN/METR/node2vec/generateSE.py
import node2vec import numpy as np import networkx as nx from gensim.models import Word2Vec is_directed = True p = 2 q = 1 num_walks = 100 walk_length = 80 dimensions = 64 window_size = 10 iter = 1000 Adj_file = '../data/Adj.txt' SE_file = '../data/SE.txt' def read_graph(edgelist): G = nx.read_edgelist( e...
911
23
65
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/model/AGCRN.py
import torch import torch.nn as nn from model.AGCRNCell import AGCRNCell class AVWDCRNN(nn.Module): def __init__(self, node_num, dim_in, dim_out, cheb_k, embed_dim, num_layers=1): super(AVWDCRNN, self).__init__() assert num_layers >= 1, 'At least one DCRNN layer in the Encoder.' self.node_n...
3,454
44.460526
113
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/model/Run_PEMS-BAY.py
import os import sys file_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(file_dir) sys.path.append(file_dir) import torch import numpy as np import torch.nn as nn import argparse import configparser from datetime import datetime from model.AGCRN import AGCRN as Network from model.BasicTrainer...
6,953
32.921951
79
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/model/AGCRN_debug.py
import torch import torch.nn as nn from model.AGCRNCell import AGCRNCell class AVWDCRNN(nn.Module): def __init__(self, node_num, dim_in, dim_out, cheb_k, embed_dim, num_layers=1): super(AVWDCRNN, self).__init__() assert num_layers >= 1, 'At least one DCRNN layer in the Encoder.' self.node_n...
4,677
41.917431
113
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/model/AGCN.py
import torch import torch.nn.functional as F import torch.nn as nn class AVWGCN(nn.Module): def __init__(self, dim_in, dim_out, cheb_k, embed_dim): super(AVWGCN, self).__init__() self.cheb_k = cheb_k self.weights_pool = nn.Parameter(torch.FloatTensor(embed_dim, cheb_k, dim_in, dim_out)) ...
1,453
54.923077
112
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/model/AGCRNCell.py
import torch import torch.nn as nn from model.AGCN import AVWGCN class AGCRNCell(nn.Module): def __init__(self, node_num, dim_in, dim_out, cheb_k, embed_dim): super(AGCRNCell, self).__init__() self.node_num = node_num self.hidden_dim = dim_out self.gate = AVWGCN(dim_in+self.hidden_d...
1,065
40
80
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/model/Run_METR-LA.py
import os import sys file_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(file_dir) sys.path.append(file_dir) import torch import numpy as np import torch.nn as nn import argparse import configparser from datetime import datetime from model.AGCRN import AGCRN as Network from model.BasicTraine...
6,953
32.757282
79
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/model/BasicTrainer.py
import torch import math import os import time import copy import numpy as np from lib.logger import get_logger from lib.metrics import All_Metrics class Trainer(object): def __init__(self, model, loss, optimizer, train_loader, val_loader, test_loader, scaler, args, lr_scheduler=None): sup...
9,286
42.600939
148
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/model/Run_BJ.py
import os import sys file_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(file_dir) sys.path.append(file_dir) import torch import numpy as np import torch.nn as nn import argparse import configparser from datetime import datetime from model.AGCRN import AGCRN as Network from model.BasicTrainer...
6,947
32.892683
79
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/lib/load_dataset.py
import os import numpy as np def load_st_dataset(dataset): #output B, N, D if dataset == 'PEMSD4': data_path = os.path.join('../data/PeMSD4/pems04.npz') data = np.load(data_path)['data'][:, :, 0] #onley the first dimension, traffic flow data elif dataset == 'PEMSD8': data_path = os...
697
37.777778
113
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/lib/TrainInits.py
import torch import random import numpy as np def init_seed(seed): ''' Disable cudnn to maximize reproducibility ''' torch.cuda.cudnn_enabled = False torch.backends.cudnn.deterministic = True random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed)...
1,818
33.980769
120
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/lib/dataloader.py
import torch import numpy as np import torch.utils.data from lib.add_window import Add_Window_Horizon from lib.load_dataset import load_st_dataset from lib.normalization import NScaler, MinMax01Scaler, MinMax11Scaler, StandardScaler, ColumnMinMaxScaler def normalize_dataset(data, normalizer, column_wise=False): if...
9,437
45.492611
208
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/lib/logger.py
import os import logging from datetime import datetime def get_logger(root, name=None, debug=True): #when debug is true, show DEBUG and INFO in screen #when debug is false, show DEBUG in file and info in both screen&file #INFO will always be in screen # create a logger logger = logging.getLogger(na...
1,641
35.488889
79
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/lib/add_window.py
import numpy as np def Add_Window_Horizon(data, window=3, horizon=1, single=False): ''' :param data: shape [B, ...] :param window: :param horizon: :return: X is [B, W, ...], Y is [B, H, ...] ''' length = len(data) end_index = length - horizon - window + 1 X = [] #windows Y ...
1,053
26.736842
71
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/lib/metrics.py
''' Always evaluate the model with MAE, RMSE, MAPE, RRSE, PNBI, and oPNBI. Why add mask to MAE and RMSE? Filter the 0 that may be caused by error (such as loop sensor) Why add mask to MAPE and MARE? Ignore very small values (e.g., 0.5/0.5=100%) ''' import numpy as np import torch def MAE_torch(pred, true, mask...
7,947
34.641256
103
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/AGCRN/lib/normalization.py
import numpy as np import torch class NScaler(object): def transform(self, data): return data def inverse_transform(self, data): return data class StandardScaler: """ Standard the input """ def __init__(self, mean, std): self.mean = mean self.std = std de...
4,047
30.138462
93
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN_BJ/layer.py
from __future__ import division import torch import torch.nn as nn from torch.nn import init import numbers import torch.nn.functional as F from collections import OrderedDict class gconv_RNN(nn.Module): def __init__(self): super(gconv_RNN, self).__init__() def forward(self, x, A): x = torch...
2,008
26.902778
79
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN_BJ/net.py
import torch.utils.data as utils import torch.nn.functional as F import torch import torch.nn as nn from torch.autograd import Variable from torch.nn.parameter import Parameter import numpy as np import pandas as pd import math import time from layer import * import random import sys from collections import OrderedDict...
9,248
33.901887
79
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN_BJ/util.py
import pickle import numpy as np import os import scipy.sparse as sp import torch from scipy.sparse import linalg from torch.autograd import Variable def normal_std(x): return x.std() * np.sqrt((len(x) - 1.) / (len(x))) class DataLoaderS(object): def __init__(self, file_name, ...
12,198
31.530667
112
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN_BJ/train.py
import torch import numpy as np import argparse import time from util import * from trainer import Trainer from net import DGCRN import setproctitle import os import random setproctitle.setproctitle("DGCRN@lifuxian") def str_to_bool(value): if isinstance(value, bool): return value if value.lower() i...
15,842
34.76298
186
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN_BJ/trainer.py
import torch.optim as optim import math from net import * import util class Trainer(): def __init__(self, model, lrate, wdecay, clip, step_size, seq_out_len, scaler, device, ...
3,313
33.520833
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN_BJ/scripts/generate_training_data_BJ.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import numpy as np import os import pandas as pd def generate_graph_seq2seq_io_data( df, x_offsets, y_offsets, add_time_in_day=True, add_day_in_...
4,417
31.970149
398
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/DGCRN_BJ/scripts/gen_adj_mx_BJ.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import pandas as pd import pickle def get_adjacency_matrix(distance_df, sensor_ids, normalized_k=0.1): """ :param distance_df: data frame with three columns: [from,...
2,790
42.609375
125
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/ASTGCN/train_MSTGCN_r.py
#!/usr/bin/env python # coding: utf-8 import torch import torch.nn as nn import torch.optim as optim import numpy as np import os from time import time import shutil import argparse import configparser from model.MSTGCN_r import make_model from lib.utils import load_graphdata_channel1, get_adjacency_matrix, evaluate_on...
6,970
31.423256
150
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/ASTGCN/train_ASTGCN_r.py
#!/usr/bin/env python # coding: utf-8 import torch import torch.nn as nn import torch.optim as optim import numpy as np import os from time import time import shutil import argparse import configparser from model.ASTGCN_r import make_model from lib.utils import load_graphdata_channel1, get_adjacency_matrix, compute_val...
6,972
30.840183
150
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/ASTGCN/prepareData.py
import os import numpy as np import argparse import configparser def search_data(sequence_length, num_of_depend, label_start_idx, num_for_predict, units, points_per_hour): ''' Parameters ---------- sequence_length: int, length of all history data num_of_depend: int, label_start...
11,903
38.157895
147
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/ASTGCN/model/ASTGCN_r.py
# -*- coding:utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from lib.utils import scaled_Laplacian, cheb_polynomial class Spatial_Attention_layer(nn.Module): ''' compute spatial attention scores ''' def __init__(self, DEVICE, in_channels, num_of_vertices, num_of_timesteps...
10,548
36.275618
194
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/ASTGCN/model/MSTGCN_r.py
# -*- coding:utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from lib.utils import scaled_Laplacian, cheb_polynomial class cheb_conv(nn.Module): ''' K-order chebyshev graph convolution ''' def __init__(self, K, cheb_polynomials, in_channels, out_channels): ''' ...
5,014
32.885135
154
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/ASTGCN/lib/utils.py
import os import numpy as np import torch import torch.utils.data from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from .metrics import masked_mape_np from scipy.sparse.linalg import eigs import pickle def load_pickle(pickle_file): try: with open(pickle_file,...
18,213
34.996047
208
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/ASTGCN/lib/metrics.py
# -*- coding:utf-8 -*- import numpy as np def masked_mape_np(y_true, y_pred, null_val=np.nan): with np.errstate(divide='ignore', invalid='ignore'): if np.isnan(null_val): mask = ~np.isnan(y_true) else: mask = np.not_equal(y_true, null_val) mask = mask.astype('float...
541
30.882353
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STSGCN/main.py
# -*- coding:utf-8 -*- import setproctitle setproctitle.setproctitle("STSGCN@lifuxian") import time import json import argparse import numpy as np import mxnet as mx from utils import (construct_model, generate_data, masked_mae_np, masked_mape_np, masked_mse_np) parser = argparse.ArgumentParser() ...
6,547
32.238579
830
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STSGCN/utils.py
import os import numpy as np import mxnet as mx import pickle def load_pickle(pickle_file): try: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f) except UnicodeDecodeError as e: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f, encoding='l...
7,732
27.747212
78
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STSGCN/load_params.py
# -*- coding:utf-8 -*- import mxnet as mx sym, arg_params, aux_params = mx.model.load_checkpoint('STSGCN', 200) print(type(arg_params), type(aux_params))
157
18.75
69
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STSGCN/models/__init__.py
0
0
0
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STSGCN/models/stsgcn.py
# -*- coding:utf-8 -*- import mxnet as mx def position_embedding(data, input_length, num_of_vertices, embedding_size, temporal=True, spatial=True, init=mx.init.Xavier(magnitude=0.0003), prefix=""): ''' Parameters ---------- data: mx...
12,140
23.137177
76
py
Traffic-Benchmark
Traffic-Benchmark-master/methods/STSGCN/test/test_stsgcn.py
# -*- coding:utf-8 -*- import sys import mxnet as mx sys.path.append('.') num_of_vertices = 358 batch_size = 16 filter_ = [3, 3, 3] filter_list = [[3, 3, 3], [6, 6, 6], [9, 9, 9]] predict_length = 12 data = mx.sym.var('data') adj = mx.sym.var('adj') label = mx.sym.var('label') def test_position_embedding(): fro...
4,947
34.342857
75
py
AGC
AGC-master-master/test.py
import scipy.io as sio import time import tensorflow as tf import numpy as np import scipy.sparse as sp from sklearn.cluster import KMeans from metrics import clustering_metrics from sklearn.metrics.pairwise import euclidean_distances from sklearn.feature_extraction.text import TfidfTransformer from sklearn.preprocessi...
4,987
26.711111
104
py
AGC
AGC-master-master/munkres.py
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- # Documentation is intended to be processed by Epydoc. """ Introduction ============ The Munkres module provides an implementation of the Munkres algorithm (also called the Hungarian algorithm or the Kuhn-Munkres algorithm), useful for solving the Assignment Problem...
27,084
30.275982
82
py
AGC
AGC-master-master/metrics.py
from sklearn.metrics import f1_score from sklearn.metrics import roc_auc_score from sklearn.metrics import average_precision_score from sklearn import metrics from munkres import Munkres, print_matrix import numpy as np class linkpred_metrics(): def __init__(self, edges_pos, edges_neg): self.edges_pos = ed...
4,397
39.348624
259
py
FL-MRCM
FL-MRCM-main/main_fl_mr.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import copy import numpy as np import torch import os from utils.options import args_parser from models.recon_Update import LocalUpdate from models.Fed import FedAvg from models.test import evaluator_normal as evaluator from data.mri_data import Slice...
5,441
37.595745
148
py
FL-MRCM
FL-MRCM-main/main_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import torch import os from utils.options import args_parser from models.test import test_save_result, test_save_vector from data.mri_data import SliceData, DataTransform from data.subsample import create_mask_for_mask_type from models.unet_model impo...
2,799
32.73494
127
py
FL-MRCM
FL-MRCM-main/main_fl_mrcm.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 # import matplotlib # matplotlib.use('Agg') # import matplotlib.pyplot as plt import copy import numpy as np import torch import os from utils.options import args_parser from models.recon_Update import LocalUpdate_ad_da from models.Fed import FedAvg f...
8,221
43.443243
167
py
FL-MRCM
FL-MRCM-main/models/test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @python: 3.6 import torch import torch.nn.functional as F from torch.utils.data import DataLoader from collections import defaultdict import numpy as np from utils import evaluate import h5py from tqdm import tqdm def test_save_result(net_g, datatest, args): net_g....
9,725
44.877358
91
py
FL-MRCM
FL-MRCM-main/models/unet_model.py
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import torch from torch import nn from torch.nn import functional as F class ConvBlock(nn.Module): """ A Convolutional Block that co...
10,036
35.234657
98
py
FL-MRCM
FL-MRCM-main/models/Fed.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import copy import torch from torch import nn def FedAvg(w): w_avg = copy.deepcopy(w[0]) for k in w_avg.keys(): for i in range(1, len(w)): w_avg[k] += w[i][k] w_avg[k] = torch.div(w_avg[k], len(w)) return w_av...
322
18
46
py
FL-MRCM
FL-MRCM-main/models/recon_Update.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import torch from torch import nn from torch.utils.data import DataLoader, Dataset import time import numpy as np from torch.autograd import Variable from torch.nn import functional as F class LocalUpdate(object): def __init__(self, args, device...
8,565
46.588889
131
py
FL-MRCM
FL-MRCM-main/models/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @python: 3.6
61
14.5
23
py
FL-MRCM
FL-MRCM-main/utils/evaluate.py
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import argparse import pathlib from argparse import ArgumentParser import h5py import numpy as np from runstats import Statistics from skima...
3,937
31.816667
96
py
FL-MRCM
FL-MRCM-main/utils/preprocess_datasets_brats.py
import os import h5py import pathlib from data import transforms import numpy as np import torch import nibabel as nib from tqdm import tqdm def mkdir(folder): if not os.path.exists(folder): os.makedirs(folder) def main(): root_dir ='path to /MICCAI_BraTS2020_ValidationData' root_out_dir = 'path...
2,678
35.202703
97
py
FL-MRCM
FL-MRCM-main/utils/sampling.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import numpy as np from torchvision import datasets, transforms from collections import OrderedDict def mnist_iid(dataset, num_users): """ Sample I.I.D. client data from MNIST dataset :param dataset: :param num_users: :return: dict...
3,579
31.844037
106
py
FL-MRCM
FL-MRCM-main/utils/options.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import argparse import pathlib def args_parser(): parser = argparse.ArgumentParser() # federated arguments parser.add_argument('--epochs', type=int, default=50, help="rounds of training") parser.add_argument('--num_users', type=int, d...
2,977
61.041667
105
py
FL-MRCM
FL-MRCM-main/utils/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @python: 3.6
61
14.5
23
py