code stringlengths 17 6.64M |
|---|
def unfreeze_t5(model):
model = (model.module if hasattr(model, 'module') else model)
for (name, child) in model.named_children():
if (name == 'gnn_model'):
continue
for param in child.parameters():
param.requires_grad = True
|
def overwrite_t5stack_forward(t5_stack):
def forward(self, input_ids=None, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, inputs_embeds=None, head_mask=None, cross_attn_head_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_d... |
def missing_grad_handler(model):
temp = 0
for (k, v) in model.named_parameters():
temp += v.sum()
return (temp * 0.0)
|
def train(model, optimizer, scheduler, step, train_dataset, eval_dataset, test_dataset, opt, collator, best_dev_em, checkpoint_path, relation_bank):
torch.manual_seed((opt.local_rank + opt.seed))
train_sampler = RandomSampler(train_dataset)
train_dataloader = DataLoader(train_dataset, sampler=train_sample... |
def evaluate(model, dataset, tokenizer, collator, opt, relation_bank, ifTest=False, step=0, checkpoint_path=None):
sampler = SequentialSampler(dataset)
dataloader = DataLoader(dataset, sampler=sampler, batch_size=(opt.per_gpu_batch_size * 2), drop_last=False, collate_fn=collator)
model.eval()
total = ... |
def play_game(model_name, env_name, game_queue, reward_queue, index):
'Plays one game with the given model and gym environment\n and returns the final score (i.e. cumulative reward)'
print('Starting process #{}..'.format(index))
if (not args.random):
model = torch.load(model_name, map_locati... |
def main():
set_start_method('spawn')
for model in args.models:
model_name = os.path.basename(os.path.normpath(model))
results_path = os.path.normpath(args.save)
if (not os.path.exists(results_path)):
os.mkdir(results_path)
results_name = '{}.txt'.format(model_name)... |
def main():
model = None
if (not args.random):
model = torch.load(args.model, map_location=device)
model.eval()
c = Connection(start_binary=(not args.dont_start_binary), binary_path=args.binary)
buttons = [buttons[0] for buttons in KEY_MAPPING[args.game]]
num_buttons = len(buttons)... |
def play_game(model_name, queue, index):
'Plays one game with the given model and gym environment\n and returns the final score (i.e. cumulative reward)'
print('Starting process #{}..'.format(index))
if (not args.random):
model = torch.load(model_name, map_location=device)
model.eval... |
def main():
set_start_method('spawn')
for model in args.models:
model_name = os.path.basename(os.path.normpath(model))
results_path = os.path.normpath(args.save)
if (not os.path.exists(results_path)):
os.mkdir(results_path)
results_name = '{}.txt'.format(model_name)... |
def get_avg_from_file(file_path):
with open(file_path) as f:
avg_line = f.readlines()[(- 1)]
match = re.match('Avg: (.*)', avg_line)
return float(match.group(1))
|
def get_stdev_from_file(file_path):
values = get_datapoints_from_file(file_path)
return statistics.stdev(values)
|
def get_datapoints_from_file(file_path):
with open(file_path) as f:
lines = f.readlines()
values = []
for line in lines:
try:
values.append(float(line))
except ValueError:
pass
return values
|
def finish_recording(recording_path, env_name, unique_id, data):
'Store recorded data into a json file'
trajectory_file = os.path.join(recording_path, 'trajectories_pressed_buttons', '{}'.format(env_name), '{}.json'.format(unique_id))
with open(trajectory_file, 'w') as f:
json.dump(data, f)
|
def start_recording(recording_path, env_name):
'\n Create and initialize any directories/files\n for recording, and return unique\n ID for this recording (timestamp).\n '
unique_id = str(int(time.time()))
screens_dir = os.path.join(recording_path, 'screens', '{}'.format(env_name), unique_id)
... |
def main(args):
c = Connection(start_binary=(not args.dont_start_binary), binary_path=args.binary)
record = False
recording_id = None
image_directory = None
recorded_data = []
recording_index = 0
recording_start_time = None
previous_response = None
previous_frame_time = None
fr... |
def compress_to_bytes(compress=True, **kwargs):
'\n Compress a dict of numpy arrays with .savez\n and return the bytes.\n\n Parameters:\n compress: If True, compress the bytes using\n compression algorithm (using LZ4)\n kwargs: Numpy arrays that will be stored.\n ... |
def decompress_to_arrays(array_bytes, compress=True):
'\n Decompress bytearray back to numpy arrays. Inverse\n of `compress_to_bytes`\n\n Parameters:\n bytearray: Bytearray to be decompressed\n compress: If True, bytes were compressed with\n LZ4 and require decompressing.\n... |
class AtariDataLoader():
'Keras Sequence where the elements are batches from the Atari dataset'
def __init__(self, directory, game, batch_size=32, stack=3, controls=18, size=(84, 84), percentile=None, top_n=None, augment=False, preload=False, merge=False, dqn=False, json=False, fileformat='png', action_delay... |
class AtariDataLoaderProcess(multiprocessing.Process):
'Process that runs a single AtariDataLoader instance'
def __init__(self, request_queue, response_queue, dataloader_args):
self.loader = AtariDataLoader(**dataloader_args)
self.request_queue = request_queue
self.response_queue = re... |
class MultiprocessAtariDataLoader():
'Creates multiple dataloader processes and serves data from them\n as an iterator\n \n Note: The iterator can return batches in any order, but is guaranteed\n to return every batch exactly once.\n '
def __init__(self, dataloader_args, workers):
supe... |
class AtariHeadDataloader():
def __init__(self, directory, batch_size=32, stack=3, controls=18, size=(84, 84), percentile=None, top_n=None, augment=False, preload=False, merge=False, dqn=False, action_delay=0, print_stats=False):
self.batch_size = batch_size
self.stack = stack
self.contro... |
class AtariDataLoaderProcess(multiprocessing.Process):
'Process that runs a single AtariDataLoader instance'
def __init__(self, request_queue, response_queue, dataloader_args):
self.loader = AtariHeadDataloader(**dataloader_args)
self.request_queue = request_queue
self.response_queue ... |
class MultiprocessAtariHeadDataLoader():
'Creates multiple dataloader processes and serves data from them\n as an iterator\n \n Note: The iterator can return batches in any order, but is guaranteed\n to return every batch exactly once.\n '
def __init__(self, dataloader_args, workers):
... |
def main(args):
input_data = None
with open(args.input) as f:
input_data = json.load(f)
key_mapping = KEY_MAPPING[args.game]
button_representatives = [buttons[0] for buttons in key_mapping]
new_data = {'allowed_buttons': button_representatives, 'steps': None}
new_steps = []
for ste... |
def human_normalized_score(score, random, human, stdev=None):
norm_score = ((100 * (score - random)) / (human - random))
if (stdev is not None):
upper = ((100 * ((score + stdev) - random)) / (human - random))
lower = ((100 * ((score - stdev) - random)) / (human - random))
return (norm_... |
def figure_nodelay_atari():
with open('results.json') as f:
results = json.load(f)
atari_games = ['Ms. Pac-Man', 'Video Pinball', 'Q*bert', "Montezuma's Revenge", 'Space Invaders']
(_, axs) = plt.subplots(len(atari_games), 1, sharex=True, figsize=(6, 8))
for (k, game) in enumerate(atari_games)... |
def figure_nodelay():
with open('results.json') as f:
results = json.load(f)
games = results['bc'].keys()
atari_games = ['Ms. Pac-Man', 'Video Pinball', 'Q*bert', "Montezuma's Revenge", 'Space Invaders']
games = [game for game in games if (game not in atari_games)]
(_, ax) = plt.subplots(1... |
def figure_delay():
with open('results.json') as f:
results = json.load(f)
(_, axs) = plt.subplots(2, 5, figsize=(12, 5), sharex=True)
coolwarm = cm.get_cmap('coolwarm', 9)
colors = [coolwarm(x) for x in np.linspace(0, 1, 9)]
for row in range(2):
if (row == 0):
dataset ... |
def figure_learning():
def get_avg_from_file(file_path):
with open(file_path) as f:
avg_line = f.readlines()[(- 1)]
match = re.match('Avg: (.*)', avg_line)
return float(match.group(1))
def get_stdev_from_file(file_path):
values = get_datapoints_from_file(f... |
def main(args):
scores = []
for filepath in args.inputs:
json_data = None
with open(filepath) as f:
json_data = json.load(f)
rewards = [step['r'] for step in json_data['steps']]
scores.append(sum(rewards))
print('Individual scores: ')
pprint(scores)
prin... |
class Mnih2015(nn.Module):
'CNN head similar to one used in Mnih 2015\n (Human-level control through deep reinforcement learning, Mnih 2015)'
def __init__(self, image_shape, num_channels, num_actions):
super(Mnih2015, self).__init__()
self.num_actions = num_actions
self.conv1 = ... |
class Connection():
'Automatically starts the binary and creates a socket connection to it.\n\n When started with the default arguments, will start the binary on an open\n port and connect to it.\n\n If start_binary is set to False, the binary will\n not be automatically started, and connection will i... |
def load(in_file=None, format='tsv'):
' Load a clustering from a file. By default the input file is a\n tab-separated listing of words and their cluster ID. Returns a dictionary of\n the clustering.\n\n Args:\n in_file (string): path to input file\n format (string): input file format (defau... |
def save(mapping=None, out=None, format='tsv'):
' Save a clustering (dictionary) to file. By default the output file is\n a tab-separated listing of words and their cluster ID.\n\n Args:\n mapping (dict): word-to-tag mapping\n out (string): path to output file\n format (string): output ... |
def tag_string(mapping=None, text=None, unk=unk):
"Tag a string with the corresponding cluster ID's. If a word is not\n found in the clustering, use unk.\n\n Args:\n mapping (dict): word-to-tag mapping\n text (string): the string to be tagged\n unk (string): what to label unknown/unseen... |
def tag_stdin(mapping=None, unk=unk):
' This calls tag_string() for each line in stdin, and prints the\n result to stdout.\n\n Args:\n mapping (dict): word-to-tag mapping\n unk (string): what to label unknown/unseen words that are not in\n mapping (default: <unk>)\n '
... |
def cluster(text=None, in_file=None, classes=None, class_file=None, class_offset=None, forward_lambda=None, ngram_input=None, min_count=None, out=None, print_freqs=None, quiet=None, refine=None, rev_alternate=None, threads=None, tune_cycles=None, unidirectional=None, verbose=None, word_vectors=None):
'\n Produ... |
def main():
' No real reason to use this as a standalone script. Just invoke the\n C-compiled binary for standalone applications. But here you\n go, anyways.\n '
import argparse
parser = argparse.ArgumentParser(description='Clusters words, or tags them')
parser.add_argument('-i', '-... |
class Generator(nn.Module):
def __init__(self, params):
super().__init__()
self.noise_dim = params.noise_dims
self.gkernel = gkern1D(params.gkernlen, params.gkernsig)
self.FC = nn.Sequential(nn.Linear(self.noise_dim, 256), nn.LeakyReLU(0.2), nn.Dropout(p=0.2), nn.Linear(256, (32 *... |
class Params():
'Class that loads hyperparameters from a json file.\n\n Example:\n ```\n params = Params(json_path)\n print(params.learning_rate)\n params.learning_rate = 0.5 # change the value of learning_rate in params\n ```\n '
def __init__(self, json_path):
self.update(json_... |
def set_logger(log_path):
'Sets the logger to log info in terminal and file `log_path`.\n\n In general, it is useful to have a logger so that every output to the terminal is saved\n in a permanent file. Here we save it to `model_dir/train.log`.\n\n Example:\n ```\n logging.info("Starting training..... |
def save_dict_to_json(d, json_path):
'Saves dict of floats in json file\n\n Args:\n d: (dict) of float-castable values (np.float, int, float, etc.)\n json_path: (string) path to json file\n '
with open(json_path, 'w') as f:
d = {k: float(v) for (k, v) in d.items()}
json.dum... |
def row_csv2dict(csv_file):
dict_club = {}
with open(csv_file) as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
dict_club[(row[0], row[1])] = row[2]
return dict_club
|
def save_checkpoint(state, checkpoint):
"Saves model and training parameters at checkpoint + 'last.pth.tar'. If is_best==True, also saves\n checkpoint + 'best.pth.tar'\n Args:\n state: (dict) contains model's state_dict, may contain other keys such as epoch, optimizer state_dict\n is_best: (bo... |
def load_checkpoint(checkpoint, model, optimizer=None, scheduler=None):
'Loads model parameters (state_dict) from file_path. If optimizer is provided, loads state_dict of\n optimizer assuming it is present in checkpoint.\n Args:\n checkpoint: (string) filename which needs to be loaded\n model:... |
def plot_loss_history(loss_history, params):
(effs_mean_history, diversity_history, binarization_history) = loss_history
iterations = [(i * params.plot_iter) for i in range(len(effs_mean_history))]
plt.figure()
plt.plot(iterations, effs_mean_history)
plt.plot(iterations, diversity_history)
plt... |
def plot_histogram(Effs, Iter, fig_path):
ax = plt.figure()
bins = [(i * 5) for i in range(21)]
plt.hist((Effs * 100), bins, facecolor='blue', alpha=0.5)
plt.xlim(0, 100)
plt.ylim(0, 50)
plt.yticks([])
plt.xticks(fontsize=12)
plt.xlabel('Deflection efficiency (%)', fontsize=12)
plt... |
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.initialized = False
def initialize(self):
self.parser.add_argument('--G', type=str, default='UnetINDiv4_CCAM', help='choice of network for Gener... |
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.initialized = False
def initialize(self):
self.parser.add_argument('--G', type=str, default='NVDLMED', help='choice of network')
self.pa... |
class TrainingInstance(object):
'A single training instance (sentence pair).'
def __init__(self, tokens):
self.tokens = tokens
self.input_tokens = tokens
self.target_tokens = tokens
def __str__(self):
s = ''
s += ('tokens: %s\n' % ' '.join([tokenization.printable_... |
def write_instance_to_example_files(instances, word_to_id, max_seq_length, output_files):
'Create TF example files from `TrainingInstance`s.'
writers = []
for output_file in output_files:
writers.append(tf.python_io.TFRecordWriter(output_file))
writer_index = 0
total_written = 0
for (i... |
def create_int_feature(values):
feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return feature
|
def create_float_feature(values):
feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
return feature
|
def create_training_instances(all_tokens, vocab_words, max_seq_length, rng):
'Create `TrainingInstance`s from raw text.'
rng.shuffle(all_tokens)
instances = []
print('Process of "create_training_instances"')
for tokens in all_tokens:
instances.append(create_instances_from_sentence(tokens, ... |
def create_instances_from_sentence(tokens, max_seq_length, rng):
'Creates `TrainingInstance`s for a single sentence.'
max_num_tokens = (max_seq_length - 2)
assert (len(tokens) >= 1)
if (len(tokens) >= max_num_tokens):
truncate_seq(tokens, max_num_tokens, rng)
if (tokens[0] is not '[SOS]'):... |
def truncate_seq(tokens, max_num_tokens, rng):
'Truncates a sequence to a maximum sequence length.'
while True:
total_length = len(tokens)
if (total_length <= max_num_tokens):
break
trunc_tokens = tokens
assert (len(trunc_tokens) >= 1)
if (rng.random() < 0.5... |
def read_all_sentences(input_files):
all_sentences = []
for input_file in input_files:
with open(input_file, 'r') as reader:
for line in reader.readlines():
line = line.strip()
if (not line):
continue
else:
... |
def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu):
'Creates an optimizer training op.'
global_step = tf.train.get_or_create_global_step()
learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32)
learning_rate = tf.train.polynomial_decay(learning_rate, global... |
class AdamWeightDecayOptimizer(tf.train.Optimizer):
'A basic Adam optimizer that includes "correct" L2 weight decay.'
def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, name='AdamWeightDecayOptimizer'):
'Constructs a AdamW... |
def model_fn_builder(config, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings):
'Returns `model_fn` closure for TPUEstimator.'
def model_fn(features, labels, mode, params):
'The `model_fn` for TPUEstimator.'
tf.logging.info('*** Features ***')... |
def get_lm_output(config, input_tensor, output_weights, label_ids, label_mask):
'Get loss and log probs for the LM.'
input_shape = modeling.get_shape_list(input_tensor, expected_rank=3)
input_tensor = tf.reshape(input_tensor, [(input_shape[0] * input_shape[1]), input_shape[2]])
with tf.variable_scope(... |
def input_fn_builder(input_files, max_seq_length, is_training, num_cpu_threads=4):
'Creates an `input_fn` closure to be passed to TPUEstimator.'
def input_fn(params):
'The actual input function.'
batch_size = params['batch_size']
name_to_features = {'input_ids': tf.FixedLenFeature([ma... |
def _decode_record(record, name_to_features):
'Decodes a record to a TensorFlow example.'
example = tf.parse_single_example(record, name_to_features)
for name in list(example.keys()):
t = example[name]
if (t.dtype == tf.int64):
t = tf.to_int32(t)
example[name] = t
r... |
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
if ((not FLAGS.do_train) and (not FLAGS.do_eval)):
raise ValueError('At least one of `do_train` or `do_eval` must be True.')
config = modeling.BertConfig.from_json_file(FLAGS.config_file)
tf.gfile.MakeDirs(FLAGS.output_dir)
src = FLAGS... |
class TestingInstance(object):
'A single test instance (sentence pair).'
def __init__(self, tokens):
self.tokens = tokens
self.input_tokens = tokens
self.target_tokens = tokens
def __str__(self):
s = ''
s += ('tokens: %s\n' % ' '.join([tokenization.printable_text(... |
def create_testing_instances(sentence, tokenizer, max_seq_length=128):
'Create `TestInstance`s from raw text.'
max_token_num = (max_seq_length - 2)
tokens = tokenizer.tokenize(sentence)
if (len(tokens) > max_token_num):
tokens = tokens[:max_token_num]
if (tokens[0] is not '[SOS]'):
... |
def create_instances_from_tokens(tokens):
'Creates `TestInstance`s for a single sentence.'
instance = TestingInstance(tokens)
return instance
|
def validate_case_matches_checkpoint(do_lower_case, init_checkpoint):
'Checks whether the casing config is consistent with the checkpoint name.'
if (not init_checkpoint):
return
m = re.match('^.*?([A-Za-z0-9_-]+)/bert_model.ckpt', init_checkpoint)
if (m is None):
return
model_name ... |
def convert_to_unicode(text):
"Converts `text` to Unicode (if it's not already), assuming utf-8 input."
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Uns... |
def printable_text(text):
'Returns text encoded in a way suitable for print or `tf.logging`.'
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Unsupported s... |
def load_vocab(vocab_file):
'Loads a vocabulary file into a dictionary.'
vocab = collections.OrderedDict()
index = 0
with tf.gfile.GFile(vocab_file, 'r') as reader:
while True:
token = convert_to_unicode(reader.readline())
if (not token):
break
... |
def convert_by_vocab(vocab, items):
'Converts a sequence of [tokens|ids] using the vocab.'
output = []
for item in items:
output.append(vocab[item])
return output
|
def convert_tokens_to_ids(vocab, tokens):
return convert_by_vocab(vocab, tokens)
|
def convert_ids_to_tokens(inv_vocab, ids):
return convert_by_vocab(inv_vocab, ids)
|
def whitespace_tokenize(text):
'Runs basic whitespace cleaning and splitting on a piece of text.'
text = text.strip()
if (not text):
return []
tokens = text.split()
return tokens
|
class FullTokenizer(object):
'Runs end-to-end tokenziation.'
def __init__(self, vocab_file, do_lower_case=True):
self.vocab = load_vocab(vocab_file)
self.inv_vocab = {v: k for (k, v) in self.vocab.items()}
self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
self... |
class BasicTokenizer(object):
'Runs basic tokenization (punctuation splitting, lower casing, etc.).'
def __init__(self, do_lower_case=True):
'Constructs a BasicTokenizer.\n\n Args:\n do_lower_case: Whether to lower case the input.\n '
self.do_lower_case = do_lower_case
def tok... |
class WordpieceTokenizer(object):
'Runs WordPiece tokenziation.'
def __init__(self, vocab, unk_token='[UNK]', max_input_chars_per_word=200):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
'T... |
def _is_whitespace(char):
'Checks whether `chars` is a whitespace character.'
if ((char == ' ') or (char == '\t') or (char == '\n') or (char == '\r')):
return True
cat = unicodedata.category(char)
if (cat == 'Zs'):
return True
return False
|
def _is_control(char):
'Checks whether `chars` is a control character.'
if ((char == '\t') or (char == '\n') or (char == '\r')):
return False
cat = unicodedata.category(char)
if cat.startswith('C'):
return True
return False
|
def _is_punctuation(char):
'Checks whether `chars` is a punctuation character.'
cp = ord(char)
if (((cp >= 33) and (cp <= 47)) or ((cp >= 58) and (cp <= 64)) or ((cp >= 91) and (cp <= 96)) or ((cp >= 123) and (cp <= 126))):
return True
cat = unicodedata.category(char)
if cat.startswith('P'... |
def path2gt(file_path, dataset):
if (dataset == 'GTZAN'):
return gtzan_path2gt(file_path)
elif (dataset == 'Ballroom'):
return ballroom_path2gt(file_path)
elif (dataset == 'ExtendedBallroom'):
return extended_ballroom_path2gt(file_path)
elif (dataset == 'UrbanSound8K'):
... |
def gtzan_path2gt(file_path):
tag = file_path[(file_path.rfind('/') + 1):file_path.rfind('.', 0, (- 4))]
print(tag)
if (tag == 'blues'):
return 0
elif (tag == 'classical'):
return 1
elif (tag == 'country'):
return 2
elif (tag == 'disco'):
return 3
elif (tag ... |
def ballroom_path2gt(file_path):
cut_end = file_path[:file_path.rfind('/')]
tag = cut_end[(cut_end.rfind('/') + 1):]
print(tag)
if (tag == 'ChaChaCha'):
return 0
elif (tag == 'Jive'):
return 1
elif (tag == 'Quickstep'):
return 2
elif (tag == 'Rumba'):
return... |
def extended_ballroom_path2gt(file_path):
cut_end = file_path[:file_path.rfind('/')]
tag = cut_end[(cut_end.rfind('/') + 1):]
print(tag)
if (tag == 'Chacha'):
return 0
elif (tag == 'Foxtrot'):
return 1
elif (tag == 'Jive'):
return 2
elif (tag == 'Pasodoble'):
... |
def urban_sound_path2gt(file_path):
tag = file_path[(file_path.rfind('/') + 1):]
print(tag)
df = pd.read_csv('/datasets/MTG/users/jpons/urban_sounds/UrbanSound8K/metadata/UrbanSound8K.csv')
return int(df[(df.slice_file_name == tag)].classID)
|
def build(config, x_in):
if (config['CNN']['architecture'] == 'cnn_small_filters'):
return cnn_small_filters(config, x_in)
elif (config['CNN']['architecture'] == 'cnn_single'):
return cnn_single(config, x_in)
elif (config['CNN']['architecture'] == 'cnn_music'):
return cnn_music(con... |
def cnn_small_filters(config, x_in):
with tf.name_scope('cnn_small_filters'):
print(('[SMALL FILTERS] Input: ' + str(x_in.get_shape)))
input_layer = tf.reshape(x_in, [(- 1), config['CNN']['n_frames'], config['CNN']['n_mels'], 1])
conv1 = tf.layers.conv2d(inputs=input_layer, filters=config[... |
def cnn_single(config, x_in):
with tf.name_scope('cnn_single'):
print(('[CNN SINGLE] Input: ' + str(x_in.get_shape)))
input_layer = tf.reshape(x_in, [(- 1), config['CNN']['n_frames'], config['CNN']['n_mels'], 1])
conv1 = tf.layers.conv2d(inputs=input_layer, filters=config['CNN']['num_filte... |
def cnn_music(config, x_in):
if (config['CNN']['num_filters'] == 256):
remove = 64
elif (config['CNN']['num_filters'] == 128):
remove = 32
elif (config['CNN']['num_filters'] == 64):
remove = 16
elif (config['CNN']['num_filters'] == 32):
remove = 8
elif (config['CNN'... |
def backend(route_out, config):
"Function implementing the proposed back-end.\n - 'route_out': is the output of the front-end, and therefore the input of this function.\n - 'config': dictionary with some configurable parameters like: number of output units - config['numOutputNeurons']\n or nu... |
def sample_level(config, x_in):
'Function implementing the front-end proposed by Lee et al. 2017.\n Lee, et al. "Sample-level Deep Convolutional Neural Networks for Music Auto-tagging Using Raw Waveforms." \n arXiv preprint arXiv:1703.01789 (2017).\n - \'x\': placeholder whith the input.\n - \'i... |
def frame_level(config, x_in):
conv1 = tf.layers.conv1d(inputs=x_in, filters=config['CNN']['num_filters'], kernel_size=512, strides=32, padding='valid', activation=tf.nn.relu, kernel_initializer=tf.contrib.layers.variance_scaling_initializer())
front_end_out = tf.expand_dims(conv1, 3)
[end_c1, end_cr2, en... |
def frame_level_many(config, x_in):
conv0 = tf.layers.conv1d(inputs=x_in, filters=config['CNN']['num_filters'], kernel_size=512, strides=32, padding='same', activation=tf.nn.relu, kernel_initializer=tf.contrib.layers.variance_scaling_initializer())
conv1 = tf.layers.conv1d(inputs=x_in, filters=config['CNN']['... |
def cnn_audio(config, x_in):
if (config['CNN']['num_filters'] == 256):
remove = 64
elif (config['CNN']['num_filters'] == 128):
remove = 32
elif (config['CNN']['num_filters'] == 64):
remove = 16
elif (config['CNN']['num_filters'] == 32):
remove = 8
elif (config['CNN'... |
class BaseELM(BaseEstimator):
'\n Base class for ELMs.\n\n Warning: This class should not be used directly.\n Use derived classes instead.\n '
__metaclass__ = ABCMeta
def __init__(self, hidden_layer, regressor):
self.regressor = regressor
self.hidden_layer = hidden_layer
... |
class GenELMRegressor(BaseELM, RegressorMixin):
'\n ELMRegressor is a regressor based on the Extreme Learning Machine.\n\n An Extreme Learning Machine (ELM) is a single layer feedforward\n network with a random hidden layer components and ordinary linear\n least squares fitting of the hidden->output w... |
class GenELMClassifier(BaseELM, ClassifierMixin):
'\n GenELMClassifier is a classifier based on the Extreme Learning Machine.\n\n An Extreme Learning Machine (ELM) is a single layer feedforward\n network with a random hidden layer components and ordinary linear\n least squares fitting of the hidden->o... |
class ELMRegressor(BaseEstimator, RegressorMixin):
'\n ELMRegressor is a regressor based on the Extreme Learning Machine.\n\n An Extreme Learning Machine (ELM) is a single layer feedforward\n network with a random hidden layer components and ordinary linear\n least squares fitting of the hidden->outpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.