code stringlengths 17 6.64M |
|---|
def get_checkpoint_history_callback(outdir, config, dataset, comet_experiment, horovod_enabled, is_hpo_run=False):
callbacks = []
if ((not horovod_enabled) or (hvd.rank() == 0)):
cp_dir = (Path(outdir) / 'weights')
cp_dir.mkdir(parents=True, exist_ok=True)
cp_callback = ModelOptimizerC... |
def get_rundir(base='experiments'):
if (not os.path.exists(base)):
os.makedirs(base)
previous_runs = os.listdir(base)
if (len(previous_runs) == 0):
run_number = 1
else:
run_number = (max([int(s.split('run_')[1]) for s in previous_runs]) + 1)
logdir = ('run_%02d' % run_numbe... |
def make_model(config, dtype):
model = config['parameters']['model']
if (model == 'transformer'):
return make_transformer(config, dtype)
elif (model == 'gnn_dense'):
return make_gnn_dense(config, dtype)
raise KeyError('Unknown model type {}'.format(model))
|
def make_gnn_dense(config, dtype):
parameters = ['do_node_encoding', 'node_update_mode', 'node_encoding_hidden_dim', 'dropout', 'activation', 'num_graph_layers_id', 'num_graph_layers_reg', 'input_encoding', 'skip_connection', 'output_decoding', 'combined_graph_layer', 'debug']
kwargs = {}
for par in param... |
def make_transformer(config, dtype):
parameters = ['input_encoding', 'output_decoding', 'num_layers_encoder', 'num_layers_decoder_reg', 'num_layers_decoder_cls', 'hidden_dim', 'num_heads', 'num_random_features']
kwargs = {}
for par in parameters:
if (par in config['parameters'].keys()):
... |
def eval_model(model, dataset, config, outdir, jet_ptcut=5.0, jet_match_dr=0.1, verbose=False):
ibatch = 0
if (config['evaluation_jet_algo'] == 'ee_genkt_algorithm'):
jetdef = fastjet.JetDefinition(fastjet.ee_genkt_algorithm, 0.7, (- 1.0))
elif (config['evaluation_jet_algo'] == 'antikt_algorithm')... |
def freeze_model(model, config, outdir):
def model_output(ret):
return tf.concat([ret['cls'], ret['charge'], ret['pt'], ret['eta'], ret['sin_phi'], ret['cos_phi'], ret['energy']], axis=(- 1))
full_model = tf.function((lambda x: model_output(model(x, training=False))))
niter = 10
nfeat = confi... |
class LearningRateLoggingCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, numpy_logs):
try:
lr = self.model.optimizer._decayed_lr(tf.float32).numpy()
tf.summary.scalar('learning rate', data=lr, step=epoch)
except AttributeError as e:
print(e... |
def configure_model_weights(model, trainable_layers):
print('setting trainable layers: {}'.format(trainable_layers))
if (trainable_layers is None):
trainable_layers = 'all'
if (trainable_layers == 'all'):
model.trainable = True
elif (trainable_layers == 'regression'):
for cg in... |
def make_focal_loss(config):
def loss(x, y):
from .tfa import sigmoid_focal_crossentropy
return sigmoid_focal_crossentropy(x, y, alpha=float(config['setup'].get('focal_loss_alpha', 0.25)), gamma=float(config['setup'].get('focal_loss_gamma', 2.0)), from_logits=config['setup']['cls_output_as_logits... |
class CosineAnnealer():
def __init__(self, start, end, steps):
self.start = start
self.end = end
self.steps = steps
self.n = 0
def step(self):
cos = (np.cos((np.pi * (self.n / self.steps))) + 1)
self.n += 1
return (self.end + (((self.start - self.end) ... |
class OneCycleScheduler(LearningRateSchedule):
"`LearningRateSchedule` that schedules the learning rate on a 1cycle policy as per Leslie Smith's paper\n (https://arxiv.org/pdf/1803.09820.pdf).\n\n The implementation adopts additional improvements as per the fastai library:\n https://docs.fast.ai/callback... |
class MomentumOneCycleScheduler(Callback):
"`Callback` that schedules the momentum according to the 1cycle policy as per Leslie Smith's paper\n (https://arxiv.org/pdf/1803.09820.pdf).\n NOTE: This callback only schedules the momentum parameter, not the learning rate. It is intended to be used with the\n ... |
def is_tensor_or_variable(x):
return (tf.is_tensor(x) or isinstance(x, tf.Variable))
|
class LossFunctionWrapper(tf.keras.losses.Loss):
'Wraps a loss function in the `Loss` class.'
def __init__(self, fn, reduction=tf.keras.losses.Reduction.AUTO, name=None, **kwargs):
'Initializes `LossFunctionWrapper` class.\n\n Args:\n fn: The loss function to wrap, with signature `fn(... |
class SigmoidFocalCrossEntropy(LossFunctionWrapper):
"Implements the focal loss function.\n\n Focal loss was first introduced in the RetinaNet paper\n (https://arxiv.org/pdf/1708.02002.pdf). Focal loss is extremely useful for\n classification when you have highly imbalanced classes. It down-weights\n ... |
@tf.function
def sigmoid_focal_crossentropy(y_true, y_pred, alpha=0.25, gamma=2.0, from_logits: bool=False) -> tf.Tensor:
'Implements the focal loss function.\n\n Focal loss was first introduced in the RetinaNet paper\n (https://arxiv.org/pdf/1708.02002.pdf). Focal loss is extremely useful for\n classifi... |
def get_hp_str(result):
def func(key):
if ('config' in key):
return key.split('config/')[(- 1)]
s = ''
for (ii, hp) in enumerate(list(filter(None.__ne__, [func(key) for key in result.keys()]))):
if ((ii % 6) == 0):
s += '\n'
s += '{}={}; '.format(hp, result... |
def plot_ray_analysis(analysis, save=False, skip=0):
to_plot = ['charge_loss', 'cls_loss', 'cos_phi_loss', 'energy_loss', 'eta_loss', 'learning_rate', 'loss', 'pt_loss', 'sin_phi_loss', 'val_charge_loss', 'val_cls_loss', 'val_cos_phi_loss', 'val_energy_loss', 'val_eta_loss', 'val_loss', 'val_pt_loss', 'val_sin_ph... |
def correct_column_names_in_trial_dataframes(analysis):
'\n Sometimes some trial dataframes are missing column names and have been\n given the first row of values as column names. This function corrects\n this in the ray.tune.Analysis object.\n '
trial_dataframes = analysis.trial_dataframes
tr... |
def get_top_k_df(analysis, k):
result_df = analysis.dataframe()
if (analysis.default_mode == 'min'):
dd = result_df.nsmallest(k, analysis.default_metric)
elif (analysis.default_mode == 'max'):
dd = result_df.nlargest(k, analysis.default_metric)
return dd
|
def topk_summary_plot(analysis, k, save=False, save_dir=None):
to_plot = ['val_cls_loss', 'val_energy_loss', 'val_loss']
dd = get_top_k_df(analysis, k)
dfs = analysis.trial_dataframes
(fig, axs) = plt.subplots(k, 5, figsize=(12, 9), tight_layout=True)
for (key, ax_row) in zip(dd['logdir'], axs):
... |
def topk_summary_plot_v2(analysis, k, save=False, save_dir=None):
print('Creating summary plot of top {} trials.'.format(k))
to_plot = ['val_loss', 'val_cls_loss']
dd = get_top_k_df(analysis, k)
dfs = analysis.trial_dataframes
(fig, axs) = plt.subplots(len(to_plot), 1, figsize=(12, 9), tight_layou... |
def summarize_top_k(analysis, k, save=False, save_dir=None):
print('Creating summary table of top {} trials.'.format(k))
dd = get_top_k_df(analysis, k)
summary = pd.concat([dd[['loss', 'cls_loss', 'val_loss', 'val_cls_loss']], dd.filter(regex='config/*'), dd['logdir']], axis=1)
cm_green = sns.light_pa... |
def analyze_ray_experiment(exp_dir, default_metric, default_mode):
from ray.tune import Analysis
analysis = Analysis(exp_dir, default_metric=default_metric, default_mode=default_mode)
topk_summary_plot_v2(analysis, 5, save_dir=exp_dir)
(summ, styled) = summarize_top_k(analysis, k=10, save_dir=exp_dir)... |
def count_skipped_configurations(exp_dir):
skiplog_file_path = (Path(exp_dir) / 'skipped_configurations.txt')
if skiplog_file_path.exists():
with open(skiplog_file_path, 'r') as f:
lines = f.readlines()
count = 0
for line in lines:
if (line == (('#' ... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--bin-size', type=int, default=256)
parser.add_argument('--num-features', type=int, default=17)
parser.add_argument('--batch-size', type=int, default=20)
parser.add_argument('--num-threads', type=int, default=1)
parser.a... |
def get_mem_cpu_mb():
return (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1000)
|
def get_mem_gpu_mb():
mem = pynvml.nvmlDeviceGetMemoryInfo(handle)
return ((mem.used / 1000) / 1000)
|
def get_mem_mb(use_gpu):
if use_gpu:
return get_mem_gpu_mb()
else:
return get_mem_cpu_mb()
|
def create_experiment_dir(prefix=None, suffix=None, experiments_dir='experiments'):
if (prefix is None):
train_dir = (Path(experiments_dir) / datetime.datetime.now().strftime('%Y%m%d_%H%M%S_%f'))
else:
train_dir = (Path(experiments_dir) / (prefix + datetime.datetime.now().strftime('%Y%m%d_%H%M... |
def create_comet_experiment(comet_exp_name, comet_offline=False, outdir=None):
try:
if comet_offline:
logging.info('Using comet-ml OfflineExperiment, saving logs locally.')
if (outdir is None):
raise ValueError('Please specify am output directory when setting comet_... |
def hits_to_features(hit_data, iev, coll, feats):
if ('TrackerHit' in coll):
new_feats = []
for feat in feats:
feat_to_get = feat
if (feat == 'energy'):
feat_to_get = 'eDep'
new_feats.append((feat, feat_to_get))
else:
new_feats = [(f,... |
def track_pt(omega):
a = (3 * (10 ** (- 4)))
b = 4
return (a * np.abs((b / omega)))
|
def track_to_features(prop_data, iev):
track_arr = prop_data[track_coll][iev]
feats_from_track = ['type', 'chi2', 'ndf', 'dEdx', 'dEdxError', 'radiusOfInnermostHit']
ret = {feat: track_arr[((track_coll + '.') + feat)] for feat in feats_from_track}
n_tr = len(ret['type'])
trackstate_idx = prop_data... |
def visualize(sample, data, iev, trk_opacity=0.8):
Xelem = pandas.DataFrame(data[iev]['Xelem'])
ycand = pandas.DataFrame(data[iev]['ycand'])
ygen = pandas.DataFrame(data[iev]['ygen'])
eta_range = 1000
radius_mult = 2000
trk_x = []
trk_y = []
trk_z = []
for (irow, row) in Xelem[(Xel... |
def node_label_func(n):
return '{0} {1}\nE={2:.2f}\n{3:.1f}:{4:.1f}'.format(n[0].upper(), g.nodes[n]['typ'], g.nodes[n]['e'], g.nodes[n]['eta'], g.nodes[n]['phi'])
|
def node_color_func(n):
colors = {'gen': 'blue', 'el': 'gray', 'pf': 'purple', 'tp': 'red', 'cp': 'red', 'gen': 'blue'}
return colors[n[0]]
|
def plot_energy_stack(energies, pids):
uniq_pids = np.unique(pids)
hists = []
bins = np.logspace((- 1), 6, 61)
for pid in uniq_pids:
h = bh.Histogram(bh.axis.Variable(bins))
h.fill(energies[(pids == pid)])
hists.append(h)
mplhep.histplot(hists, stack=False, label=[str(p) fo... |
def to_bh(data, bins, cumulative=False):
h1 = bh.Histogram(bh.axis.Variable(bins))
h1.fill(data)
if cumulative:
h1[:] = (np.sum(h1.values()) - np.cumsum(h1))
return h1
|
def load_pickle(fn):
d = pickle.load(open(fn, 'rb'))
ret = []
for it in d:
ret.append({'slimmedGenJets': it['slimmedGenJets'], 'slimmedJetsPuppi': it['slimmedJetsPuppi'], 'genMetTrue': it['genMetTrue'], 'slimmedMETsPuppi': it['slimmedMETsPuppi']})
return ret
|
def varbins(*args):
newlist = []
for arg in args[:(- 1)]:
newlist.append(arg[:(- 1)])
newlist.append(args[(- 1)])
return np.concatenate(newlist)
|
def get_hist_and_merge(files, histname):
hists = []
for fn in files:
fi = uproot.open(fn)
h = fi[histname].to_boost()
hists.append(h)
return sum(hists[1:], hists[0])
|
def Gauss(x, a, x0, sigma):
return (a * np.exp(((- ((x - x0) ** 2)) / (2 * (sigma ** 2)))))
|
def fit_response(hist2d, bin_range):
centers = []
means = []
means_unc = []
sigmas = []
sigmas_unc = []
for ibin in bin_range:
print(ibin)
plt.figure()
xvals = hist2d.axes[1].centers
vals = hist2d.values()[ibin]
errs = np.sqrt(vals)
errs[(vals ==... |
def yield_from_ds():
for elem in dss:
(yield {'X': elem['X'], 'ygen': elem['ygen'], 'ycand': elem['ycand']})
|
def particle_has_track(g, particle):
for e in g.edges(particle):
if (e[1][0] == 'track'):
return True
return False
|
def get_tower_gen_fracs(g, tower):
e_130 = 0.0
e_211 = 0.0
e_22 = 0.0
e_11 = 0.0
ptcls = []
for e in g.edges(tower):
if (e[1][0] == 'particle'):
if (not particle_has_track(g, e[1])):
ptcls.append(e[1])
pid = abs(g.nodes[e[1]]['pid'])
... |
def make_tower_array(tower_dict):
return np.array([1, tower_dict['et'], tower_dict['eta'], np.sin(tower_dict['phi']), np.cos(tower_dict['phi']), tower_dict['energy'], tower_dict['eem'], tower_dict['ehad'], 0.0, 0.0, 0.0, 0.0])
|
def make_track_array(track_dict):
return np.array([2, track_dict['pt'], track_dict['eta'], np.sin(track_dict['phi']), np.cos(track_dict['phi']), track_dict['p'], track_dict['eta_outer'], np.sin(track_dict['phi_outer']), np.cos(track_dict['phi_outer']), track_dict['charge'], track_dict['is_gen_muon'], track_dict['... |
def make_gen_array(gen_dict):
if (not gen_dict):
return np.zeros(7)
encoded_pid = gen_pid_encoding.get(abs(gen_dict['pid']), 1)
charge = (math.copysign(1, gen_dict['pid']) if (encoded_pid in [1, 4, 5]) else 0)
return np.array([encoded_pid, charge, gen_dict['pt'], gen_dict['eta'], np.sin(gen_di... |
def make_cand_array(cand_dict):
if (not cand_dict):
return np.zeros(7)
encoded_pid = gen_pid_encoding.get(abs(cand_dict['pid']), 1)
return np.array([encoded_pid, cand_dict['charge'], cand_dict.get('pt', 0), cand_dict['eta'], np.sin(cand_dict['phi']), np.cos(cand_dict['phi']), cand_dict.get('energy... |
def make_triplets(g, tracks, towers, particles, pfparticles):
triplets = []
remaining_particles = set(particles)
remaining_pfcandidates = set(pfparticles)
for t in tracks:
ptcl = None
for e in g.edges(t):
if (e[1][0] == 'particle'):
ptcl = e[1]
... |
def process_chunk(infile, ev_start, ev_stop, outfile):
f = ROOT.TFile.Open(infile)
tree = f.Get('Delphes')
X_all = []
ygen_all = []
ygen_remaining_all = []
ycand_all = []
for iev in range(ev_start, ev_stop):
print('event {}/{} out of {} in the full file'.format(iev, ev_stop, tree.G... |
def process_chunk_args(args):
process_chunk(*args)
|
def chunks(lst, n):
'Yield successive n-sized chunks from lst.'
for i in range(0, len(lst), n):
(yield lst[i:(i + n)])
|
def parse_args():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--dir', type=str, default='parameters/delphes-gnn-skipconn.yaml', help='dir containing csv files')
args = parser.parse_args()
return args
|
def plot_gpu_util(df, cuda_device, ax):
ax.plot(df['time'], df['GPU{}_util'.format(cuda_device)], alpha=0.8)
ax.set_xlabel('Time [s]')
ax.set_ylabel('GPU utilization [%]')
ax.set_title('GPU{}'.format(cuda_device))
ax.grid(alpha=0.3)
|
def plot_gpu_power(df, cuda_device, ax):
ax.plot(df['time'], df['GPU{}_power'.format(cuda_device)], alpha=0.8)
ax.set_xlabel('Time [s]')
ax.set_ylabel('Power consumption [W]')
ax.set_title('GPU{}'.format(cuda_device))
ax.grid(alpha=0.3)
|
def plot_gpu_mem_util(df, cuda_device, ax):
ax.plot(df['time'], df['GPU{}_mem_util'.format(cuda_device)], alpha=0.8)
ax.set_xlabel('Time [s]')
ax.set_ylabel('GPU memory utilization [%]')
ax.set_title('GPU{}'.format(cuda_device))
ax.grid(alpha=0.3)
|
def plot_gpu_mem_used(df, cuda_device, ax):
ax.plot(df['time'], df['GPU{}_mem_used'.format(cuda_device)], alpha=0.8)
ax.set_xlabel('Time [s]')
ax.set_ylabel('Used GPU memory [MiB]')
ax.set_title('GPU{}'.format(cuda_device))
ax.grid(alpha=0.3)
|
def plot_dfs(dfs, plot_func, suffix):
(fig, axs) = plt.subplots(2, 2, figsize=(12, 9), tight_layout=True)
for ax in axs.flat:
ax.label_outer()
for (cuda_device, (df, ax)) in enumerate(zip(dfs, axs.flat)):
plot_func(df, cuda_device, ax)
plt.suptitle('{}'.format(file.stem))
plt.savef... |
class TestGNN(unittest.TestCase):
def helper_test_pairwise_dist_shape(self, dist_func):
A = tf.random.normal((2, 128, 32))
B = tf.random.normal((2, 128, 32))
out = dist_func(A, B)
self.assertEqual(out.shape, (2, 128, 128))
def test_pairwise_l2_dist_shape(self):
from m... |
class TestGNNTorchAndTensorflow(unittest.TestCase):
def test_GHConvDense(self):
from mlpf.tfmodel.model import GHConvDense
nn1 = GHConvDense(output_dim=128, activation='selu')
from mlpf.pyg.gnn_lsh import GHConvDense as GHConvDenseTorch
nn2 = GHConvDenseTorch(output_dim=128, activ... |
def maybe_download(filename, work_directory):
"Download the data from Yann's website, unless it's already here."
if (not os.path.exists(work_directory)):
os.mkdir(work_directory)
filepath = os.path.join(work_directory, filename)
if (not os.path.exists(filepath)):
(filepath, _) = urllib... |
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return int(numpy.frombuffer(bytestream.read(4), dtype=dt))
|
def extract_images(filename):
'Extract the images into a 4D uint8 numpy array [index, y, x, depth].'
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if (magic != 2051):
raise ValueError(('Invalid magic number %d in MNIST image f... |
def dense_to_one_hot(labels_dense, num_classes=10):
'Convert class labels from scalars to one-hot vectors.'
num_labels = labels_dense.shape[0]
index_offset = (numpy.arange(num_labels) * num_classes)
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[(index_offset + labels_... |
def extract_labels(filename, one_hot=False):
'Extract the labels into a 1D uint8 numpy array [index].'
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if (magic != 2049):
raise ValueError(('Invalid magic number %d in MNIST label... |
class DataSet(object):
def __init__(self, images, labels, fake_data=False):
if fake_data:
self._num_examples = 10000
else:
assert (images.shape[0] == labels.shape[0]), ('images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
self._num_examples = ima... |
def read_data_sets(train_dir, fake_data=False, one_hot=False):
class DataSets(object):
pass
data_sets = DataSets()
if fake_data:
data_sets.train = DataSet([], [], fake_data=True)
data_sets.validation = DataSet([], [], fake_data=True)
data_sets.test = DataSet([], [], fake_d... |
def maybe_download(filename, work_directory):
"Download the data from Yann's website, unless it's already here."
if (not os.path.exists(work_directory)):
os.mkdir(work_directory)
filepath = os.path.join(work_directory, filename)
if (not os.path.exists(filepath)):
(filepath, _) = urllib... |
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return int(numpy.frombuffer(bytestream.read(4), dtype=dt))
|
def extract_images(filename):
'Extract the images into a 4D uint8 numpy array [index, y, x, depth].'
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if (magic != 2051):
raise ValueError(('Invalid magic number %d in MNIST image f... |
def dense_to_one_hot(labels_dense, num_classes=10):
'Convert class labels from scalars to one-hot vectors.'
num_labels = labels_dense.shape[0]
index_offset = (numpy.arange(num_labels) * num_classes)
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[(index_offset + labels_... |
def extract_labels(filename, one_hot=False):
'Extract the labels into a 1D uint8 numpy array [index].'
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if (magic != 2049):
raise ValueError(('Invalid magic number %d in MNIST label... |
class DataSet(object):
def __init__(self, images, labels, fake_data=False):
if fake_data:
self._num_examples = 10000
else:
assert (images.shape[0] == labels.shape[0]), ('images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
self._num_examples = ima... |
def read_data_sets(train_dir, fake_data=False, one_hot=False):
class DataSets(object):
pass
data_sets = DataSets()
if fake_data:
data_sets.train = DataSet([], [], fake_data=True)
data_sets.validation = DataSet([], [], fake_data=True)
data_sets.test = DataSet([], [], fake_d... |
def make_chain():
chain = [1]
while (chain[(- 1)] != states[(- 1)]):
choices = transitions[chain[(- 1)]]
j = np.random.randint(len(choices))
chain.append(choices[j])
return chain
|
def valid_chain(chain):
if (len(chain) == 0):
return False
if (chain[0] != states[0]):
return False
for i in range(1, len(chain)):
if (chain[i] not in transitions[chain[(i - 1)]]):
return False
return True
|
def convert_chain(chain):
sequence = ''
for value in chain:
sequence += aliases[value]
return sequence
|
def load_id2any(index_file, format=None):
fspec = open(index_file)
ids = []
id2any = dict()
for line in fspec.readlines():
(id, any) = line.strip().split('\t')
ids.append(id)
if (format == 'toFloat'):
id2any[id] = [float(i) for i in eval(any)]
else:
... |
def split_magna(ids, id2path):
train_set = []
val_set = []
test_set = []
for id in ids:
path = id2path[id]
folder = int(path[(path.rfind('/') - 1):path.rfind('/')], 16)
if (folder < 12):
train_set.append(id)
elif (folder < 13):
val_set.append(id)... |
def write_gt_file(ids, id2gt, file_name):
fw = open(file_name, 'w')
for id in ids:
if (id in IDS_ERROR):
continue
fw.write(('%s\t%s\n' % (id, id2gt[id])))
fw.close()
|
def evaluation(batch_dispatcher, tf_vars, array_cost, pred_array, id_array):
[sess, normalized_y, cost, x, y_, is_train] = tf_vars
for batch in tqdm(batch_dispatcher):
(pred, cost_pred) = sess.run([normalized_y, cost], feed_dict={x: batch['X'], y_: batch['Y'], is_train: False})
if (not array_c... |
def model_number(x, is_training, config):
if (config['model_number'] == 0):
print('\nMODEL: Dieleman | BN input')
return models_baselines.dieleman(x, is_training, config)
elif (config['model_number'] == 1):
print('\nMODEL: VGG 32 | BN input')
return models_baselines.vgg(x, is_t... |
def dieleman(x, is_training, config):
print(('Input: ' + str(x.get_shape)))
input_layer = tf.expand_dims(x, 3)
bn_input = tf.compat.v1.layers.batch_normalization(input_layer, training=is_training)
conv1 = tf.compat.v1.layers.conv2d(inputs=bn_input, filters=32, kernel_size=[8, config['yInput']], paddin... |
def vgg(x, is_training, config, num_filters=32):
print(('Input: ' + str(x.get_shape)))
input_layer = tf.expand_dims(x, 3)
bn_input = tf.compat.v1.layers.batch_normalization(input_layer, training=is_training)
conv1 = tf.compat.v1.layers.conv2d(inputs=bn_input, filters=num_filters, kernel_size=[3, 3], p... |
def timbre(x, is_training, config, num_filt=1):
print(('Input: ' + str(x.get_shape)))
expanded_layer = tf.expand_dims(x, 3)
input_layer = tf.compat.v1.layers.batch_normalization(expanded_layer, training=is_training)
input_pad_7 = tf.pad(input_layer, [[0, 0], [3, 3], [0, 0], [0, 0]], 'CONSTANT')
in... |
def musically_motivated_cnns(x, is_training, yInput, num_filt, type):
expanded_layer = tf.expand_dims(x, 3)
input_layer = tf.compat.v1.layers.batch_normalization(expanded_layer, training=is_training)
input_pad_7 = tf.pad(input_layer, [[0, 0], [3, 3], [0, 0], [0, 0]], 'CONSTANT')
if ('timbral' in type)... |
def timbral_block(inputs, filters, kernel_size, is_training, padding='valid', activation=tf.nn.relu):
conv = tf.compat.v1.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, padding=padding, activation=activation)
bn_conv = tf.compat.v1.layers.batch_normalization(conv, training=is_training)... |
def tempo_block(inputs, filters, kernel_size, is_training, padding='same', activation=tf.nn.relu):
conv = tf.compat.v1.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, padding=padding, activation=activation)
bn_conv = tf.compat.v1.layers.batch_normalization(conv, training=is_training)
... |
def dense_cnns(front_end_output, is_training, num_filt):
front_end_pad = tf.pad(front_end_output, [[0, 0], [3, 3], [0, 0]], 'CONSTANT')
conv1 = tf.compat.v1.layers.conv1d(inputs=front_end_pad, filters=num_filt, kernel_size=7, padding='valid', activation=tf.nn.relu, kernel_initializer=tf.contrib.layers.varianc... |
def compute_audio_repr(audio_file, audio_repr_file):
(audio, sr) = librosa.load(audio_file, sr=config['resample_sr'])
if (config['type'] == 'waveform'):
audio_repr = audio
audio_repr = np.expand_dims(audio_repr, axis=1)
elif (config['spectrogram_type'] == 'mel'):
audio_repr = libro... |
def do_process(files, index):
try:
[id, audio_file, audio_repr_file] = files[index]
if (not os.path.exists(audio_repr_file[:(audio_repr_file.rfind('/') + 1)])):
path = Path(audio_repr_file[:(audio_repr_file.rfind('/') + 1)])
path.mkdir(parents=True, exist_ok=True)
l... |
def process_files(files):
if DEBUG:
print('WARNING: Parallelization is not used!')
for index in range(0, len(files)):
do_process(files, index)
else:
Parallel(n_jobs=config['num_processing_units'])((delayed(do_process)(files, index) for index in range(0, len(files))))
|
class Data():
'Standard data format. \n '
def __init__(self):
self.X_train = None
self.y_train = None
self.X_test = None
self.y_test = None
self.__device = None
self.__dtype = None
@property
def device(self):
return self.__device
@prope... |
class FNN(StructureNN):
'Fully connected neural networks.\n '
def __init__(self, ind, outd, layers=2, width=50, activation='relu', initializer='default', softmax=False):
super(FNN, self).__init__()
self.ind = ind
self.outd = outd
self.layers = layers
self.width = wi... |
class Module(torch.nn.Module):
'Standard module format. \n '
def __init__(self):
super(Module, self).__init__()
self.activation = None
self.initializer = None
self.__device = None
self.__dtype = None
@property
def device(self):
return self.__device
... |
class StructureNN(Module):
'Structure-oriented neural network used as a general map based on designing architecture.\n '
def __init__(self):
super(StructureNN, self).__init__()
def predict(self, x, returnnp=False):
return (self(x).cpu().detach().numpy() if returnnp else self(x))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.