code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def from_json_file(cls, json_file): """Constructs a `NewsConfig` from a json file of parameters.""" with tf.gfile.GFile(json_file, "r") as reader: text = reader.read() return cls.from_dict(json.loads(text))
Constructs a `NewsConfig` from a json file of parameters.
from_json_file
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def mask_attention_for_ltr(attention_scores, attention_mask): """ Mask attention so that we're only predicting going forward :param attention_scores: [batch, heads, dst_sequence, src_sequence], where information flows from src to dst. :param attention_mask [query_length, key_length] :return: masked attention """ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. mask = attention_mask[None, None] return attention_scores * mask - tf.cast(1e10, attention_scores.dtype) * (1 - mask)
Mask attention so that we're only predicting going forward :param attention_scores: [batch, heads, dst_sequence, src_sequence], where information flows from src to dst. :param attention_mask [query_length, key_length] :return: masked attention
mask_attention_for_ltr
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def _attention_projection_and_transpose(x_flat, batch_size, seq_length, num_attention_heads, size_per_head, name, initializer_range=0.02): """ :param x_flat: [batch_size*seq_length, width] :return: A fixed up tensor of size [batch_size, num_attention_heads, seq_length, size_per_head] """ batch_size_seq_length, dim = get_shape_list(x_flat, expected_rank=2) # Had to remove this bc of generation script # if (batch_size_seq_length != batch_size * seq_length): # raise ValueError("passed in a tensor of shape {} when batch_size={} and seq_length={}".format( # (batch_size_seq_length, dim), batch_size, seq_length # )) if dim != size_per_head * num_attention_heads: raise ValueError("passed in a tensor of shape {} when size_per_head={} and num_attention_heads={}".format( (batch_size_seq_length, dim), size_per_head, num_attention_heads )) projected = tf.layers.dense( x_flat, num_attention_heads * size_per_head, name=name, kernel_initializer=create_initializer(initializer_range)) projected = tf.reshape( projected, [batch_size, seq_length, num_attention_heads, size_per_head]) output_tensor = tf.transpose(projected, [0, 2, 1, 3]) return output_tensor
:param x_flat: [batch_size*seq_length, width] :return: A fixed up tensor of size [batch_size, num_attention_heads, seq_length, size_per_head]
_attention_projection_and_transpose
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def attention_layer(x_flat, attention_mask, batch_size, seq_length, size_per_head=512, num_attention_heads=1, *, cache=None, initializer_range=0.02, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, do_cache=False): """ :param x_flat: Tensor input, should be [batch_size*seq_length, dim] :param attention_mask: Attention mask to use of size [seq_length, seq_length+cached_length] :param size_per_head: dim = size_per_head * num_attention_heads :param num_attention_heads: dim = size_per_head * num_attention_heads :param cache: Optionally some past (cached) things of size [batch, 2, heads, sequence, features], where 2 is [k, v] :param do_cache: True if we should return cache :return: A new tensor of shape [batch_size, seq_length, dim] as well as a new cache "cached_keys_and_values" that will be of size [batch_size, 2, num_attention_heads, seq_length, dim] """ batch_size_seq_length, dim = get_shape_list(x_flat, expected_rank=2) # Had to remove this because of generation script # if (batch_size_seq_length != batch_size * seq_length): # raise ValueError("passed in a tensor of shape {} when batch_size={} and seq_length={}".format( # (batch_size_seq_length, dim), batch_size, seq_length # )) if dim != size_per_head * num_attention_heads: raise ValueError("passed in a tensor of shape {} when size_per_head={} and num_attention_heads={}".format( (batch_size_seq_length, dim), size_per_head, num_attention_heads )) # if do_cache and past is not None: # Shape will be (batch_size, 2, num_attention_heads, past_seq_length, dim) # past_shape = get_shape_list(past, 5) # desired_shape = (batch_size, 2, num_attention_heads, seq_length, dim) # if tuple(past_shape) != desired_shape: # raise ValueError(f"The shape of the cache is {past_shape} but we want {desired_shape}") # [ batch_size, num_attention_heads, seq_length, size_per_head] query = _attention_projection_and_transpose(x_flat, batch_size=batch_size, seq_length=seq_length, num_attention_heads=num_attention_heads, size_per_head=size_per_head, name='query_layer', initializer_range=initializer_range) key = _attention_projection_and_transpose(x_flat, batch_size=batch_size, seq_length=seq_length, num_attention_heads=num_attention_heads, size_per_head=size_per_head, name='key_layer', initializer_range=initializer_range) value = _attention_projection_and_transpose(x_flat, batch_size=batch_size, seq_length=seq_length, num_attention_heads=num_attention_heads, size_per_head=size_per_head, name='value_layer', initializer_range=initializer_range) # Add to cache cached_keys_and_values = tf.stack([key, value], axis=1) if do_cache else None # Things that were relevant from the cache if cache is not None: pk, pv = tf.unstack(cache, axis=1) key = tf.concat([pk, key], axis=-2) value = tf.concat([pv, value], axis=-2) # Multiply [batch_size, num_attention_heads, seq_length, size_per_head] with # [batch_size, num_attention_heads, size_per_head, seq_length+cached_length] -> # [batch_size, num_attention_heads, seq_length, seq_length+cached_length] attention_scores = tf.matmul(query, key, transpose_b=True) attention_scores = tf.multiply(attention_scores, 1.0 / math.sqrt(float(size_per_head))) attention_scores = mask_attention_for_ltr(attention_scores, attention_mask) attention_probs = tf.nn.softmax(attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. # NOPENOPENOPENOPE # attention_probs = factoreddropout(attention_probs, attention_probs_dropout_prob) # Multiply [batch_size, num_attention_heads, seq_length, seq_length+cached_length] with # [batch_size, num_attention_heads, seq_length+cached_length, size_per_head] -> # [batch_size, num_attention_heads, seq_length, size_per_head] -> context_layer = tf.matmul(attention_probs, value) # `context_layer` = [batch_size, seq_length, num_attention_heads, size_per_head] context_layer = tf.transpose(context_layer, [0, 2, 1, 3]) context_layer = tf.reshape(context_layer, [batch_size * seq_length, num_attention_heads * size_per_head]) context_layer_projected = tf.layers.dense( context_layer, num_attention_heads * size_per_head, kernel_initializer=create_initializer(initializer_range), name='context_projection_layer' ) context_layer_projected = dropout(context_layer_projected, hidden_dropout_prob) return context_layer_projected, cached_keys_and_values
:param x_flat: Tensor input, should be [batch_size*seq_length, dim] :param attention_mask: Attention mask to use of size [seq_length, seq_length+cached_length] :param size_per_head: dim = size_per_head * num_attention_heads :param num_attention_heads: dim = size_per_head * num_attention_heads :param cache: Optionally some past (cached) things of size [batch, 2, heads, sequence, features], where 2 is [k, v] :param do_cache: True if we should return cache :return: A new tensor of shape [batch_size, seq_length, dim] as well as a new cache "cached_keys_and_values" that will be of size [batch_size, 2, num_attention_heads, seq_length, dim]
attention_layer
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def residual_mlp_layer(x_flat, intermediate_size, initializer_range=0.02, hidden_dropout_prob=0.1): """ :param x: The attention output. It should be [batch_size*seq_length, dim] :param intermediate_size: the hidden projection. By default this is the input_dim * 4. in the original GPT we would return layer_norm(x_norm + h1) rather than layer_norm(x + h1) :return: """ batch_size_seq_length, hidden_size = get_shape_list(x_flat, expected_rank=2) x_norm = layer_norm(x_flat, name='mlp_ln0') intermediate_output = tf.layers.dense( x_norm, intermediate_size, activation=gelu, kernel_initializer=create_initializer(initializer_range), name='intermediate', ) output_for_residual = tf.layers.dense( intermediate_output, hidden_size, name='output', kernel_initializer=create_initializer(initializer_range)) output_for_residual = dropout(output_for_residual, hidden_dropout_prob) layer_output = layer_norm(x_flat + output_for_residual, name='mlp_ln1') return layer_output
:param x: The attention output. It should be [batch_size*seq_length, dim] :param intermediate_size: the hidden projection. By default this is the input_dim * 4. in the original GPT we would return layer_norm(x_norm + h1) rather than layer_norm(x + h1) :return:
residual_mlp_layer
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def embed(input_ids, vocab_size, embedding_size, position_offset=0, initializer_range=0.02, max_position_embeddings=512, use_one_hot_embeddings=True): """reur and position embeddings :param input_ids: int Tensor of shape [batch_size, seq_length]. :param vocab_size: number of words in vocab :param embedding_size: dimensionality of the embedding :param position_offset: aka number of cached tokens. :param initializer_range: float. Range of the weight initialization. :param max_position_embeddings: int. Maximum sequence length. :param use_one_hot_embeddings: probably want this to be true :return: [batch_size, seq_length, embedding_size] embedded tensor """ (batch_size, seq_length) = get_shape_list(input_ids, expected_rank=2) embedding_table = tf.get_variable( name='word_embed', shape=[vocab_size, embedding_size], initializer=create_initializer(initializer_range), ) assert_op = tf.assert_less_equal(tf.reduce_max(input_ids), vocab_size - 1) with tf.control_dependencies([assert_op]): if use_one_hot_embeddings: flat_input_ids = tf.reshape(input_ids, [-1]) one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size) output_flat = tf.matmul(one_hot_input_ids, embedding_table) else: output_flat = tf.nn.embedding_lookup(embedding_table, input_ids) embedded_input = tf.reshape(output_flat, [batch_size, seq_length, embedding_size]) assert_op = tf.assert_less_equal(seq_length, max_position_embeddings) with tf.control_dependencies([assert_op]): full_position_embeddings = tf.get_variable( name='pos_embed', shape=[max_position_embeddings, embedding_size], initializer=create_initializer(initializer_range), ) # Since the position embedding table is a learned variable, we create it # using a (long) sequence length `max_position_embeddings`. The actual # sequence length might be shorter than this, for faster training of # tasks that do not have long sequences. # # So `full_position_embeddings` is effectively an embedding table # for position [0, 1, 2, ..., max_position_embeddings-1], and the current # sequence has positions [0, 1, 2, ... seq_length-1], so we can just # perform a slice. if position_offset == 0: embedded_input += tf.slice(full_position_embeddings, [0, 0], [seq_length, -1])[None] else: # Tensorflow is too stupid to allow slicing flat_pos_ids = (tf.range(seq_length, dtype=tf.int32) + position_offset) one_hot_pos_ids = tf.one_hot(flat_pos_ids, depth=max_position_embeddings) # [seq_length, full_position_embeddings], [full_position_embeddings, dim] seq_embeds = tf.matmul(one_hot_pos_ids, full_position_embeddings) embedded_input += seq_embeds[None] # embedded_input += tf.slice(full_position_embeddings[position_offset:], [0, 0], [seq_length, -1])[None] return layer_norm(embedded_input, name='embed_norm'), embedding_table
reur and position embeddings :param input_ids: int Tensor of shape [batch_size, seq_length]. :param vocab_size: number of words in vocab :param embedding_size: dimensionality of the embedding :param position_offset: aka number of cached tokens. :param initializer_range: float. Range of the weight initialization. :param max_position_embeddings: int. Maximum sequence length. :param use_one_hot_embeddings: probably want this to be true :return: [batch_size, seq_length, embedding_size] embedded tensor
embed
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def _top_p_sample(logits, ignore_ids=None, num_samples=1, p=0.9): """ Does top-p sampling. if ignore_ids is on, then we will zero out those logits. :param logits: [batch_size, vocab_size] tensor :param ignore_ids: [vocab_size] one-hot representation of the indices we'd like to ignore and never predict, like padding maybe :param p: topp threshold to use, either a float or a [batch_size] vector :return: [batch_size, num_samples] samples # TODO FIGURE OUT HOW TO DO THIS ON TPUS. IT'S HELLA SLOW RIGHT NOW, DUE TO ARGSORT I THINK """ with tf.variable_scope('top_p_sample'): batch_size, vocab_size = get_shape_list(logits, expected_rank=2) probs = tf.nn.softmax(logits if ignore_ids is None else logits - tf.cast(ignore_ids[None], tf.float32) * 1e10, axis=-1) if isinstance(p, float) and p > 0.999999: # Don't do top-p sampling in this case print("Top-p sampling DISABLED", flush=True) return { 'probs': probs, 'sample': tf.random.categorical( logits=logits if ignore_ids is None else logits - tf.cast(ignore_ids[None], tf.float32) * 1e10, num_samples=num_samples, dtype=tf.int32), } # [batch_size, vocab_perm] indices = tf.argsort(probs, direction='DESCENDING') cumulative_probabilities = tf.math.cumsum(tf.batch_gather(probs, indices), axis=-1, exclusive=False) # find the top pth index to cut off. careful we don't want to cutoff everything! # result will be [batch_size, vocab_perm] p_expanded = p if isinstance(p, float) else p[:, None] exclude_mask = tf.logical_not( tf.logical_or(cumulative_probabilities < p_expanded, tf.range(vocab_size)[None] < 1)) # OPTION A - sample in the sorted space, then unsort. logits_to_use = tf.batch_gather(logits, indices) - tf.cast(exclude_mask, tf.float32) * 1e10 sample_perm = tf.random.categorical(logits=logits_to_use, num_samples=num_samples) sample = tf.batch_gather(indices, sample_perm) # OPTION B - unsort first - Indices need to go back to 0 -> N-1 -- then sample # unperm_indices = tf.argsort(indices, direction='ASCENDING') # include_mask_unperm = tf.batch_gather(include_mask, unperm_indices) # logits_to_use = logits - (1 - tf.cast(include_mask_unperm, tf.float32)) * 1e10 # sample = tf.random.categorical(logits=logits_to_use, num_samples=num_samples, dtype=tf.int32) return { 'probs': probs, 'sample': sample, }
Does top-p sampling. if ignore_ids is on, then we will zero out those logits. :param logits: [batch_size, vocab_size] tensor :param ignore_ids: [vocab_size] one-hot representation of the indices we'd like to ignore and never predict, like padding maybe :param p: topp threshold to use, either a float or a [batch_size] vector :return: [batch_size, num_samples] samples # TODO FIGURE OUT HOW TO DO THIS ON TPUS. IT'S HELLA SLOW RIGHT NOW, DUE TO ARGSORT I THINK
_top_p_sample
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def _top_k_sample(logits, ignore_ids=None, num_samples=1, k=10): """ Does top-k sampling. if ignore_ids is on, then we will zero out those logits. :param logits: [batch_size, vocab_size] tensor :param ignore_ids: [vocab_size] one-hot representation of the indices we'd like to ignore and never predict, like padding maybe :param p: topp threshold to use, either a float or a [batch_size] vector :return: [batch_size, num_samples] samples # TODO FIGURE OUT HOW TO DO THIS ON TPUS. IT'S HELLA SLOW RIGHT NOW, DUE TO ARGSORT I THINK """ with tf.variable_scope('top_p_sample'): batch_size, vocab_size = get_shape_list(logits, expected_rank=2) probs = tf.nn.softmax(logits if ignore_ids is None else logits - tf.cast(ignore_ids[None], tf.float32) * 1e10, axis=-1) # [batch_size, vocab_perm] indices = tf.argsort(probs, direction='DESCENDING') # find the top pth index to cut off. careful we don't want to cutoff everything! # result will be [batch_size, vocab_perm] k_expanded = k if isinstance(k, int) else k[:, None] exclude_mask = tf.range(vocab_size)[None] >= k_expanded # OPTION A - sample in the sorted space, then unsort. logits_to_use = tf.batch_gather(logits, indices) - tf.cast(exclude_mask, tf.float32) * 1e10 sample_perm = tf.random.categorical(logits=logits_to_use, num_samples=num_samples) sample = tf.batch_gather(indices, sample_perm) return { 'probs': probs, 'sample': sample, }
Does top-k sampling. if ignore_ids is on, then we will zero out those logits. :param logits: [batch_size, vocab_size] tensor :param ignore_ids: [vocab_size] one-hot representation of the indices we'd like to ignore and never predict, like padding maybe :param p: topp threshold to use, either a float or a [batch_size] vector :return: [batch_size, num_samples] samples # TODO FIGURE OUT HOW TO DO THIS ON TPUS. IT'S HELLA SLOW RIGHT NOW, DUE TO ARGSORT I THINK
_top_k_sample
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def __init__(self, config: GroverConfig, is_training, input_ids, cache=None, do_cache=False, pad_token_id=0, chop_off_last_token=True, scope=None, reuse=False): """ :param config: :param is_training: :param input_ids: Tensor thats of size [batch_size, seq_length] :param cache: Optionally, a tensor to use that will contain cached information of the size [batch_size, num_layers, 2, num_heads, cache_length, features] :param do_cache: Whether to cache again. :param pad_token_id: Which token will be used for padding (probably 0.) :param chop_off_last_token: True if we will end up using this for TRAINING only. False if we want to generate. it means the last token in input_ids will not be processed by the model as input :param scope: scope to run this on """ self.config = copy.deepcopy(config) self.is_training = is_training self.pad_token_id = pad_token_id if not is_training: self.config.hidden_dropout_prob = 0.0 self.config.attention_probs_dropout_prob = 0.0 if chop_off_last_token: self.target_ids = input_ids[:, 1:] self.input_ids = input_ids[:, :-1] else: self.input_ids = input_ids self.target_ids = tf.concat((input_ids[:, 1:], tf.constant(self.pad_token_id, dtype=self.input_ids.dtype, shape=[get_shape_list(self.input_ids, 2)[0], 1])), 1) self.batch_size, self.seq_length = get_shape_list(self.input_ids, 2) if cache is None: caches = [None] * config.num_hidden_layers self.cache_length = 0 else: batch_size_, num_layers_, two_, num_heads_, self.cache_length, features_ = get_shape_list( cache, expected_rank=6) assert batch_size_ == self.batch_size assert num_layers_ == config.num_hidden_layers assert two_ == 2 assert num_heads_ == config.num_attention_heads assert features_ == (config.hidden_size // config.num_attention_heads) caches = tf.unstack(cache, axis=1) with tf.variable_scope(scope, default_name='newslm', reuse=reuse): with tf.variable_scope("embeddings"): embeddings, self.embedding_table = embed(self.input_ids, config.vocab_size, config.hidden_size, position_offset=self.cache_length, initializer_range=config.initializer_range, max_position_embeddings=config.max_position_embeddings, use_one_hot_embeddings=True) mask = get_attention_mask(self.seq_length, self.seq_length + self.cache_length, dtype=embeddings.dtype) # We keep the representation as a 2D tensor to avoid re-shaping it back and # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on # the GPU/CPU but may not be free on the TPU, so we want to minimize them to # help the optimizer. hidden_state = tf.reshape(embeddings, [self.batch_size * self.seq_length, self.config.hidden_size]) new_kvs = [] for layer_idx, layer_cache in enumerate(caches): with tf.variable_scope('layer{:02d}'.format(layer_idx)): # [batch_size * seq_length, hidden_size] attention_output, new_kv = attention_layer( hidden_state, mask, batch_size=self.batch_size, seq_length=self.seq_length, size_per_head=config.hidden_size // config.num_attention_heads, num_attention_heads=config.num_attention_heads, initializer_range=config.initializer_range, hidden_dropout_prob=self.config.hidden_dropout_prob, attention_probs_dropout_prob=self.config.attention_probs_dropout_prob, do_cache=do_cache, cache=layer_cache, ) new_kvs.append(new_kv) # [batch_size * seq_length, hidden_size] hidden_state = residual_mlp_layer(hidden_state + attention_output, intermediate_size=config.intermediate_size, hidden_dropout_prob=self.config.hidden_dropout_prob) self.hidden_state = hidden_state self.new_kvs = tf.stack(new_kvs, axis=1) if do_cache else None # Note that the hidden state is still flat (batch_size*hidden_size) self.logits_flat = tf.matmul(self.hidden_state, self.embedding_table, transpose_b=True) # THE OUTPUT BIAS DOES NOT SPARK JOY # output_bias = tf.get_variable('output_bias', shape=[config.vocab_size], initializer=tf.zeros_initializer()) # self.logits_flat = tf.nn.bias_add(self.logits_flat, output_bias)
:param config: :param is_training: :param input_ids: Tensor thats of size [batch_size, seq_length] :param cache: Optionally, a tensor to use that will contain cached information of the size [batch_size, num_layers, 2, num_heads, cache_length, features] :param do_cache: Whether to cache again. :param pad_token_id: Which token will be used for padding (probably 0.) :param chop_off_last_token: True if we will end up using this for TRAINING only. False if we want to generate. it means the last token in input_ids will not be processed by the model as input :param scope: scope to run this on
__init__
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def pooled_output(self, clf_token): """ Extract pooled output given a token that says where we should look :param clf_token: :return: """ pool_idx = tf.cast(tf.argmax(tf.cast(tf.equal(self.input_ids, clf_token), tf.float32), 1), tf.int32) return tf.gather(self.hidden_state, tf.range(self.batch_size, dtype=tf.int32) * self.seq_length + pool_idx)
Extract pooled output given a token that says where we should look :param clf_token: :return:
pooled_output
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def sample_step(tokens, ignore_ids, news_config, batch_size=1, p_for_topp=0.95, cache=None, do_topk=False): """ Helper function that samples from grover for a single step :param tokens: [batch_size, n_ctx_b] tokens that we will predict from :param ignore_ids: [n_vocab] mask of the tokens we don't want to predict :param news_config: config for the GroverModel :param batch_size: batch size to use :param p_for_topp: top-p or top-k threshold :param cache: [batch_size, news_config.num_hidden_layers, 2, news_config.num_attention_heads, n_ctx_a, news_config.hidden_size // news_config.num_attention_heads] OR, None :return: new_tokens, size [batch_size] new_probs, also size [batch_size] new_cache, size [batch_size, news_config.num_hidden_layers, 2, n_ctx_b, news_config.num_attention_heads, news_config.hidden_size // news_config.num_attention_heads] """ model = GroverModel( config=news_config, is_training=False, input_ids=tokens, reuse=tf.AUTO_REUSE, scope='newslm', chop_off_last_token=False, do_cache=True, cache=cache, ) # Extract the FINAL SEQ LENGTH batch_size_times_seq_length, vocab_size = get_shape_list(model.logits_flat, expected_rank=2) next_logits = tf.reshape(model.logits_flat, [batch_size, -1, vocab_size])[:, -1] if do_topk: sample_info = _top_k_sample(next_logits, num_samples=1, k=tf.cast(p_for_topp, dtype=tf.int32)) else: sample_info = _top_p_sample(next_logits, ignore_ids=ignore_ids, num_samples=1, p=p_for_topp) new_tokens = tf.squeeze(sample_info['sample'], 1) new_probs = tf.squeeze(tf.batch_gather(sample_info['probs'], sample_info['sample']), 1) return { 'new_tokens': new_tokens, 'new_probs': new_probs, 'new_cache': model.new_kvs, }
Helper function that samples from grover for a single step :param tokens: [batch_size, n_ctx_b] tokens that we will predict from :param ignore_ids: [n_vocab] mask of the tokens we don't want to predict :param news_config: config for the GroverModel :param batch_size: batch size to use :param p_for_topp: top-p or top-k threshold :param cache: [batch_size, news_config.num_hidden_layers, 2, news_config.num_attention_heads, n_ctx_a, news_config.hidden_size // news_config.num_attention_heads] OR, None :return: new_tokens, size [batch_size] new_probs, also size [batch_size] new_cache, size [batch_size, news_config.num_hidden_layers, 2, n_ctx_b, news_config.num_attention_heads, news_config.hidden_size // news_config.num_attention_heads]
sample_step
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def sample(news_config: GroverConfig, initial_context, eos_token, ignore_ids=None, p_for_topp=0.95, do_topk=False): """ V1 version of: sample outputs from a model, and do it all at once :param news_config: Configuration used to construct the model :param initial_context: [batch_size, seq_length] that we'll start generating with :param eos_token: Stop generating if you see this (tf scalar) :param ignore_ids: NEVER GENERATE THESE [vocab_size] :return: """ batch_size, _ = get_shape_list(initial_context, expected_rank=2) if ignore_ids is None: ignore_ids = tf.constant([x == 0 for x in range(news_config.vocab_size)], dtype=tf.bool) with tf.name_scope('sample_sequence'): # Initial call to get cache context_output = initialize_from_context(initial_context, ignore_ids=ignore_ids, news_config=news_config, p_for_topp=p_for_topp, do_topk=do_topk) ctx = context_output['tokens'] cache = context_output['cache'] probs = context_output['probs'] def body(ctx, cache, probs): """ for whatever reason this didn't work when I ran it on more than one at once... ugh.""" next_outputs = sample_step(ctx[:, -1][:, None], ignore_ids=ignore_ids, news_config=news_config, batch_size=batch_size, p_for_topp=p_for_topp, cache=cache, do_topk=do_topk) # Update everything new_cache = tf.concat([cache, next_outputs['new_cache']], axis=-2) new_ids = tf.concat([ctx, next_outputs['new_tokens'][:, None]], axis=1) new_probs = tf.concat([probs, next_outputs['new_probs'][:, None]], axis=1) return [new_ids, new_cache, new_probs] def cond(ctx, cache, probs): is_eos = tf.equal(ctx, eos_token) return tf.math.logical_not(tf.reduce_all(tf.reduce_any(is_eos, axis=1))) tokens, cache, probs = tf.while_loop( cond=cond, body=body, maximum_iterations=1025 - get_shape_list(ctx)[1], loop_vars=[ctx, cache, probs], shape_invariants=[tf.TensorShape([batch_size, None]), tf.TensorShape( [batch_size, news_config.num_hidden_layers, 2, news_config.num_attention_heads, None, news_config.hidden_size // news_config.num_attention_heads]), tf.TensorShape([batch_size, None]), ], back_prop=False, ) return tokens, probs
V1 version of: sample outputs from a model, and do it all at once :param news_config: Configuration used to construct the model :param initial_context: [batch_size, seq_length] that we'll start generating with :param eos_token: Stop generating if you see this (tf scalar) :param ignore_ids: NEVER GENERATE THESE [vocab_size] :return:
sample
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def body(ctx, cache, probs): """ for whatever reason this didn't work when I ran it on more than one at once... ugh.""" next_outputs = sample_step(ctx[:, -1][:, None], ignore_ids=ignore_ids, news_config=news_config, batch_size=batch_size, p_for_topp=p_for_topp, cache=cache, do_topk=do_topk) # Update everything new_cache = tf.concat([cache, next_outputs['new_cache']], axis=-2) new_ids = tf.concat([ctx, next_outputs['new_tokens'][:, None]], axis=1) new_probs = tf.concat([probs, next_outputs['new_probs'][:, None]], axis=1) return [new_ids, new_cache, new_probs]
for whatever reason this didn't work when I ran it on more than one at once... ugh.
body
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def classification_model_fn_builder(config: GroverConfig, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, num_labels, pool_token_id, adafactor=False, adam_bfloat=False, lm_loss_coef=0.5): """Returns `model_fn` closure for TPUEstimator. FOR CLASSIFICATION ONLY!""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) input_ids = features["input_ids"] label_ids = features["label_ids"] if "is_real_example" in features: is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32) else: is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32) is_training = (mode == tf.estimator.ModeKeys.TRAIN) # Create model with aux loss model = GroverModel( config=config, is_training=is_training, input_ids=input_ids, pad_token_id=config.pad_token_id, chop_off_last_token=False, ) with tf.variable_scope('classification'): hidden_state = model.pooled_output(pool_token_id) if is_training: hidden_state = dropout(hidden_state, dropout_prob=0.1) logits = tf.layers.dense( hidden_state, num_labels, kernel_initializer=create_initializer(config.initializer_range), name='logits' ) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(label_ids, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) class_loss = tf.reduce_mean(per_example_loss) total_loss = lm_loss_coef * model.lm_loss() + class_loss if is_training: train_op, train_metrics = optimization_adafactor.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) # tvars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) tvars = tf.trainable_variables() train_metrics['minibatch_cls_loss'] = class_loss train_metrics['minibatch_acc'] = tf.reduce_mean( tf.cast(tf.equal(tf.argmax(logits, axis=-1, output_type=tf.int32), label_ids), tf.float32)) else: train_op = None train_metrics = {} tvars = tf.trainable_variables() initialized_variable_names = {} scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names ) = get_assignment_map_from_checkpoint(tvars, init_checkpoint) if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*" tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: if use_tpu: output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, train_op=train_op, host_call=construct_scalar_host_call(metric_dict=train_metrics, model_dir=params['model_dir'], prefix='training/'), scaffold_fn=scaffold_fn) else: output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, train_op=train_op, training_hooks=[ tf.train.LoggingTensorHook({'loss': tf.metrics.mean(total_loss)[1]}, every_n_iter=100)], scaffold_fn=scaffold_fn) elif mode == tf.estimator.ModeKeys.EVAL: def metric_fn(per_example_loss, label_ids, logits, is_real_example): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions, weights=is_real_example) loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example) return { "eval_accuracy": accuracy, "eval_loss": loss, } eval_metrics = (metric_fn, [per_example_loss, label_ids, logits, is_real_example]) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, eval_metrics=eval_metrics, scaffold_fn=scaffold_fn) else: output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions={'logits': logits, 'probs': tf.nn.softmax(logits, axis=-1)}, scaffold_fn=scaffold_fn) return output_spec return model_fn
Returns `model_fn` closure for TPUEstimator. FOR CLASSIFICATION ONLY!
classification_model_fn_builder
python
rowanz/grover
lm/modeling.py
https://github.com/rowanz/grover/blob/master/lm/modeling.py
Apache-2.0
def _do_use_weight_decay(self, param_name): """Whether to use L2 weight decay for `param_name`.""" if not self.weight_decay_rate: return False if self.exclude_from_weight_decay: for r in self.exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True
Whether to use L2 weight decay for `param_name`.
_do_use_weight_decay
python
rowanz/grover
lm/optimization_adafactor.py
https://github.com/rowanz/grover/blob/master/lm/optimization_adafactor.py
Apache-2.0
def _get_variable_name(self, param_name): """Get the variable name from the tensor name.""" m = re.match("^(.*):\\d+$", param_name) if m is not None: param_name = m.group(1) return param_name
Get the variable name from the tensor name.
_get_variable_name
python
rowanz/grover
lm/optimization_adafactor.py
https://github.com/rowanz/grover/blob/master/lm/optimization_adafactor.py
Apache-2.0
def assert_rank(tensor, expected_rank, name=None): """Raises an exception if the tensor rank is not of the expected rank. Args: tensor: A tf.Tensor to check the rank of. expected_rank: Python integer or list of integers, expected rank. name: Optional name of the tensor for the error message. Raises: ValueError: If the expected shape doesn't match the actual shape. """ if name is None: name = tensor.name expected_rank_dict = {} if isinstance(expected_rank, six.integer_types): expected_rank_dict[expected_rank] = True else: for x in expected_rank: expected_rank_dict[x] = True actual_rank = tensor.shape.ndims if actual_rank not in expected_rank_dict: scope_name = tf.get_variable_scope().name raise ValueError( "For the tensor `%s` in scope `%s`, the actual rank " "`%d` (shape = %s) is not equal to the expected rank `%s`" % (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))
Raises an exception if the tensor rank is not of the expected rank. Args: tensor: A tf.Tensor to check the rank of. expected_rank: Python integer or list of integers, expected rank. name: Optional name of the tensor for the error message. Raises: ValueError: If the expected shape doesn't match the actual shape.
assert_rank
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def get_shape_list(tensor, expected_rank=None, name=None): """Returns a list of the shape of tensor, preferring static dimensions. Args: tensor: A tf.Tensor object to find the shape of. expected_rank: (optional) int. The expected rank of `tensor`. If this is specified and the `tensor` has a different rank, and exception will be thrown. name: Optional name of the tensor for the error message. Returns: A list of dimensions of the shape of tensor. All static dimensions will be returned as python integers, and dynamic dimensions will be returned as tf.Tensor scalars. """ if name is None: name = tensor.name if expected_rank is not None: assert_rank(tensor, expected_rank, name) shape = tensor.shape.as_list() non_static_indexes = [] for (index, dim) in enumerate(shape): if dim is None: non_static_indexes.append(index) if not non_static_indexes: return shape dyn_shape = tf.shape(tensor) for index in non_static_indexes: shape[index] = dyn_shape[index] return shape
Returns a list of the shape of tensor, preferring static dimensions. Args: tensor: A tf.Tensor object to find the shape of. expected_rank: (optional) int. The expected rank of `tensor`. If this is specified and the `tensor` has a different rank, and exception will be thrown. name: Optional name of the tensor for the error message. Returns: A list of dimensions of the shape of tensor. All static dimensions will be returned as python integers, and dynamic dimensions will be returned as tf.Tensor scalars.
get_shape_list
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def gelu(input_tensor): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: input_tensor: float Tensor to perform activation. Returns: `input_tensor` with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.erf(input_tensor / tf.sqrt(2.0))) return input_tensor * cdf
Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: input_tensor: float Tensor to perform activation. Returns: `input_tensor` with the GELU activation applied.
gelu
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def layer_norm(input_tensor, name=None, epsilon=1e-5): """Run layer normalization on the last dimension of the tensor.""" name2use = f'LayerNorm_{name}' if name is not None else name with tf.variable_scope(name2use, default_name='LayerNorm'): dim = input_tensor.shape[-1].value gamma = tf.get_variable('gamma', [dim], initializer=tf.constant_initializer(1)) beta = tf.get_variable('beta', [dim], initializer=tf.constant_initializer(0)) mean = tf.reduce_mean(input_tensor, axis=-1, keepdims=True) std = tf.reduce_mean(tf.square(input_tensor - mean), axis=-1, keepdims=True) input_tensor = (input_tensor - mean) * tf.rsqrt(std + epsilon) input_tensor = input_tensor * gamma + beta return input_tensor
Run layer normalization on the last dimension of the tensor.
layer_norm
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def dropout(input_tensor, dropout_prob): """Perform dropout. Args: input_tensor: float Tensor. dropout_prob: Python float. The probability of dropping out a value (NOT of *keeping* a dimension as in `tf.nn.dropout`). Returns: A version of `input_tensor` with dropout applied. """ if dropout_prob is None or dropout_prob == 0.0: return input_tensor output = tf.nn.dropout(input_tensor, rate=dropout_prob) return output
Perform dropout. Args: input_tensor: float Tensor. dropout_prob: Python float. The probability of dropping out a value (NOT of *keeping* a dimension as in `tf.nn.dropout`). Returns: A version of `input_tensor` with dropout applied.
dropout
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def get_attention_mask(nd, ns, *, dtype): """ this is a TPU compatible version of tf.matrix_band_part(tf.ones([nd, ns]), -1, ns-nd) where the lower right triangle contains 1s """ i = tf.range(nd)[:, None] j = tf.range(ns) m = i >= j - ns + nd return tf.cast(m, dtype)
this is a TPU compatible version of tf.matrix_band_part(tf.ones([nd, ns]), -1, ns-nd) where the lower right triangle contains 1s
get_attention_mask
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def get_assignment_map_from_checkpoint(tvars, init_checkpoint): """Compute the union of the current variables and checkpoint variables.""" assignment_map = {} initialized_variable_names = {} name_to_variable = collections.OrderedDict() for var in tvars: name = var.name m = re.match("^(.*):\\d+$", name) if m is not None: name = m.group(1) name_to_variable[name] = var init_vars = tf.train.list_variables(init_checkpoint) assignment_map = collections.OrderedDict() for x in init_vars: (name, var) = (x[0], x[1]) if name not in name_to_variable: continue assignment_map[name] = name initialized_variable_names[name] = 1 initialized_variable_names[name + ":0"] = 1 return (assignment_map, initialized_variable_names)
Compute the union of the current variables and checkpoint variables.
get_assignment_map_from_checkpoint
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def construct_scalar_host_call(metric_dict, model_dir, prefix=""): """Construct a host call to log scalars when training on TPU. Args: metric_dict: A dict of the tensors to be logged. model_dir: The location to write the summary. prefix: The prefix (if any) to prepend to the metric names. Returns: A tuple of (function, args_to_be_passed_to_said_function) """ metric_names = list(metric_dict.keys()) def host_call_fn(global_step, *args): """Training host call. Creates scalar summaries for training metrics. This function is executed on the CPU and should not directly reference any Tensors in the rest of the `model_fn`. To pass Tensors from the model to the `metric_fn`, provide as part of the `host_call`. See https://www.tensorflow.org/api_docs/python/tf/contrib/tpu/TPUEstimatorSpec for more information. Arguments should match the list of `Tensor` objects passed as the second element in the tuple passed to `host_call`. Args: global_step: `Tensor with shape `[batch]` for the global_step *args: Remaining tensors to log. Returns: List of summary ops to run on the CPU host. """ step = global_step[0] with tf.contrib.summary.create_file_writer( logdir=model_dir, filename_suffix=".host_call").as_default(): with tf.contrib.summary.always_record_summaries(): for i, name in enumerate(metric_names): tf.contrib.summary.scalar(prefix + name, args[i][0], step=step) return tf.contrib.summary.all_summary_ops() # To log the current learning rate, and gradient norm for Tensorboard, the # summary op needs to be run on the host CPU via host_call. host_call # expects [batch_size, ...] Tensors, thus reshape to introduce a batch # dimension. These Tensors are implicitly concatenated to # [params['batch_size']]. global_step_tensor = tf.reshape( tf.compat.v1.train.get_or_create_global_step(), [1]) other_tensors = [tf.reshape(metric_dict[key], [1]) for key in metric_names] return host_call_fn, [global_step_tensor] + other_tensors
Construct a host call to log scalars when training on TPU. Args: metric_dict: A dict of the tensors to be logged. model_dir: The location to write the summary. prefix: The prefix (if any) to prepend to the metric names. Returns: A tuple of (function, args_to_be_passed_to_said_function)
construct_scalar_host_call
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def host_call_fn(global_step, *args): """Training host call. Creates scalar summaries for training metrics. This function is executed on the CPU and should not directly reference any Tensors in the rest of the `model_fn`. To pass Tensors from the model to the `metric_fn`, provide as part of the `host_call`. See https://www.tensorflow.org/api_docs/python/tf/contrib/tpu/TPUEstimatorSpec for more information. Arguments should match the list of `Tensor` objects passed as the second element in the tuple passed to `host_call`. Args: global_step: `Tensor with shape `[batch]` for the global_step *args: Remaining tensors to log. Returns: List of summary ops to run on the CPU host. """ step = global_step[0] with tf.contrib.summary.create_file_writer( logdir=model_dir, filename_suffix=".host_call").as_default(): with tf.contrib.summary.always_record_summaries(): for i, name in enumerate(metric_names): tf.contrib.summary.scalar(prefix + name, args[i][0], step=step) return tf.contrib.summary.all_summary_ops()
Training host call. Creates scalar summaries for training metrics. This function is executed on the CPU and should not directly reference any Tensors in the rest of the `model_fn`. To pass Tensors from the model to the `metric_fn`, provide as part of the `host_call`. See https://www.tensorflow.org/api_docs/python/tf/contrib/tpu/TPUEstimatorSpec for more information. Arguments should match the list of `Tensor` objects passed as the second element in the tuple passed to `host_call`. Args: global_step: `Tensor with shape `[batch]` for the global_step *args: Remaining tensors to log. Returns: List of summary ops to run on the CPU host.
host_call_fn
python
rowanz/grover
lm/utils.py
https://github.com/rowanz/grover/blob/master/lm/utils.py
Apache-2.0
def ind_where(array: np.ndarray, target, return_first_match=True, default_value=-1): """ :param array: Single dimension array :param target: target to search for :param return_first_match: If true, return the first index that matches, otherwise, return the last one :param default_value: Index to return if there was no match :return: index of the first match, or -1 if nothing """ assert array.ndim == 1 matching_inds = np.where(array == target)[0] if len(matching_inds) > 0: if return_first_match: return int(matching_inds[0]) else: return int(matching_inds[-1]) return default_value
:param array: Single dimension array :param target: target to search for :param return_first_match: If true, return the first index that matches, otherwise, return the last one :param default_value: Index to return if there was no match :return: index of the first match, or -1 if nothing
ind_where
python
rowanz/grover
lm/validate.py
https://github.com/rowanz/grover/blob/master/lm/validate.py
Apache-2.0
def _get_split(domain): """ You could do this by domain, or not""" if random.random() < TRAIN_PORTION: return 'train' return 'val'
You could do this by domain, or not
_get_split
python
rowanz/grover
realnews/dedupe_crawl.py
https://github.com/rowanz/grover/blob/master/realnews/dedupe_crawl.py
Apache-2.0
def get_matching_s3_objects(bucket, prefix='', suffix=''): """ Generate objects in an S3 bucket. THANK YOU https://alexwlchan.net/2018/01/listing-s3-keys-redux/ :param bucket: Name of the S3 bucket. :param prefix: Only fetch objects whose key starts with this prefix (optional). :param suffix: Only fetch objects whose keys end with this suffix (optional). """ kwargs = {'Bucket': bucket} # If the prefix is a single string (not a tuple of strings), we can # do the filtering directly in the S3 API. if isinstance(prefix, str): kwargs['Prefix'] = prefix while True: # The S3 API response is a large blob of metadata. # 'Contents' contains information about the listed objects. resp = s3client.list_objects_v2(**kwargs) try: contents = resp['Contents'] except KeyError: return for obj in contents: key = obj['Key'] if key.startswith(prefix) and key.endswith(suffix): yield obj['Key'''] # The S3 API is paginated, returning up to 1000 keys at a time. # Pass the continuation token into the next response, until we # reach the final page (when this field is missing). try: kwargs['ContinuationToken'] = resp['NextContinuationToken'] except KeyError: break
Generate objects in an S3 bucket. THANK YOU https://alexwlchan.net/2018/01/listing-s3-keys-redux/ :param bucket: Name of the S3 bucket. :param prefix: Only fetch objects whose key starts with this prefix (optional). :param suffix: Only fetch objects whose keys end with this suffix (optional).
get_matching_s3_objects
python
rowanz/grover
realnews/dedupe_crawl.py
https://github.com/rowanz/grover/blob/master/realnews/dedupe_crawl.py
Apache-2.0
def article_iterator(encoder, final_desired_size=1025): """ Iterate through the provided filename + tokenize""" assert os.path.exists(args.input_fn) with open(args.input_fn, 'r') as f: for l_no, l in enumerate(f): if l_no % args.num_folds == args.fold: article = json.loads(l) article['input_ids'] = tokenize_for_grover_training(encoder, article, desired_size=final_desired_size, unconditional_prob=.35) article['inst_index'] = (l_no // args.num_folds) if article['inst_index'] < 100: print('---\nINPUT{}. {}\n---\nTokens: {}\n'.format(article['inst_index'], detokenize(encoder, article['input_ids']), article['input_ids'] ), flush=True) if len(article['input_ids']) == 0: continue yield article
Iterate through the provided filename + tokenize
article_iterator
python
rowanz/grover
realnews/prepare_lm_data.py
https://github.com/rowanz/grover/blob/master/realnews/prepare_lm_data.py
Apache-2.0
def _stream_from_buffer(buffer, current_desired_size, pad_token=0, add_articles_to_end=False): """ Combines short articles that are in a buffer """ random.shuffle(buffer) i = 0 while i < len(buffer): article = buffer[i] if add_articles_to_end: for article2add in buffer[(i + 1):]: i += 1 article['input_ids'].append(encoder.padding) article['input_ids'].append(encoder.reset_context) article['input_ids'].extend(article2add['input_ids']) if len(article['input_ids']) >= current_desired_size: article['input_ids'] = article['input_ids'][:current_desired_size] break # print(f"YIELD FROM BUFFER {i}") # Pad to right length amount_to_pad = current_desired_size - len(article['input_ids']) article['input_ids'].extend([pad_token] * amount_to_pad) article['sub_index'] = 0 yield article i += 1
Combines short articles that are in a buffer
_stream_from_buffer
python
rowanz/grover
realnews/prepare_lm_data.py
https://github.com/rowanz/grover/blob/master/realnews/prepare_lm_data.py
Apache-2.0
def buffered_and_sliding_window_article_iterator(encoder, current_desired_size, final_desired_size=1025): """ We apply a sliding window to fix long sequences, and use a buffer that combines short sequences.""" assert current_desired_size <= final_desired_size buffer = [] for article in article_iterator(encoder, final_desired_size=final_desired_size): amount_to_pad = current_desired_size - len(article['input_ids']) if article['split'] == 'val' or amount_to_pad <= 0: for sub_index, sub_article in enumerate(sliding_window(article, max_seq_length=current_desired_size, pad_token=encoder.padding)): sub_article['sub_index'] = sub_index # print(f"AMT2PAD < 0 YIELD-{inst_index} sliding window {sub_index}", flush=True) yield sub_article else: # Buffer time. buffer.append(article) if len(buffer) % 100 == 0: yield from _stream_from_buffer(buffer, current_desired_size=current_desired_size, pad_token=encoder.padding, add_articles_to_end=args.add_extra_articles_to_end) buffer = [] yield from _stream_from_buffer(buffer, current_desired_size=current_desired_size, pad_token=encoder.padding, add_articles_to_end=args.add_extra_articles_to_end)
We apply a sliding window to fix long sequences, and use a buffer that combines short sequences.
buffered_and_sliding_window_article_iterator
python
rowanz/grover
realnews/prepare_lm_data.py
https://github.com/rowanz/grover/blob/master/realnews/prepare_lm_data.py
Apache-2.0
def _url_seems_ok(url, domain_to_allowed_subdomains): """ Check if the URL seems ok. if it does then we'll return a tuple of CLEAN URL, main domain. :param url: :return: """ # Long URLs are usually bad if len(url) > 200: return False # FIRST check if the domain is OK ext = tldextract.extract(url) main_domain = ext.domain + '.' + ext.suffix allowed_subdomains = domain_to_allowed_subdomains.get(main_domain, None) if allowed_subdomains is None: return False if isinstance(allowed_subdomains, list) and not ext.subdomain in allowed_subdomains: return False # Check for banned extensios parsed = urlparse(url) parsed = parsed._replace(query="", fragment="") path_to_use = parsed.path file_extension = os.path.splitext(path_to_use)[1] if file_extension in BANNED_EXTENSIONS: return False # If there are two dotcoms then that's probably bad! endings = len(re.findall(r'(\.com|\.co\.uk|\.net|\.org)', url)) if endings > 1: return False # Check for banned words if not (is_banned_regex.search(url) is None): return False # AT A LATER DATE: we need to check if the URL was banned return (parsed.geturl(), main_domain)
Check if the URL seems ok. if it does then we'll return a tuple of CLEAN URL, main domain. :param url: :return:
_url_seems_ok
python
rowanz/grover
realnews/process_ccrawl.py
https://github.com/rowanz/grover/blob/master/realnews/process_ccrawl.py
Apache-2.0
def serialize(self): """ Return simple page object to JSONify and write to file. """ return { 'meta_lang': self.dummy_article.meta_lang, 'title': self.title, 'text': self.text, 'summary': self.summary, 'authors': self.authors, 'publish_date': self.publish_date }
Return simple page object to JSONify and write to file.
serialize
python
rowanz/grover
realnews/process_ccrawl.py
https://github.com/rowanz/grover/blob/master/realnews/process_ccrawl.py
Apache-2.0
def get_pairs(word): """Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
get_pairs
python
rowanz/grover
sample/encoder.py
https://github.com/rowanz/grover/blob/master/sample/encoder.py
Apache-2.0
def _tokenize_article_pieces(encoder, item): """ Turn the article into tokens NOTE: in hindsight I kinda messed up here because the first token is always represented as a BPE continuation rather than an initial token in its own right. whoops.... :param item: Contains things that need to be tokenized fields are ['domain', 'date', 'authors', 'title', 'article', 'summary'] :return: dict """ article_pieces = { 'article': [encoder.begin_article] + encoder.encode(item['text']) + [encoder.end_article], 'domain': [encoder.begin_domain] + encoder.encode(item['domain']) + [encoder.end_domain], 'title': [encoder.begin_title] + encoder.encode(item['title']) + [encoder.end_title], } # 4/6: Attach the summary too, why the hell not if item['summary'] and len(item['summary']) > 50: article_pieces['summary'] = [encoder.begin_summary] + encoder.encode(item['summary']) + [encoder.end_summary] # 5/6: date date_split = item['publish_date'].split('-') assert len(date_split) == 3 assert date_split[0].isdigit() date_txt = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][int(date_split[0]) - 1] + ' {}, {}'.format( date_split[1], date_split[2]) article_pieces['date'] = [encoder.begin_date] + encoder.encode(date_txt) + [encoder.end_date] # 6/6: authors authors = ', '.join(item['authors']) if len(authors) > 5: article_pieces['authors'] = [encoder.begin_authors] + encoder.encode(authors) + [encoder.end_authors] return article_pieces
Turn the article into tokens NOTE: in hindsight I kinda messed up here because the first token is always represented as a BPE continuation rather than an initial token in its own right. whoops.... :param item: Contains things that need to be tokenized fields are ['domain', 'date', 'authors', 'title', 'article', 'summary'] :return: dict
_tokenize_article_pieces
python
rowanz/grover
sample/encoder.py
https://github.com/rowanz/grover/blob/master/sample/encoder.py
Apache-2.0
def _cut_tokens_to_add_stuff(tokens, stuff_to_add, desired_size, padding_token): """ The idea behind this function is to take away tokens from `tokens' such that tokens[:LENGTH] + stuff_to_add becomes exactly at the right size (desired_size). :param tokens: :param stuff_to_add: :param desired_size: :return: """ if len(tokens) >= desired_size: return tokens # no way we can add this stuff if len(stuff_to_add) >= desired_size: return tokens if (len(tokens) + len(stuff_to_add)) <= desired_size: return tokens + stuff_to_add # Otherwise we'll have to actually cut tokens = tokens[:(desired_size - len(stuff_to_add) - 1)] tokens.append(padding_token) tokens.extend(stuff_to_add) return tokens
The idea behind this function is to take away tokens from `tokens' such that tokens[:LENGTH] + stuff_to_add becomes exactly at the right size (desired_size). :param tokens: :param stuff_to_add: :param desired_size: :return:
_cut_tokens_to_add_stuff
python
rowanz/grover
sample/encoder.py
https://github.com/rowanz/grover/blob/master/sample/encoder.py
Apache-2.0
def tokenize_for_grover_training(encoder, item, desired_size=1024, unconditional_prob=0.35, metadata_dropout_prob=0.1, cut_prob=0.2): """ Not only will we tokenize an item with a BPE encoder, but we'll also put it in a nice format for language modeling. The goal is to MINIMIZE PADDING. If we don't fill up the desired size of 1024 tokens then we're wasting compute. The canonical order is DOMAIN DATE AUTHORS TITLE ARTICLE SUMMARY :param encoder: :param item: Contains things like {"url": "https://www.advocate.com/node/1010911", "timestamp": "20180118211607", "url_used": "https://web.archive.org/web/20180118211607id_/https://www.advocate.com/node/1010911", "domain": "advocate.com", "title": "Report: One-Third of Trump's Judicial Picks Are Anti-LGBT", "text": .... "summary": .... "authors": list "publish_date": ... } :param desired_size: the goal for how long the span will be :param unconditional_prob: The probability that we will generate JUST THE TEXT first. :param metadata_dropout_prob: The probability that we will drop out each item of metadata :param cut_prob: The probability that, if we're already over the desired size, we'll cut the article and start predicting metadata before the desired_size window ends. :return: """ # Get all the bits and pieces article_pieces = _tokenize_article_pieces(encoder, item) canonical_metadata_order = ['domain', 'date', 'authors', 'title'] # unconditional_prob is probability we only generate the text first, without any metadata switch = random.random() if switch < unconditional_prob: assignments = {'article': 'a'} chunk_a = article_pieces.pop('article') chunk_b = [] for x in canonical_metadata_order + ['summary']: if random.random() > metadata_dropout_prob: chunk_b.extend(article_pieces.pop(x, [])) assignments[x] = 'b' elif switch < 0.5: # Put everything in chunk_a, without dropout assignments = {} chunk_a = [] chunk_b = [] for x in canonical_metadata_order + ['article', 'summary']: chunk_a.extend(article_pieces.pop(x, [])) assignments[x] = 'a' else: assignments = {} chunk_a = [] chunk_b = [] for k in canonical_metadata_order + ['article', 'summary']: if random.random() < metadata_dropout_prob and k not in ('article', 'title'): pass elif random.random() < 0.5: if k != 'summary': chunk_a.extend(article_pieces.pop(k, [])) assignments[k] = 'a' else: chunk_b.extend(article_pieces.pop(k, [])) assignments[k] = 'b' if (len(chunk_a) + len(chunk_b)) <= desired_size: return chunk_a + chunk_b if (assignments.get('article', '') == 'a') and (len(chunk_b) > 0) and (random.random() < cut_prob): return _cut_tokens_to_add_stuff(chunk_a, chunk_b, desired_size, encoder.padding) tokens = chunk_a + chunk_b return tokens
Not only will we tokenize an item with a BPE encoder, but we'll also put it in a nice format for language modeling. The goal is to MINIMIZE PADDING. If we don't fill up the desired size of 1024 tokens then we're wasting compute. The canonical order is DOMAIN DATE AUTHORS TITLE ARTICLE SUMMARY :param encoder: :param item: Contains things like {"url": "https://www.advocate.com/node/1010911", "timestamp": "20180118211607", "url_used": "https://web.archive.org/web/20180118211607id_/https://www.advocate.com/node/1010911", "domain": "advocate.com", "title": "Report: One-Third of Trump's Judicial Picks Are Anti-LGBT", "text": .... "summary": .... "authors": list "publish_date": ... } :param desired_size: the goal for how long the span will be :param unconditional_prob: The probability that we will generate JUST THE TEXT first. :param metadata_dropout_prob: The probability that we will drop out each item of metadata :param cut_prob: The probability that, if we're already over the desired size, we'll cut the article and start predicting metadata before the desired_size window ends. :return:
tokenize_for_grover_training
python
rowanz/grover
sample/encoder.py
https://github.com/rowanz/grover/blob/master/sample/encoder.py
Apache-2.0
def sliding_window(article, max_seq_length, pad_token): """ Randomly sample some spans. It's a simple approximation of sliding window :param tokens: :param max_seq_length: :return: """ # if it's shorter, no need for this if len(article['input_ids']) <= max_seq_length: amount_to_pad = max_seq_length - len(article['input_ids']) article['input_ids'].extend([pad_token] * amount_to_pad) yield article return num_spans = len(article['input_ids']) - max_seq_length + 1 weights = np.ones(num_spans, dtype=np.float32) # weights[0] = max_seq_length weights /= weights.sum() num_to_yield = int(0.5 + len(article['input_ids']) / max_seq_length) starts = np.random.choice(num_spans, size=num_to_yield, replace=False, p=weights) input_ids = article.pop('input_ids') for i in starts.tolist(): article['input_ids'] = input_ids[i:(i + max_seq_length)] yield article
Randomly sample some spans. It's a simple approximation of sliding window :param tokens: :param max_seq_length: :return:
sliding_window
python
rowanz/grover
sample/encoder.py
https://github.com/rowanz/grover/blob/master/sample/encoder.py
Apache-2.0
def format_context(encoder, news_article, target): """ Generates a news article given some partial information :param news_article: Contains context :param target: What we want to get an answer for. :return: """ canonical_metadata_order = ['domain', 'date', 'authors', 'title', 'article'] tokens = [] for metadata_category in canonical_metadata_order: metadata = news_article.get(metadata_category, '').strip() # This MIGHT BE needed because I think during training time we never saw empty articles # if metadata or ((metadata_category == 'article') and target != 'article'): if (metadata_category == 'article') and (target != 'article'): metadata = news_article.get('title', '') # Just copy from the title maybe? if metadata: tokens.append(encoder.__dict__[f'begin_{metadata_category}']) tokens.extend(encoder.encode(metadata)) tokens.append(encoder.__dict__[f'end_{metadata_category}']) assert target in (canonical_metadata_order + ['summary']) tokens.append(encoder.__dict__[f'begin_{target}']) return tokens
Generates a news article given some partial information :param news_article: Contains context :param target: What we want to get an answer for. :return:
format_context
python
rowanz/grover
sample/encoder.py
https://github.com/rowanz/grover/blob/master/sample/encoder.py
Apache-2.0
def extract_generated_target(output_tokens, encoder, target): """ Given some tokens that were generated, extract the target :param output_tokens: [num_tokens] thing that was generated :param encoder: how they were encoded :param target: the piece of metadata we wanted to generate! :return: """ # Filter out first instance of start token assert output_tokens.ndim == 1 start_tokens = output_tokens == encoder.__dict__[f'begin_{target}'] if np.any(start_tokens): start_ind = np.argmax(start_tokens) + 1 else: start_ind = 0 end_tokens = output_tokens == encoder.__dict__[f'end_{target}'] if np.any(end_tokens): end_ind = np.argmax(end_tokens) else: end_ind = output_tokens.shape[0] return { 'extraction': encoder.decode(output_tokens[start_ind:end_ind]), 'start_ind': start_ind, 'end_ind': end_ind, }
Given some tokens that were generated, extract the target :param output_tokens: [num_tokens] thing that was generated :param encoder: how they were encoded :param target: the piece of metadata we wanted to generate! :return:
extract_generated_target
python
rowanz/grover
sample/encoder.py
https://github.com/rowanz/grover/blob/master/sample/encoder.py
Apache-2.0
def compute_distance_two_loops(self, X_test): """ Inefficient naive implementation, use only as a way of understanding what kNN is doing """ num_test = X_test.shape[0] num_train = self.X_train.shape[0] distances = np.zeros((num_test, num_train)) for i in range(num_test): for j in range(num_train): # (Taking sqrt is not necessary: min distance won't change since sqrt is monotone) distances[i, j] = np.sqrt( self.eps + np.sum((X_test[i, :] - self.X_train[j, :]) ** 2) ) return distances
Inefficient naive implementation, use only as a way of understanding what kNN is doing
compute_distance_two_loops
python
aladdinpersson/Machine-Learning-Collection
ML/algorithms/knn/knn.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/algorithms/knn/knn.py
MIT
def compute_distance_one_loop(self, X_test): """ Much better than two-loops but not as fast as fully vectorized version. Utilize Numpy broadcasting in X_train - X_test[i,:] """ num_test = X_test.shape[0] num_train = self.X_train.shape[0] distances = np.zeros((num_test, num_train)) for i in range(num_test): # (Taking sqrt is not necessary: min distance won't change since sqrt is monotone) distances[i, :] = np.sqrt( self.eps + np.sum((self.X_train - X_test[i, :]) ** 2, axis=1) ) return distances
Much better than two-loops but not as fast as fully vectorized version. Utilize Numpy broadcasting in X_train - X_test[i,:]
compute_distance_one_loop
python
aladdinpersson/Machine-Learning-Collection
ML/algorithms/knn/knn.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/algorithms/knn/knn.py
MIT
def compute_distance_vectorized(self, X_test): """ Can be tricky to understand this, we utilize heavy vecotorization as well as numpy broadcasting. Idea: if we have two vectors a, b (two examples) and for vectors we can compute (a-b)^2 = a^2 - 2a (dot) b + b^2 expanding on this and doing so for every vector lends to the heavy vectorized formula for all examples at the same time. """ X_test_squared = np.sum(X_test ** 2, axis=1, keepdims=True) X_train_squared = np.sum(self.X_train ** 2, axis=1, keepdims=True) two_X_test_X_train = np.dot(X_test, self.X_train.T) # (Taking sqrt is not necessary: min distance won't change since sqrt is monotone) return np.sqrt( self.eps + X_test_squared - 2 * two_X_test_X_train + X_train_squared.T )
Can be tricky to understand this, we utilize heavy vecotorization as well as numpy broadcasting. Idea: if we have two vectors a, b (two examples) and for vectors we can compute (a-b)^2 = a^2 - 2a (dot) b + b^2 expanding on this and doing so for every vector lends to the heavy vectorized formula for all examples at the same time.
compute_distance_vectorized
python
aladdinpersson/Machine-Learning-Collection
ML/algorithms/knn/knn.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/algorithms/knn/knn.py
MIT
def trim(im): """ Converts image to grayscale using cv2, then computes binary matrix of the pixels that are above a certain threshold, then takes out the first row where a certain percetage of the pixels are above the threshold will be the first clip point. Same idea for col, max row, max col. """ percentage = 0.02 img = np.array(im) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) im = img_gray > 0.1 * np.mean(img_gray[img_gray != 0]) row_sums = np.sum(im, axis=1) col_sums = np.sum(im, axis=0) rows = np.where(row_sums > img.shape[1] * percentage)[0] cols = np.where(col_sums > img.shape[0] * percentage)[0] min_row, min_col = np.min(rows), np.min(cols) max_row, max_col = np.max(rows), np.max(cols) im_crop = img[min_row : max_row + 1, min_col : max_col + 1] return Image.fromarray(im_crop)
Converts image to grayscale using cv2, then computes binary matrix of the pixels that are above a certain threshold, then takes out the first row where a certain percetage of the pixels are above the threshold will be the first clip point. Same idea for col, max row, max col.
trim
python
aladdinpersson/Machine-Learning-Collection
ML/Kaggles/DiabeticRetinopathy/preprocess_images.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Kaggles/DiabeticRetinopathy/preprocess_images.py
MIT
def resize_maintain_aspect(image, desired_size): """ Stole this from some stackoverflow post but can't remember which, this will add padding to maintain the aspect ratio. """ old_size = image.size # old_size[0] is in (width, height) format ratio = float(desired_size) / max(old_size) new_size = tuple([int(x * ratio) for x in old_size]) im = image.resize(new_size, Image.ANTIALIAS) new_im = Image.new("RGB", (desired_size, desired_size)) new_im.paste(im, ((desired_size - new_size[0]) // 2, (desired_size - new_size[1]) // 2)) return new_im
Stole this from some stackoverflow post but can't remember which, this will add padding to maintain the aspect ratio.
resize_maintain_aspect
python
aladdinpersson/Machine-Learning-Collection
ML/Kaggles/DiabeticRetinopathy/preprocess_images.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Kaggles/DiabeticRetinopathy/preprocess_images.py
MIT
def fast_image_resize(input_path_folder, output_path_folder, output_size=None): """ Uses multiprocessing to make it fast """ if not output_size: warnings.warn("Need to specify output_size! For example: output_size=100") exit() if not os.path.exists(output_path_folder): os.makedirs(output_path_folder) jobs = [ (file, input_path_folder, output_path_folder, output_size) for file in os.listdir(input_path_folder) ] with Pool() as p: list(tqdm(p.imap_unordered(save_single, jobs), total=len(jobs)))
Uses multiprocessing to make it fast
fast_image_resize
python
aladdinpersson/Machine-Learning-Collection
ML/Kaggles/DiabeticRetinopathy/preprocess_images.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Kaggles/DiabeticRetinopathy/preprocess_images.py
MIT
def check_accuracy( loader, model, loss_fn, input_shape=None, toggle_eval=True, print_accuracy=True ): """ Check accuracy of model on data from loader """ if toggle_eval: model.eval() device = next(model.parameters()).device num_correct = 0 num_samples = 0 y_preds = [] y_true = [] with torch.no_grad(): for x, y in loader: x = x.to(device=device) y = y.to(device=device) if input_shape: x = x.reshape(x.shape[0], *input_shape) scores = model(x) predictions = torch.sigmoid(scores) > 0.5 y_preds.append(torch.clip(torch.sigmoid(scores), 0.005, 0.995).cpu().numpy()) y_true.append(y.cpu().numpy()) num_correct += (predictions.squeeze(1) == y).sum() num_samples += predictions.size(0) accuracy = num_correct / num_samples if toggle_eval: model.train() if print_accuracy: print(f"Accuracy: {accuracy * 100:.2f}%") print(log_loss(np.concatenate(y_true, axis=0), np.concatenate(y_preds, axis=0))) return accuracy
Check accuracy of model on data from loader
check_accuracy
python
aladdinpersson/Machine-Learning-Collection
ML/Kaggles/Dog vs Cat Competition/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Kaggles/Dog vs Cat Competition/utils.py
MIT
def get_submission(loader, dataset, model_15, model_4): """ This can be done a lot faster.. but it didn't take too much time to do it in this inefficient way """ model_15.eval() model_4.eval() id_lookup = pd.read_csv("data/IdLookupTable.csv") predictions = [] image_id = 1 for image, label in tqdm(loader): image = image.to(config.DEVICE) preds_15 = torch.clip(model_15(image).squeeze(0), 0.0, 96.0) preds_4 = torch.clip(model_4(image).squeeze(0), 0.0, 96.0) feature_names = id_lookup.loc[id_lookup["ImageId"] == image_id]["FeatureName"] for feature_name in feature_names: feature_index = dataset.category_names.index(feature_name) if feature_names.shape[0] < 10: predictions.append(preds_4[feature_index].item()) else: predictions.append(preds_15[feature_index].item()) image_id += 1 df = pd.DataFrame({"RowId": np.arange(1, len(predictions)+1), "Location": predictions}) df.to_csv("submission.csv", index=False) model_15.train() model_4.train()
This can be done a lot faster.. but it didn't take too much time to do it in this inefficient way
get_submission
python
aladdinpersson/Machine-Learning-Collection
ML/Kaggles/Facial Keypoint Detection Competition/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Kaggles/Facial Keypoint Detection Competition/utils.py
MIT
def precision(y_true, y_pred): """ Fraction of True Positive Elements divided by total number of positive predicted units How I view it: Assuming we say someone has cancer: how often are we correct? It tells us how much we can trust the model when it predicts an individual as positive. """ tp = true_negatives(y_true, y_pred) fp = false_positives(y_true, y_pred) return tp / (tp + fp)
Fraction of True Positive Elements divided by total number of positive predicted units How I view it: Assuming we say someone has cancer: how often are we correct? It tells us how much we can trust the model when it predicts an individual as positive.
precision
python
aladdinpersson/Machine-Learning-Collection
ML/ml_metrics/metrics.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/ml_metrics/metrics.py
MIT
def recall(y_true, y_pred): """ Recall meaasure the model's predictive accuracy for the positive class. How I view it, out of all the people that has cancer: how often are we able to detect it? """ tp = true_negatives(y_true, y_pred) fn = false_negatives(y_true, y_pred) return tp / (tp + fn)
Recall meaasure the model's predictive accuracy for the positive class. How I view it, out of all the people that has cancer: how often are we able to detect it?
recall
python
aladdinpersson/Machine-Learning-Collection
ML/ml_metrics/metrics.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/ml_metrics/metrics.py
MIT
def sort_array(encoder, decoder, device, arr=None): """ A very simple example of use of the model Input: encoder nn.Module decoder nn.Module device array to sort (optional) """ if arr is None: arr = ask_user() with torch.no_grad(): while arr != "q": # Avoid numerical errors by rounding to max_len arr = eval(arr) lengths = [ len(str(elem).split(".")[1]) if len(str(elem).split(".")) > 1 else 0 for elem in arr ] max_len = max(lengths) source = torch.tensor(arr, dtype=torch.float).to(device).unsqueeze(1) batch_size = source.shape[1] target_len = source.shape[0] + 1 outputs = torch.zeros(target_len, batch_size, target_len - 1).to(device) encoder_states, hidden, cell = encoder(source) # First input will be <SOS> token x = torch.tensor([-1], dtype=torch.float).to(device) predictions = torch.zeros((target_len)).to(device) for t in range(1, target_len): # At every time step use encoder_states and update hidden, cell attention, energy, hidden, cell = decoder( x, encoder_states, hidden, cell ) # Store prediction for current time step outputs[t] = energy.permute(1, 0) # Get the best word the Decoder predicted (index in the vocabulary) best_guess = attention.argmax(0) predictions[t] = best_guess.item() x = torch.tensor([best_guess.item()], dtype=torch.float).to(device) output = [ round(source[predictions[1:].long()][i, :].item(), max_len) for i in range(source.shape[0]) ] print(f"Here's the result: {output}") arr = ask_user()
A very simple example of use of the model Input: encoder nn.Module decoder nn.Module device array to sort (optional)
sort_array
python
aladdinpersson/Machine-Learning-Collection
ML/Projects/DeepSort/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Projects/DeepSort/utils.py
MIT
def __init__(self, input_size, num_classes): """ Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9) """ super(NN, self).__init__() # Our first linear layer take input_size, in this case 784 nodes to 50 # and our second linear layer takes 50 to the num_classes we have, in # this case 10. self.fc1 = nn.Linear(input_size, 50) self.fc2 = nn.Linear(50, num_classes)
Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)
__init__
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/Basics/pytorch_simple_fullynet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/Basics/pytorch_simple_fullynet.py
MIT
def forward(self, x): """ x here is the mnist images and we run it through fc1, fc2 that we created above. we also add a ReLU activation function in between and for that (since it has no parameters) I recommend using nn.functional (F) Parameters: x: mnist images Returns: out: the output of the network """ x = F.relu(self.fc1(x)) x = self.fc2(x) return x
x here is the mnist images and we run it through fc1, fc2 that we created above. we also add a ReLU activation function in between and for that (since it has no parameters) I recommend using nn.functional (F) Parameters: x: mnist images Returns: out: the output of the network
forward
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/Basics/pytorch_simple_fullynet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/Basics/pytorch_simple_fullynet.py
MIT
def check_accuracy(loader, model): """ Check accuracy of our trained model given a loader and a model Parameters: loader: torch.utils.data.DataLoader A loader for the dataset you want to check accuracy on model: nn.Module The model you want to check accuracy on Returns: acc: float The accuracy of the model on the dataset given by the loader """ num_correct = 0 num_samples = 0 model.eval() # We don't need to keep track of gradients here so we wrap it in torch.no_grad() with torch.no_grad(): # Loop through the data for x, y in loader: # Move data to device x = x.to(device=device) y = y.to(device=device) # Get to correct shape x = x.reshape(x.shape[0], -1) # Forward pass scores = model(x) _, predictions = scores.max(1) # Check how many we got correct num_correct += (predictions == y).sum() # Keep track of number of samples num_samples += predictions.size(0) model.train() return num_correct / num_samples
Check accuracy of our trained model given a loader and a model Parameters: loader: torch.utils.data.DataLoader A loader for the dataset you want to check accuracy on model: nn.Module The model you want to check accuracy on Returns: acc: float The accuracy of the model on the dataset given by the loader
check_accuracy
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/Basics/pytorch_simple_fullynet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/Basics/pytorch_simple_fullynet.py
MIT
def visualize_bbox(img, bbox, class_name, color=(255, 0, 0), thickness=5): """Visualizes a single bounding box on the image""" x_min, y_min, x_max, y_max = map(int, bbox) cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color, thickness) return img
Visualizes a single bounding box on the image
visualize_bbox
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/Basics/albumentations_tutorial/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/Basics/albumentations_tutorial/utils.py
MIT
def fade_in(self, alpha, downscaled, out): """Used to fade in downscaled using avg pooling and output from CNN""" # alpha should be scalar within [0, 1], and upscale.shape == generated.shape return alpha * out + (1 - alpha) * downscaled
Used to fade in downscaled using avg pooling and output from CNN
fade_in
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/GANs/ProGAN/model.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/GANs/ProGAN/model.py
MIT
def generate_examples(gen, steps, truncation=0.7, n=100): """ Tried using truncation trick here but not sure it actually helped anything, you can remove it if you like and just sample from torch.randn """ gen.eval() alpha = 1.0 for i in range(n): with torch.no_grad(): noise = torch.tensor(truncnorm.rvs(-truncation, truncation, size=(1, config.Z_DIM, 1, 1)), device=config.DEVICE, dtype=torch.float32) img = gen(noise, alpha, steps) save_image(img*0.5+0.5, f"saved_examples/img_{i}.png") gen.train()
Tried using truncation trick here but not sure it actually helped anything, you can remove it if you like and just sample from torch.randn
generate_examples
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/GANs/ProGAN/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/GANs/ProGAN/utils.py
MIT
def fade_in(self, alpha, downscaled, out): """Used to fade in downscaled using avg pooling and output from CNN""" # alpha should be scalar within [0, 1], and upscale.shape == generated.shape return alpha * out + (1 - alpha) * downscaled
Used to fade in downscaled using avg pooling and output from CNN
fade_in
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/GANs/StyleGAN/model.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/GANs/StyleGAN/model.py
MIT
def __init__(self, gamma=0.99, save=True, save_frequency=100, save_filename="ema_weights.pth"): """ Initialize the weight to which we will do the exponential moving average and the dictionary where we store the model parameters """ self.gamma = gamma self.registered = {} self.save_filename = save_filename self.save_frequency = save_frequency self.count = 0 if save_filename in os.listdir("."): self.registered = torch.load(self.save_filename) if not save: warnings.warn("Note that the exponential moving average weights will not be saved to a .pth file!")
Initialize the weight to which we will do the exponential moving average and the dictionary where we store the model parameters
__init__
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/GANs/StyleGAN/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/GANs/StyleGAN/utils.py
MIT
def register_weights(self, model): """ Registers the weights of the model which will later be used when we take the moving average """ for name, param in model.named_parameters(): if param.requires_grad: self.registered[name] = param.clone().detach()
Registers the weights of the model which will later be used when we take the moving average
register_weights
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/GANs/StyleGAN/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/GANs/StyleGAN/utils.py
MIT
def inference(digit, num_examples=1): """ Generates (num_examples) of a particular digit. Specifically we extract an example of each digit, then after we have the mu, sigma representation for each digit we can sample from that. After we sample we can run the decoder part of the VAE and generate examples. """ images = [] idx = 0 for x, y in dataset: if y == idx: images.append(x) idx += 1 if idx == 10: break encodings_digit = [] for d in range(10): with torch.no_grad(): mu, sigma = model.encode(images[d].view(1, 784)) encodings_digit.append((mu, sigma)) mu, sigma = encodings_digit[digit] for example in range(num_examples): epsilon = torch.randn_like(sigma) z = mu + sigma * epsilon out = model.decode(z) out = out.view(-1, 1, 28, 28) save_image(out, f"generated_{digit}_ex{example}.png")
Generates (num_examples) of a particular digit. Specifically we extract an example of each digit, then after we have the mu, sigma representation for each digit we can sample from that. After we sample we can run the decoder part of the VAE and generate examples.
inference
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/more_advanced/VAE/train.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/more_advanced/VAE/train.py
MIT
def inference(model, dataset, digit, num_examples=1): """ Generates (num_examples) of a particular digit. Specifically we extract an example of each digit, then after we have the mu, sigma representation for each digit we can sample from that. After we sample we can run the decoder part of the VAE and generate examples. """ images = [] idx = 0 for x, y in dataset: if y == idx: images.append(x) idx += 1 if idx == 10: break encodings_digit = [] for d in range(10): with torch.no_grad(): mu, sigma = model.encode(images[d].view(1, 784)) encodings_digit.append((mu, sigma)) mu, sigma = encodings_digit[digit] for example in range(num_examples): epsilon = torch.randn_like(sigma) z = mu + sigma * epsilon out = model.decode(z) out = out.view(-1, 1, 28, 28) save_image(out, f"generated_{digit}_ex{example}.png")
Generates (num_examples) of a particular digit. Specifically we extract an example of each digit, then after we have the mu, sigma representation for each digit we can sample from that. After we sample we can run the decoder part of the VAE and generate examples.
inference
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/more_advanced/VAE/lightning_vae/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/more_advanced/VAE/lightning_vae/utils.py
MIT
def intersection_over_union(boxes_preds, boxes_labels, box_format="midpoint"): """ Calculates intersection over union Parameters: boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4) boxes_labels (tensor): Correct Labels of Boxes (BATCH_SIZE, 4) box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2) Returns: tensor: Intersection over union for all examples """ # Slicing idx:idx+1 in order to keep tensor dimensionality # Doing ... in indexing if there would be additional dimensions # Like for Yolo algorithm which would have (N, S, S, 4) in shape if box_format == "midpoint": box1_x1 = boxes_preds[..., 0:1] - boxes_preds[..., 2:3] / 2 box1_y1 = boxes_preds[..., 1:2] - boxes_preds[..., 3:4] / 2 box1_x2 = boxes_preds[..., 0:1] + boxes_preds[..., 2:3] / 2 box1_y2 = boxes_preds[..., 1:2] + boxes_preds[..., 3:4] / 2 box2_x1 = boxes_labels[..., 0:1] - boxes_labels[..., 2:3] / 2 box2_y1 = boxes_labels[..., 1:2] - boxes_labels[..., 3:4] / 2 box2_x2 = boxes_labels[..., 0:1] + boxes_labels[..., 2:3] / 2 box2_y2 = boxes_labels[..., 1:2] + boxes_labels[..., 3:4] / 2 elif box_format == "corners": box1_x1 = boxes_preds[..., 0:1] box1_y1 = boxes_preds[..., 1:2] box1_x2 = boxes_preds[..., 2:3] box1_y2 = boxes_preds[..., 3:4] box2_x1 = boxes_labels[..., 0:1] box2_y1 = boxes_labels[..., 1:2] box2_x2 = boxes_labels[..., 2:3] box2_y2 = boxes_labels[..., 3:4] x1 = torch.max(box1_x1, box2_x1) y1 = torch.max(box1_y1, box2_y1) x2 = torch.min(box1_x2, box2_x2) y2 = torch.min(box1_y2, box2_y2) # Need clamp(0) in case they do not intersect, then we want intersection to be 0 intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0) box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1)) box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1)) return intersection / (box1_area + box2_area - intersection + 1e-6)
Calculates intersection over union Parameters: boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4) boxes_labels (tensor): Correct Labels of Boxes (BATCH_SIZE, 4) box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2) Returns: tensor: Intersection over union for all examples
intersection_over_union
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/metrics/iou.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/metrics/iou.py
MIT
def mean_average_precision( pred_boxes, true_boxes, iou_threshold=0.5, box_format="midpoint", num_classes=20 ): """ Calculates mean average precision Parameters: pred_boxes (list): list of lists containing all bboxes with each bboxes specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2] true_boxes (list): Similar as pred_boxes except all the correct ones iou_threshold (float): threshold where predicted bboxes is correct box_format (str): "midpoint" or "corners" used to specify bboxes num_classes (int): number of classes Returns: float: mAP value across all classes given a specific IoU threshold """ # list storing all AP for respective classes average_precisions = [] # used for numerical stability later on epsilon = 1e-6 for c in range(num_classes): detections = [] ground_truths = [] # Go through all predictions and targets, # and only add the ones that belong to the # current class c for detection in pred_boxes: if detection[1] == c: detections.append(detection) for true_box in true_boxes: if true_box[1] == c: ground_truths.append(true_box) # find the amount of bboxes for each training example # Counter here finds how many ground truth bboxes we get # for each training example, so let's say img 0 has 3, # img 1 has 5 then we will obtain a dictionary with: # amount_bboxes = {0:3, 1:5} amount_bboxes = Counter([gt[0] for gt in ground_truths]) # We then go through each key, val in this dictionary # and convert to the following (w.r.t same example): # ammount_bboxes = {0:torch.tensor[0,0,0], 1:torch.tensor[0,0,0,0,0]} for key, val in amount_bboxes.items(): amount_bboxes[key] = torch.zeros(val) # sort by box probabilities which is index 2 detections.sort(key=lambda x: x[2], reverse=True) TP = torch.zeros((len(detections))) FP = torch.zeros((len(detections))) total_true_bboxes = len(ground_truths) # If none exists for this class then we can safely skip if total_true_bboxes == 0: continue for detection_idx, detection in enumerate(detections): # Only take out the ground_truths that have the same # training idx as detection ground_truth_img = [ bbox for bbox in ground_truths if bbox[0] == detection[0] ] num_gts = len(ground_truth_img) best_iou = 0 for idx, gt in enumerate(ground_truth_img): iou = intersection_over_union( torch.tensor(detection[3:]), torch.tensor(gt[3:]), box_format=box_format, ) if iou > best_iou: best_iou = iou best_gt_idx = idx if best_iou > iou_threshold: # only detect ground truth detection once if amount_bboxes[detection[0]][best_gt_idx] == 0: # true positive and add this bounding box to seen TP[detection_idx] = 1 amount_bboxes[detection[0]][best_gt_idx] = 1 else: FP[detection_idx] = 1 # if IOU is lower then the detection is a false positive else: FP[detection_idx] = 1 TP_cumsum = torch.cumsum(TP, dim=0) FP_cumsum = torch.cumsum(FP, dim=0) recalls = TP_cumsum / (total_true_bboxes + epsilon) precisions = TP_cumsum / (TP_cumsum + FP_cumsum + epsilon) precisions = torch.cat((torch.tensor([1]), precisions)) recalls = torch.cat((torch.tensor([0]), recalls)) # torch.trapz for numerical integration average_precisions.append(torch.trapz(precisions, recalls)) return sum(average_precisions) / len(average_precisions)
Calculates mean average precision Parameters: pred_boxes (list): list of lists containing all bboxes with each bboxes specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2] true_boxes (list): Similar as pred_boxes except all the correct ones iou_threshold (float): threshold where predicted bboxes is correct box_format (str): "midpoint" or "corners" used to specify bboxes num_classes (int): number of classes Returns: float: mAP value across all classes given a specific IoU threshold
mean_average_precision
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/metrics/mean_avg_precision.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/metrics/mean_avg_precision.py
MIT
def nms(bboxes, iou_threshold, threshold, box_format="corners"): """ Does Non Max Suppression given bboxes Parameters: bboxes (list): list of lists containing all bboxes with each bboxes specified as [class_pred, prob_score, x1, y1, x2, y2] iou_threshold (float): threshold where predicted bboxes is correct threshold (float): threshold to remove predicted bboxes (independent of IoU) box_format (str): "midpoint" or "corners" used to specify bboxes Returns: list: bboxes after performing NMS given a specific IoU threshold """ assert type(bboxes) == list bboxes = [box for box in bboxes if box[1] > threshold] bboxes = sorted(bboxes, key=lambda x: x[1], reverse=True) bboxes_after_nms = [] while bboxes: chosen_box = bboxes.pop(0) bboxes = [ box for box in bboxes if box[0] != chosen_box[0] or intersection_over_union( torch.tensor(chosen_box[2:]), torch.tensor(box[2:]), box_format=box_format, ) < iou_threshold ] bboxes_after_nms.append(chosen_box) return bboxes_after_nms
Does Non Max Suppression given bboxes Parameters: bboxes (list): list of lists containing all bboxes with each bboxes specified as [class_pred, prob_score, x1, y1, x2, y2] iou_threshold (float): threshold where predicted bboxes is correct threshold (float): threshold to remove predicted bboxes (independent of IoU) box_format (str): "midpoint" or "corners" used to specify bboxes Returns: list: bboxes after performing NMS given a specific IoU threshold
nms
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/metrics/nms.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/metrics/nms.py
MIT
def intersection_over_union(boxes_preds, boxes_labels, box_format="midpoint"): """ Calculates intersection over union Parameters: boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4) boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4) box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2) Returns: tensor: Intersection over union for all examples """ if box_format == "midpoint": box1_x1 = boxes_preds[..., 0:1] - boxes_preds[..., 2:3] / 2 box1_y1 = boxes_preds[..., 1:2] - boxes_preds[..., 3:4] / 2 box1_x2 = boxes_preds[..., 0:1] + boxes_preds[..., 2:3] / 2 box1_y2 = boxes_preds[..., 1:2] + boxes_preds[..., 3:4] / 2 box2_x1 = boxes_labels[..., 0:1] - boxes_labels[..., 2:3] / 2 box2_y1 = boxes_labels[..., 1:2] - boxes_labels[..., 3:4] / 2 box2_x2 = boxes_labels[..., 0:1] + boxes_labels[..., 2:3] / 2 box2_y2 = boxes_labels[..., 1:2] + boxes_labels[..., 3:4] / 2 if box_format == "corners": box1_x1 = boxes_preds[..., 0:1] box1_y1 = boxes_preds[..., 1:2] box1_x2 = boxes_preds[..., 2:3] box1_y2 = boxes_preds[..., 3:4] # (N, 1) box2_x1 = boxes_labels[..., 0:1] box2_y1 = boxes_labels[..., 1:2] box2_x2 = boxes_labels[..., 2:3] box2_y2 = boxes_labels[..., 3:4] x1 = torch.max(box1_x1, box2_x1) y1 = torch.max(box1_y1, box2_y1) x2 = torch.min(box1_x2, box2_x2) y2 = torch.min(box1_y2, box2_y2) # .clamp(0) is for the case when they do not intersect intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0) box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1)) box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1)) return intersection / (box1_area + box2_area - intersection + 1e-6)
Calculates intersection over union Parameters: boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4) boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4) box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2) Returns: tensor: Intersection over union for all examples
intersection_over_union
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLO/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLO/utils.py
MIT
def non_max_suppression(bboxes, iou_threshold, threshold, box_format="corners"): """ Does Non Max Suppression given bboxes Parameters: bboxes (list): list of lists containing all bboxes with each bboxes specified as [class_pred, prob_score, x1, y1, x2, y2] iou_threshold (float): threshold where predicted bboxes is correct threshold (float): threshold to remove predicted bboxes (independent of IoU) box_format (str): "midpoint" or "corners" used to specify bboxes Returns: list: bboxes after performing NMS given a specific IoU threshold """ assert type(bboxes) == list bboxes = [box for box in bboxes if box[1] > threshold] bboxes = sorted(bboxes, key=lambda x: x[1], reverse=True) bboxes_after_nms = [] while bboxes: chosen_box = bboxes.pop(0) bboxes = [ box for box in bboxes if box[0] != chosen_box[0] or intersection_over_union( torch.tensor(chosen_box[2:]), torch.tensor(box[2:]), box_format=box_format, ) < iou_threshold ] bboxes_after_nms.append(chosen_box) return bboxes_after_nms
Does Non Max Suppression given bboxes Parameters: bboxes (list): list of lists containing all bboxes with each bboxes specified as [class_pred, prob_score, x1, y1, x2, y2] iou_threshold (float): threshold where predicted bboxes is correct threshold (float): threshold to remove predicted bboxes (independent of IoU) box_format (str): "midpoint" or "corners" used to specify bboxes Returns: list: bboxes after performing NMS given a specific IoU threshold
non_max_suppression
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLO/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLO/utils.py
MIT
def mean_average_precision( pred_boxes, true_boxes, iou_threshold=0.5, box_format="midpoint", num_classes=20 ): """ Calculates mean average precision Parameters: pred_boxes (list): list of lists containing all bboxes with each bboxes specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2] true_boxes (list): Similar as pred_boxes except all the correct ones iou_threshold (float): threshold where predicted bboxes is correct box_format (str): "midpoint" or "corners" used to specify bboxes num_classes (int): number of classes Returns: float: mAP value across all classes given a specific IoU threshold """ # list storing all AP for respective classes average_precisions = [] # used for numerical stability later on epsilon = 1e-6 for c in range(num_classes): detections = [] ground_truths = [] # Go through all predictions and targets, # and only add the ones that belong to the # current class c for detection in pred_boxes: if detection[1] == c: detections.append(detection) for true_box in true_boxes: if true_box[1] == c: ground_truths.append(true_box) # find the amount of bboxes for each training example # Counter here finds how many ground truth bboxes we get # for each training example, so let's say img 0 has 3, # img 1 has 5 then we will obtain a dictionary with: # amount_bboxes = {0:3, 1:5} amount_bboxes = Counter([gt[0] for gt in ground_truths]) # We then go through each key, val in this dictionary # and convert to the following (w.r.t same example): # ammount_bboxes = {0:torch.tensor[0,0,0], 1:torch.tensor[0,0,0,0,0]} for key, val in amount_bboxes.items(): amount_bboxes[key] = torch.zeros(val) # sort by box probabilities which is index 2 detections.sort(key=lambda x: x[2], reverse=True) TP = torch.zeros((len(detections))) FP = torch.zeros((len(detections))) total_true_bboxes = len(ground_truths) # If none exists for this class then we can safely skip if total_true_bboxes == 0: continue for detection_idx, detection in enumerate(detections): # Only take out the ground_truths that have the same # training idx as detection ground_truth_img = [ bbox for bbox in ground_truths if bbox[0] == detection[0] ] num_gts = len(ground_truth_img) best_iou = 0 for idx, gt in enumerate(ground_truth_img): iou = intersection_over_union( torch.tensor(detection[3:]), torch.tensor(gt[3:]), box_format=box_format, ) if iou > best_iou: best_iou = iou best_gt_idx = idx if best_iou > iou_threshold: # only detect ground truth detection once if amount_bboxes[detection[0]][best_gt_idx] == 0: # true positive and add this bounding box to seen TP[detection_idx] = 1 amount_bboxes[detection[0]][best_gt_idx] = 1 else: FP[detection_idx] = 1 # if IOU is lower then the detection is a false positive else: FP[detection_idx] = 1 TP_cumsum = torch.cumsum(TP, dim=0) FP_cumsum = torch.cumsum(FP, dim=0) recalls = TP_cumsum / (total_true_bboxes + epsilon) precisions = torch.divide(TP_cumsum, (TP_cumsum + FP_cumsum + epsilon)) precisions = torch.cat((torch.tensor([1]), precisions)) recalls = torch.cat((torch.tensor([0]), recalls)) # torch.trapz for numerical integration average_precisions.append(torch.trapz(precisions, recalls)) return sum(average_precisions) / len(average_precisions)
Calculates mean average precision Parameters: pred_boxes (list): list of lists containing all bboxes with each bboxes specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2] true_boxes (list): Similar as pred_boxes except all the correct ones iou_threshold (float): threshold where predicted bboxes is correct box_format (str): "midpoint" or "corners" used to specify bboxes num_classes (int): number of classes Returns: float: mAP value across all classes given a specific IoU threshold
mean_average_precision
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLO/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLO/utils.py
MIT
def plot_image(image, boxes): """Plots predicted bounding boxes on the image""" im = np.array(image) height, width, _ = im.shape # Create figure and axes fig, ax = plt.subplots(1) # Display the image ax.imshow(im) # box[0] is x midpoint, box[2] is width # box[1] is y midpoint, box[3] is height # Create a Rectangle potch for box in boxes: box = box[2:] assert len(box) == 4, "Got more values than in x, y, w, h, in a box!" upper_left_x = box[0] - box[2] / 2 upper_left_y = box[1] - box[3] / 2 rect = patches.Rectangle( (upper_left_x * width, upper_left_y * height), box[2] * width, box[3] * height, linewidth=1, edgecolor="r", facecolor="none", ) # Add the patch to the Axes ax.add_patch(rect) plt.show()
Plots predicted bounding boxes on the image
plot_image
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLO/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLO/utils.py
MIT
def convert_cellboxes(predictions, S=7): """ Converts bounding boxes output from Yolo with an image split size of S into entire image ratios rather than relative to cell ratios. Tried to do this vectorized, but this resulted in quite difficult to read code... Use as a black box? Or implement a more intuitive, using 2 for loops iterating range(S) and convert them one by one, resulting in a slower but more readable implementation. """ predictions = predictions.to("cpu") batch_size = predictions.shape[0] predictions = predictions.reshape(batch_size, 7, 7, 30) bboxes1 = predictions[..., 21:25] bboxes2 = predictions[..., 26:30] scores = torch.cat( (predictions[..., 20].unsqueeze(0), predictions[..., 25].unsqueeze(0)), dim=0 ) best_box = scores.argmax(0).unsqueeze(-1) best_boxes = bboxes1 * (1 - best_box) + best_box * bboxes2 cell_indices = torch.arange(7).repeat(batch_size, 7, 1).unsqueeze(-1) x = 1 / S * (best_boxes[..., :1] + cell_indices) y = 1 / S * (best_boxes[..., 1:2] + cell_indices.permute(0, 2, 1, 3)) w_y = 1 / S * best_boxes[..., 2:4] converted_bboxes = torch.cat((x, y, w_y), dim=-1) predicted_class = predictions[..., :20].argmax(-1).unsqueeze(-1) best_confidence = torch.max(predictions[..., 20], predictions[..., 25]).unsqueeze( -1 ) converted_preds = torch.cat( (predicted_class, best_confidence, converted_bboxes), dim=-1 ) return converted_preds
Converts bounding boxes output from Yolo with an image split size of S into entire image ratios rather than relative to cell ratios. Tried to do this vectorized, but this resulted in quite difficult to read code... Use as a black box? Or implement a more intuitive, using 2 for loops iterating range(S) and convert them one by one, resulting in a slower but more readable implementation.
convert_cellboxes
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLO/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLO/utils.py
MIT
def iou_width_height(boxes1, boxes2): """ Parameters: boxes1 (tensor): width and height of the first bounding boxes boxes2 (tensor): width and height of the second bounding boxes Returns: tensor: Intersection over union of the corresponding boxes """ intersection = torch.min(boxes1[..., 0], boxes2[..., 0]) * torch.min( boxes1[..., 1], boxes2[..., 1] ) union = ( boxes1[..., 0] * boxes1[..., 1] + boxes2[..., 0] * boxes2[..., 1] - intersection ) return intersection / union
Parameters: boxes1 (tensor): width and height of the first bounding boxes boxes2 (tensor): width and height of the second bounding boxes Returns: tensor: Intersection over union of the corresponding boxes
iou_width_height
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLOv3/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLOv3/utils.py
MIT
def intersection_over_union(boxes_preds, boxes_labels, box_format="midpoint"): """ Video explanation of this function: https://youtu.be/XXYG5ZWtjj0 This function calculates intersection over union (iou) given pred boxes and target boxes. Parameters: boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4) boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4) box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2) Returns: tensor: Intersection over union for all examples """ if box_format == "midpoint": box1_x1 = boxes_preds[..., 0:1] - boxes_preds[..., 2:3] / 2 box1_y1 = boxes_preds[..., 1:2] - boxes_preds[..., 3:4] / 2 box1_x2 = boxes_preds[..., 0:1] + boxes_preds[..., 2:3] / 2 box1_y2 = boxes_preds[..., 1:2] + boxes_preds[..., 3:4] / 2 box2_x1 = boxes_labels[..., 0:1] - boxes_labels[..., 2:3] / 2 box2_y1 = boxes_labels[..., 1:2] - boxes_labels[..., 3:4] / 2 box2_x2 = boxes_labels[..., 0:1] + boxes_labels[..., 2:3] / 2 box2_y2 = boxes_labels[..., 1:2] + boxes_labels[..., 3:4] / 2 if box_format == "corners": box1_x1 = boxes_preds[..., 0:1] box1_y1 = boxes_preds[..., 1:2] box1_x2 = boxes_preds[..., 2:3] box1_y2 = boxes_preds[..., 3:4] box2_x1 = boxes_labels[..., 0:1] box2_y1 = boxes_labels[..., 1:2] box2_x2 = boxes_labels[..., 2:3] box2_y2 = boxes_labels[..., 3:4] x1 = torch.max(box1_x1, box2_x1) y1 = torch.max(box1_y1, box2_y1) x2 = torch.min(box1_x2, box2_x2) y2 = torch.min(box1_y2, box2_y2) intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0) box1_area = abs((box1_x2 - box1_x1) * (box1_y2 - box1_y1)) box2_area = abs((box2_x2 - box2_x1) * (box2_y2 - box2_y1)) return intersection / (box1_area + box2_area - intersection + 1e-6)
Video explanation of this function: https://youtu.be/XXYG5ZWtjj0 This function calculates intersection over union (iou) given pred boxes and target boxes. Parameters: boxes_preds (tensor): Predictions of Bounding Boxes (BATCH_SIZE, 4) boxes_labels (tensor): Correct labels of Bounding Boxes (BATCH_SIZE, 4) box_format (str): midpoint/corners, if boxes (x,y,w,h) or (x1,y1,x2,y2) Returns: tensor: Intersection over union for all examples
intersection_over_union
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLOv3/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLOv3/utils.py
MIT
def non_max_suppression(bboxes, iou_threshold, threshold, box_format="corners"): """ Video explanation of this function: https://youtu.be/YDkjWEN8jNA Does Non Max Suppression given bboxes Parameters: bboxes (list): list of lists containing all bboxes with each bboxes specified as [class_pred, prob_score, x1, y1, x2, y2] iou_threshold (float): threshold where predicted bboxes is correct threshold (float): threshold to remove predicted bboxes (independent of IoU) box_format (str): "midpoint" or "corners" used to specify bboxes Returns: list: bboxes after performing NMS given a specific IoU threshold """ assert type(bboxes) == list bboxes = [box for box in bboxes if box[1] > threshold] bboxes = sorted(bboxes, key=lambda x: x[1], reverse=True) bboxes_after_nms = [] while bboxes: chosen_box = bboxes.pop(0) bboxes = [ box for box in bboxes if box[0] != chosen_box[0] or intersection_over_union( torch.tensor(chosen_box[2:]), torch.tensor(box[2:]), box_format=box_format, ) < iou_threshold ] bboxes_after_nms.append(chosen_box) return bboxes_after_nms
Video explanation of this function: https://youtu.be/YDkjWEN8jNA Does Non Max Suppression given bboxes Parameters: bboxes (list): list of lists containing all bboxes with each bboxes specified as [class_pred, prob_score, x1, y1, x2, y2] iou_threshold (float): threshold where predicted bboxes is correct threshold (float): threshold to remove predicted bboxes (independent of IoU) box_format (str): "midpoint" or "corners" used to specify bboxes Returns: list: bboxes after performing NMS given a specific IoU threshold
non_max_suppression
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLOv3/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLOv3/utils.py
MIT
def mean_average_precision( pred_boxes, true_boxes, iou_threshold=0.5, box_format="midpoint", num_classes=20 ): """ Video explanation of this function: https://youtu.be/FppOzcDvaDI This function calculates mean average precision (mAP) Parameters: pred_boxes (list): list of lists containing all bboxes with each bboxes specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2] true_boxes (list): Similar as pred_boxes except all the correct ones iou_threshold (float): threshold where predicted bboxes is correct box_format (str): "midpoint" or "corners" used to specify bboxes num_classes (int): number of classes Returns: float: mAP value across all classes given a specific IoU threshold """ # list storing all AP for respective classes average_precisions = [] # used for numerical stability later on epsilon = 1e-6 for c in range(num_classes): detections = [] ground_truths = [] # Go through all predictions and targets, # and only add the ones that belong to the # current class c for detection in pred_boxes: if detection[1] == c: detections.append(detection) for true_box in true_boxes: if true_box[1] == c: ground_truths.append(true_box) # find the amount of bboxes for each training example # Counter here finds how many ground truth bboxes we get # for each training example, so let's say img 0 has 3, # img 1 has 5 then we will obtain a dictionary with: # amount_bboxes = {0:3, 1:5} amount_bboxes = Counter([gt[0] for gt in ground_truths]) # We then go through each key, val in this dictionary # and convert to the following (w.r.t same example): # ammount_bboxes = {0:torch.tensor[0,0,0], 1:torch.tensor[0,0,0,0,0]} for key, val in amount_bboxes.items(): amount_bboxes[key] = torch.zeros(val) # sort by box probabilities which is index 2 detections.sort(key=lambda x: x[2], reverse=True) TP = torch.zeros((len(detections))) FP = torch.zeros((len(detections))) total_true_bboxes = len(ground_truths) # If none exists for this class then we can safely skip if total_true_bboxes == 0: continue for detection_idx, detection in enumerate(detections): # Only take out the ground_truths that have the same # training idx as detection ground_truth_img = [ bbox for bbox in ground_truths if bbox[0] == detection[0] ] num_gts = len(ground_truth_img) best_iou = 0 for idx, gt in enumerate(ground_truth_img): iou = intersection_over_union( torch.tensor(detection[3:]), torch.tensor(gt[3:]), box_format=box_format, ) if iou > best_iou: best_iou = iou best_gt_idx = idx if best_iou > iou_threshold: # only detect ground truth detection once if amount_bboxes[detection[0]][best_gt_idx] == 0: # true positive and add this bounding box to seen TP[detection_idx] = 1 amount_bboxes[detection[0]][best_gt_idx] = 1 else: FP[detection_idx] = 1 # if IOU is lower then the detection is a false positive else: FP[detection_idx] = 1 TP_cumsum = torch.cumsum(TP, dim=0) FP_cumsum = torch.cumsum(FP, dim=0) recalls = TP_cumsum / (total_true_bboxes + epsilon) precisions = TP_cumsum / (TP_cumsum + FP_cumsum + epsilon) precisions = torch.cat((torch.tensor([1]), precisions)) recalls = torch.cat((torch.tensor([0]), recalls)) # torch.trapz for numerical integration average_precisions.append(torch.trapz(precisions, recalls)) return sum(average_precisions) / len(average_precisions)
Video explanation of this function: https://youtu.be/FppOzcDvaDI This function calculates mean average precision (mAP) Parameters: pred_boxes (list): list of lists containing all bboxes with each bboxes specified as [train_idx, class_prediction, prob_score, x1, y1, x2, y2] true_boxes (list): Similar as pred_boxes except all the correct ones iou_threshold (float): threshold where predicted bboxes is correct box_format (str): "midpoint" or "corners" used to specify bboxes num_classes (int): number of classes Returns: float: mAP value across all classes given a specific IoU threshold
mean_average_precision
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLOv3/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLOv3/utils.py
MIT
def plot_image(image, boxes): """Plots predicted bounding boxes on the image""" cmap = plt.get_cmap("tab20b") class_labels = config.COCO_LABELS if config.DATASET=='COCO' else config.PASCAL_CLASSES colors = [cmap(i) for i in np.linspace(0, 1, len(class_labels))] im = np.array(image) height, width, _ = im.shape # Create figure and axes fig, ax = plt.subplots(1) # Display the image ax.imshow(im) # box[0] is x midpoint, box[2] is width # box[1] is y midpoint, box[3] is height # Create a Rectangle patch for box in boxes: assert len(box) == 6, "box should contain class pred, confidence, x, y, width, height" class_pred = box[0] box = box[2:] upper_left_x = box[0] - box[2] / 2 upper_left_y = box[1] - box[3] / 2 rect = patches.Rectangle( (upper_left_x * width, upper_left_y * height), box[2] * width, box[3] * height, linewidth=2, edgecolor=colors[int(class_pred)], facecolor="none", ) # Add the patch to the Axes ax.add_patch(rect) plt.text( upper_left_x * width, upper_left_y * height, s=class_labels[int(class_pred)], color="white", verticalalignment="top", bbox={"color": colors[int(class_pred)], "pad": 0}, ) plt.show()
Plots predicted bounding boxes on the image
plot_image
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLOv3/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLOv3/utils.py
MIT
def cells_to_bboxes(predictions, anchors, S, is_preds=True): """ Scales the predictions coming from the model to be relative to the entire image such that they for example later can be plotted or. INPUT: predictions: tensor of size (N, 3, S, S, num_classes+5) anchors: the anchors used for the predictions S: the number of cells the image is divided in on the width (and height) is_preds: whether the input is predictions or the true bounding boxes OUTPUT: converted_bboxes: the converted boxes of sizes (N, num_anchors, S, S, 1+5) with class index, object score, bounding box coordinates """ BATCH_SIZE = predictions.shape[0] num_anchors = len(anchors) box_predictions = predictions[..., 1:5] if is_preds: anchors = anchors.reshape(1, len(anchors), 1, 1, 2) box_predictions[..., 0:2] = torch.sigmoid(box_predictions[..., 0:2]) box_predictions[..., 2:] = torch.exp(box_predictions[..., 2:]) * anchors scores = torch.sigmoid(predictions[..., 0:1]) best_class = torch.argmax(predictions[..., 5:], dim=-1).unsqueeze(-1) else: scores = predictions[..., 0:1] best_class = predictions[..., 5:6] cell_indices = ( torch.arange(S) .repeat(predictions.shape[0], 3, S, 1) .unsqueeze(-1) .to(predictions.device) ) x = 1 / S * (box_predictions[..., 0:1] + cell_indices) y = 1 / S * (box_predictions[..., 1:2] + cell_indices.permute(0, 1, 3, 2, 4)) w_h = 1 / S * box_predictions[..., 2:4] converted_bboxes = torch.cat((best_class, scores, x, y, w_h), dim=-1).reshape(BATCH_SIZE, num_anchors * S * S, 6) return converted_bboxes.tolist()
Scales the predictions coming from the model to be relative to the entire image such that they for example later can be plotted or. INPUT: predictions: tensor of size (N, 3, S, S, num_classes+5) anchors: the anchors used for the predictions S: the number of cells the image is divided in on the width (and height) is_preds: whether the input is predictions or the true bounding boxes OUTPUT: converted_bboxes: the converted boxes of sizes (N, num_anchors, S, S, 1+5) with class index, object score, bounding box coordinates
cells_to_bboxes
python
aladdinpersson/Machine-Learning-Collection
ML/Pytorch/object_detection/YOLOv3/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/object_detection/YOLOv3/utils.py
MIT
def plot_to_image(figure): """Converts the matplotlib plot specified by 'figure' to a PNG image and returns it. The supplied figure is closed and inaccessible after this call.""" # Save the plot to a PNG in memory. buf = io.BytesIO() plt.savefig(buf, format="png") # Closing the figure prevents it from being displayed directly inside # the notebook. plt.close(figure) buf.seek(0) # Convert PNG buffer to TF image image = tf.image.decode_png(buf.getvalue(), channels=4) # Add the batch dimension image = tf.expand_dims(image, 0) return image
Converts the matplotlib plot specified by 'figure' to a PNG image and returns it. The supplied figure is closed and inaccessible after this call.
plot_to_image
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/Basics/tutorial17-tensorboard/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/Basics/tutorial17-tensorboard/utils.py
MIT
def create_sprite(data): """ Tile images into sprite image. Add any necessary padding """ # For B&W or greyscale images if len(data.shape) == 3: data = np.tile(data[..., np.newaxis], (1, 1, 1, 3)) n = int(np.ceil(np.sqrt(data.shape[0]))) padding = ((0, n ** 2 - data.shape[0]), (0, 0), (0, 0), (0, 0)) data = np.pad(data, padding, mode="constant", constant_values=0) # Tile images into sprite data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3, 4)) # print(data.shape) => (n, image_height, n, image_width, 3) data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:]) # print(data.shape) => (n * image_height, n * image_width, 3) return data
Tile images into sprite image. Add any necessary padding
create_sprite
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/Basics/tutorial17-tensorboard/utils.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/Basics/tutorial17-tensorboard/utils.py
MIT
def AlexNet(input_shape: typing.Tuple[int], classes: int = 1000) -> Model: """ Implementation of the AlexNet architecture. Arguments: input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Note: when you read the paper, you will notice that the channels (filters) in the diagram is only half of what I have written below. That is because in the diagram, they only showed model for one GPU (I guess for simplicity). However, during the ILSVRC, they run the network across 2 NVIDIA GTA 580 3GB GPUs. Also, in paper, they used Local Response Normalization. This can also be done in Keras with Lambda layer. You can also use BatchNormalization layer instead. """ # convert input shape into tensor X_input = Input(input_shape) # NOTE: layer 1-5 is conv-layers # layer 1 X = Conv2D( filters = 96, kernel_size = (11, 11), strides = (4, 4), activation = "relu", padding = "same", )(X_input) X = MaxPooling2D(pool_size = (3, 3), strides = (2, 2))(X) X = Lambda(tf.nn.local_response_normalization)(X) # layer 2 X = Conv2D( filters = 256, kernel_size = (5, 5), strides = (1, 1), activation = "relu", padding = "same", )(X) X = MaxPooling2D(pool_size = (3, 3), strides = (2, 2))(X) X = Lambda(tf.nn.local_response_normalization)(X) # layer 3 X = Conv2D( filters = 384, kernel_size = (3, 3), strides = (1, 1), activation = "relu", padding = "same", )(X) # layer 4 X = Conv2D( filters = 384, kernel_size = (3, 3), strides = (1, 1), activation = "relu", padding = "same", )(X) # layer 5 X = Conv2D( filters = 256, kernel_size = (3, 3), strides = (1, 1), activation = "relu", padding = "same", )(X) X = MaxPooling2D(pool_size = (3, 3), strides = (2, 2))(X) X = Lambda(tf.nn.local_response_normalization)(X) # NOTE: layer 6-7 is fully-connected layers # layer 6 X = Flatten()(X) X = Dense(units = 4096, activation = 'relu')(X) X = Dropout(0.5)(X) # layer 7 X = Dense(units = 4096, activation = 'relu')(X) X = Dropout(0.5)(X) # layer 8 (classification layer) # use sigmoid if binary classificaton and softmax if multiclass classification X = Dense(units = classes, activation = "softmax")(X) model = Model(inputs = X_input, outputs = X, name = "AlexNet") return model
Implementation of the AlexNet architecture. Arguments: input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Note: when you read the paper, you will notice that the channels (filters) in the diagram is only half of what I have written below. That is because in the diagram, they only showed model for one GPU (I guess for simplicity). However, during the ILSVRC, they run the network across 2 NVIDIA GTA 580 3GB GPUs. Also, in paper, they used Local Response Normalization. This can also be done in Keras with Lambda layer. You can also use BatchNormalization layer instead.
AlexNet
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/AlexNet/alexnet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/AlexNet/alexnet.py
MIT
def convolution_block( X: tf.Tensor, filters: int, kernel_size: int, stride: int = 1, padding: str = 'valid', ) -> tf.Tensor: """ Convolution block for GoogLeNet. Arguments: X -- input tensor of shape (m, H, W, filters) filters -- defining the number of filters in the CONV layers kernel_size -- integer, specifying the shape of the middle CONV's window for the main path stride -- integer specifying the stride to be used padding -- padding type, same or valid. Default is valid Returns: X -- output of the identity block, tensor of shape (H, W, filters) """ X = Conv2D( filters = filters, kernel_size = (kernel_size, kernel_size), strides = (stride, stride), padding = padding, )(X) # batch normalization is not in original paper because it was not invented at that time # however I am using it here because it will improve the performance X = BatchNormalization()(X) X = Activation("relu")(X) return X
Convolution block for GoogLeNet. Arguments: X -- input tensor of shape (m, H, W, filters) filters -- defining the number of filters in the CONV layers kernel_size -- integer, specifying the shape of the middle CONV's window for the main path stride -- integer specifying the stride to be used padding -- padding type, same or valid. Default is valid Returns: X -- output of the identity block, tensor of shape (H, W, filters)
convolution_block
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/GoogLeNet/block.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/GoogLeNet/block.py
MIT
def inception_block( X: tf.Tensor, filters_1x1: int, filters_3x3_reduce: int, filters_3x3: int, filters_5x5_reduce: int, filters_5x5: int, pool_size: int, ) -> tf.Tensor: """ Inception block for GoogLeNet. Arguments: X -- input tensor of shape (m, H, W, filters) filters_1x1 -- number of filters for (1x1 conv) in first branch filters_3x3_reduce -- number of filters for (1x1 conv) dimensionality reduction before (3x3 conv) in second branch filters_3x3 -- number of filters for (3x3 conv) in second branch filters_5x5_reduce -- number of filters for (1x1 conv) dimensionality reduction before (5x5 conv) in third branch filters_5x5 -- number of filters for (5x5 conv) in third branch pool_size -- number of filters for (1x1 conv) after 3x3 max pooling in fourth branch Returns: X -- output of the identity block, tensor of shape (H, W, filters) """ # first branch conv_1x1 = convolution_block( X, filters = filters_1x1, kernel_size = 1, padding = "same" ) # second branch conv_3x3 = convolution_block( X, filters = filters_3x3_reduce, kernel_size = 1, padding = "same" ) conv_3x3 = convolution_block( conv_3x3, filters = filters_3x3, kernel_size = 3, padding = "same" ) # third branch conv_5x5 = convolution_block( X, filters = filters_5x5_reduce, kernel_size = 1, padding = "same" ) conv_5x5 = convolution_block( conv_5x5, filters = filters_5x5, kernel_size = 5, padding = "same" ) # fourth branch pool_projection = MaxPooling2D( pool_size = (2, 2), strides = (1, 1), padding = "same", )(X) pool_projection = convolution_block( pool_projection, filters = pool_size, kernel_size = 1, padding = "same" ) # concat by channel/filter return concatenate(inputs = [conv_1x1, conv_3x3, conv_5x5, pool_projection], axis = 3)
Inception block for GoogLeNet. Arguments: X -- input tensor of shape (m, H, W, filters) filters_1x1 -- number of filters for (1x1 conv) in first branch filters_3x3_reduce -- number of filters for (1x1 conv) dimensionality reduction before (3x3 conv) in second branch filters_3x3 -- number of filters for (3x3 conv) in second branch filters_5x5_reduce -- number of filters for (1x1 conv) dimensionality reduction before (5x5 conv) in third branch filters_5x5 -- number of filters for (5x5 conv) in third branch pool_size -- number of filters for (1x1 conv) after 3x3 max pooling in fourth branch Returns: X -- output of the identity block, tensor of shape (H, W, filters)
inception_block
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/GoogLeNet/block.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/GoogLeNet/block.py
MIT
def auxiliary_block( X: tf.Tensor, classes: int, ) -> tf.Tensor: """ Auxiliary block for GoogLeNet. Refer to the original paper, page 8 for the auxiliary layer specification. Arguments: X -- input tensor of shape (m, H, W, filters) classes -- number of classes for classification Return: X -- output of the identity block, tensor of shape (H, W, filters) """ X = AveragePooling2D( pool_size = (5, 5), padding = "same", strides = (3, 3), )(X) X = convolution_block( X, filters = 128, kernel_size = 1, stride = 1, padding = "same", ) X = Flatten()(X) X = Dense(units = 1024, activation = "relu")(X) X = Dropout(rate = 0.7)(X) X = Dense(units = classes)(X) X = Activation("softmax")(X) return X
Auxiliary block for GoogLeNet. Refer to the original paper, page 8 for the auxiliary layer specification. Arguments: X -- input tensor of shape (m, H, W, filters) classes -- number of classes for classification Return: X -- output of the identity block, tensor of shape (H, W, filters)
auxiliary_block
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/GoogLeNet/block.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/GoogLeNet/block.py
MIT
def GoogLeNet(input_shape: typing.Tuple[int] = (224, 224, 3), classes: int = 1000) -> Model: """ Implementation of the popular GoogLeNet aka Inception v1 architecture. Refer to the original paper, page 6 - table 1 for inception block filter sizes. Arguments: input_shape -- shape of the images of the dataset classes -- number of classes for classification Returns: model -- a Model() instance in Keras """ # convert input shape into tensor X_input = Input(input_shape) # NOTE: auxiliary layers are only used in trainig phase to improve performance # because they act as regularization and prevent vanishing gradient problem auxiliary1 = None # to store auxiliary layers classification value auxiliary2 = None # layer 1 (convolution block) X = convolution_block( X = X_input, filters = 64, kernel_size = 7, stride = 2, padding = "same", ) # layer 2 (max pool) X = MaxPooling2D( pool_size = (3, 3), padding = "same", strides = (2, 2), )(X) # layer 3 (convolution block) # 1x1 reduce X = convolution_block( X, filters = 64, kernel_size = 1, stride = 1, padding = "same", ) X = convolution_block( X, filters = 192, kernel_size = 3, stride = 1, padding = "same", ) # layer 4 (max pool) X = MaxPooling2D( pool_size = (3, 3), padding = "same", strides = (2, 2), )(X) # layer 5 (inception 3a) X = inception_block( X, filters_1x1 = 64, filters_3x3_reduce = 96, filters_3x3 = 128, filters_5x5_reduce = 16, filters_5x5 = 32, pool_size = 32, ) # layer 6 (inception 3b) X = inception_block( X, filters_1x1 = 128, filters_3x3_reduce = 128, filters_3x3 = 192, filters_5x5_reduce = 32, filters_5x5 = 96, pool_size = 64, ) # layer 7 (max pool) X = MaxPooling2D( pool_size = (3, 3), padding = "same", strides = (2, 2), )(X) # layer 8 (inception 4a) X = inception_block( X, filters_1x1 = 192, filters_3x3_reduce = 96, filters_3x3 = 208, filters_5x5_reduce = 16, filters_5x5 = 48, pool_size = 64, ) # First Auxiliary Softmax Classifier auxiliary1 = auxiliary_block(X, classes = classes) # layer 9 (inception 4b) X = inception_block( X, filters_1x1 = 160, filters_3x3_reduce = 112, filters_3x3 = 224, filters_5x5_reduce = 24, filters_5x5 = 64, pool_size = 64, ) # layer 10 (inception 4c) X = inception_block( X, filters_1x1 = 128, filters_3x3_reduce = 128, filters_3x3 = 256, filters_5x5_reduce = 24, filters_5x5 = 64, pool_size = 64, ) # layer 11 (inception 4d) X = inception_block( X, filters_1x1 = 112, filters_3x3_reduce = 144, filters_3x3 = 288, filters_5x5_reduce = 32, filters_5x5 = 64, pool_size = 64, ) # Second Auxiliary Softmax Classifier auxiliary2 = auxiliary_block(X, classes = classes) # layer 12 (inception 4e) X = inception_block( X, filters_1x1 = 256, filters_3x3_reduce = 160, filters_3x3 = 320, filters_5x5_reduce = 32, filters_5x5 = 128, pool_size = 128, ) # layer 13 (max pool) X = MaxPooling2D( pool_size = (3, 3), padding = "same", strides = (2, 2), )(X) # layer 14 (inception 5a) X = inception_block( X, filters_1x1 = 256, filters_3x3_reduce = 160, filters_3x3 = 320, filters_5x5_reduce = 32, filters_5x5 = 128, pool_size = 128, ) # layer 15 (inception 5b) X = inception_block( X, filters_1x1 = 384, filters_3x3_reduce = 192, filters_3x3 = 384, filters_5x5_reduce = 48, filters_5x5 = 128, pool_size = 128, ) # layer 16 (average pool) X = AveragePooling2D( pool_size = (7, 7), padding = "same", strides = (1, 1), )(X) # layer 17 (dropout 40%) X = Dropout(rate = 0.4)(X) # layer 18 (fully-connected layer with softmax activation) X = Dense(units = classes, activation='softmax')(X) model = Model(X_input, outputs = [X, auxiliary1, auxiliary2], name='GoogLeNet/Inception-v1') return model
Implementation of the popular GoogLeNet aka Inception v1 architecture. Refer to the original paper, page 6 - table 1 for inception block filter sizes. Arguments: input_shape -- shape of the images of the dataset classes -- number of classes for classification Returns: model -- a Model() instance in Keras
GoogLeNet
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/GoogLeNet/googlenet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/GoogLeNet/googlenet.py
MIT
def LeNet5(input_shape: typing.Tuple[int], classes: int = 1000) -> Model: """ Implementation of the classic LeNet architecture. Arguments: input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Note: because I want to keep it original, I used tanh activation instead of ReLU activation. however based on newer papers, the rectified linear unit (ReLU) performed much faster than tanh activation. """ # convert input shape into tensor X_input = Input(input_shape) # layer 1 X = Conv2D( filters = 6, kernel_size = (5, 5), strides = (1, 1), activation = "tanh", padding = "valid", )(X_input) X = AveragePooling2D(pool_size = (2, 2), strides = (2, 2), padding = "valid")(X) # layer 2 X = Conv2D( filters = 16, kernel_size = (5, 5), strides = (1, 1), activation = "tanh", padding = "valid", )(X) X = AveragePooling2D(pool_size = (2, 2), strides = (2, 2), padding = "valid")(X) # layer 3 X = Conv2D( filters = 120, kernel_size = (5, 5), strides = (1, 1), activation = "tanh", padding = "valid", )(X) # layer 4 X = Flatten()(X) X = Dense(units = 84, activation = "tanh")(X) # layer 5 (classification layer) X = Dense(units = classes, activation = "softmax")(X) model = Model(inputs = X_input, outputs = X, name = "LeNet5") return model
Implementation of the classic LeNet architecture. Arguments: input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Note: because I want to keep it original, I used tanh activation instead of ReLU activation. however based on newer papers, the rectified linear unit (ReLU) performed much faster than tanh activation.
LeNet5
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/LeNet5/lenet5.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/LeNet5/lenet5.py
MIT
def block( X: tf.Tensor, kernel_size: int, filters: typing.List[int], stage_no: int, block_name: str, is_conv_layer: bool = False, stride: int = 2 ) -> tf.Tensor: """ Block for residual network. Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) kernel_size -- integer, specifying the shape of the middle CONV's window for the main path filters -- python list of integers, defining the number of filters in the CONV layers of the main path stage_no -- integer, used to name the layers, depending on their position in the network block_name -- string/character, used to name the layers, depending on their position in the network is_conv_layer -- to identiy if identity downsample is needed stride -- integer specifying the stride to be used Returns: X -- output of the identity block, tensor of shape (n_H, n_W, n_C) """ # names conv_name_base = "res" + str(stage_no) + block_name + "_branch" bn_name_base = "bn" + str(stage_no) + block_name + "_branch" # filters F1, F2, F3 = filters # save the input value for shortcut. X_shortcut = X # First component # NOTE: if conv_layer, you need to do downsampling X = Conv2D( filters = F1, kernel_size = (1, 1), strides = (stride, stride) if is_conv_layer else (1, 1), padding = "valid", name = conv_name_base + "2a", kernel_initializer = "glorot_uniform", )(X) X = BatchNormalization(axis = 3, name = bn_name_base + "2a")(X) X = Activation("relu")(X) # Second component X = Conv2D( filters = F2, kernel_size = (kernel_size, kernel_size), strides = (1, 1), padding = "same", name = conv_name_base + "2b", kernel_initializer = "glorot_uniform", )(X) X = BatchNormalization(axis = 3, name = bn_name_base + "2b")(X) X = Activation("relu")(X) # Third component X = Conv2D( filters = F3, kernel_size = (1, 1), strides = (1, 1), padding = "valid", name = conv_name_base + "2c", kernel_initializer = "glorot_uniform", )(X) X = BatchNormalization(axis = 3, name = bn_name_base + "2c")(X) # NOTE: if is_conv_layer, you need to do downsampling the X_shortcut to match the output (X) channel # so it can be added together if is_conv_layer: X_shortcut = Conv2D( filters = F3, kernel_size = (1, 1), strides = (stride, stride), padding = "valid", name = conv_name_base + "1", kernel_initializer = "glorot_uniform", )(X_shortcut) X_shortcut = BatchNormalization(axis = 3, name = bn_name_base + "1")(X_shortcut) # Shortcut value X = Add()([X, X_shortcut]) X = Activation("relu")(X) return X
Block for residual network. Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) kernel_size -- integer, specifying the shape of the middle CONV's window for the main path filters -- python list of integers, defining the number of filters in the CONV layers of the main path stage_no -- integer, used to name the layers, depending on their position in the network block_name -- string/character, used to name the layers, depending on their position in the network is_conv_layer -- to identiy if identity downsample is needed stride -- integer specifying the stride to be used Returns: X -- output of the identity block, tensor of shape (n_H, n_W, n_C)
block
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/ResNet/block.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/ResNet/block.py
MIT
def ResNet(name: str, layers: typing.List[int], input_shape: typing.Tuple[int] = (64, 64, 3), classes: int = 6) -> Model: """ Implementation of the popular ResNet architecture. Arguments: name -- name of the architecture layers -- number of blocks per layer input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Model Architecture: Resnet50: CONV2D -> BATCHNORM -> RELU -> MAXPOOL // conv1 -> CONVBLOCK -> IDBLOCK * 2 // conv2_x -> CONVBLOCK -> IDBLOCK * 3 // conv3_x -> CONVBLOCK -> IDBLOCK * 5 // conv4_x -> CONVBLOCK -> IDBLOCK * 2 // conv5_x -> AVGPOOL -> TOPLAYER Resnet101: CONV2D -> BATCHNORM -> RELU -> MAXPOOL // conv1 -> CONVBLOCK -> IDBLOCK * 2 // conv2_x -> CONVBLOCK -> IDBLOCK * 3 // conv3_x -> CONVBLOCK -> IDBLOCK * 22 // conv4_x -> CONVBLOCK -> IDBLOCK * 2 // conv5_x -> AVGPOOL -> TOPLAYER Resnet152: CONV2D -> BATCHNORM -> RELU -> MAXPOOL // conv1 -> CONVBLOCK -> IDBLOCK * 2 // conv2_x -> CONVBLOCK -> IDBLOCK * 7 // conv3_x -> CONVBLOCK -> IDBLOCK * 35 // conv4_x -> CONVBLOCK -> IDBLOCK * 2 // conv5_x -> AVGPOOL -> TOPLAYER """ # get layers (layer1 is always the same so no need to provide) layer2, layer3, layer4, layer5 = layers # convert input shape into tensor X_input = Input(input_shape) # zero-padding X = ZeroPadding2D((3, 3))(X_input) # conv1 X = Conv2D( filters = 64, kernel_size = (7, 7), strides = (2, 2), name = "conv1", kernel_initializer = "glorot_uniform", )(X) X = BatchNormalization(axis = 3, name = "bn_conv1")(X) X = Activation("relu")(X) X = MaxPooling2D((3, 3), strides = (2, 2))(X) # conv2_x X = make_layer(X, layers = layer2, kernel_size = 3, filters = [64, 64, 256], stride = 1, stage_no = 2) # conv3_x X = make_layer(X, layers = layer3, kernel_size = 3, filters = [128, 128, 512], stride = 2, stage_no = 3) # conv4_x X = make_layer(X, layers = layer4, kernel_size = 3, filters = [256, 256, 1024], stride = 2, stage_no = 4) # conv5_x X = make_layer(X, layers = layer5, kernel_size = 3, filters = [512, 512, 2048], stride = 1, stage_no = 5) # average pooling X = AveragePooling2D((2, 2), name = "avg_pool")(X) # output layer X = Flatten()(X) X = Dense( classes, activation = "softmax", name="fc" + str(classes), kernel_initializer = "glorot_uniform" )(X) model = Model(inputs = X_input, outputs = X, name = name) return model
Implementation of the popular ResNet architecture. Arguments: name -- name of the architecture layers -- number of blocks per layer input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras Model Architecture: Resnet50: CONV2D -> BATCHNORM -> RELU -> MAXPOOL // conv1 -> CONVBLOCK -> IDBLOCK * 2 // conv2_x -> CONVBLOCK -> IDBLOCK * 3 // conv3_x -> CONVBLOCK -> IDBLOCK * 5 // conv4_x -> CONVBLOCK -> IDBLOCK * 2 // conv5_x -> AVGPOOL -> TOPLAYER Resnet101: CONV2D -> BATCHNORM -> RELU -> MAXPOOL // conv1 -> CONVBLOCK -> IDBLOCK * 2 // conv2_x -> CONVBLOCK -> IDBLOCK * 3 // conv3_x -> CONVBLOCK -> IDBLOCK * 22 // conv4_x -> CONVBLOCK -> IDBLOCK * 2 // conv5_x -> AVGPOOL -> TOPLAYER Resnet152: CONV2D -> BATCHNORM -> RELU -> MAXPOOL // conv1 -> CONVBLOCK -> IDBLOCK * 2 // conv2_x -> CONVBLOCK -> IDBLOCK * 7 // conv3_x -> CONVBLOCK -> IDBLOCK * 35 // conv4_x -> CONVBLOCK -> IDBLOCK * 2 // conv5_x -> AVGPOOL -> TOPLAYER
ResNet
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/ResNet/resnet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/ResNet/resnet.py
MIT
def make_layer(X: tf.Tensor, layers: int, kernel_size: int, filters: typing.List[int], stride: int, stage_no: int) -> tf.Tensor: """ Method to create one conv-identity layer for ResNet. Arguments: X -- input tensor layers -- number of blocks per layer kernel_size -- size of the kernel for the block filters -- number of filters/channels stride -- number of stride for downsampling the input stage_no -- stage number just to name the layer Returns: X -- output tensor """ # create convolution block X = block( X, kernel_size = kernel_size, filters = filters, stage_no = stage_no, block_name = "a", is_conv_layer = True, stride = stride ) # create identity block block_name_ordinal = ord("b") for _ in range(layers - 1): X = block( X, kernel_size = kernel_size, filters = filters, stage_no = stage_no, block_name = chr(block_name_ordinal) ) block_name_ordinal += 1 return X
Method to create one conv-identity layer for ResNet. Arguments: X -- input tensor layers -- number of blocks per layer kernel_size -- size of the kernel for the block filters -- number of filters/channels stride -- number of stride for downsampling the input stage_no -- stage number just to name the layer Returns: X -- output tensor
make_layer
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/ResNet/resnet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/ResNet/resnet.py
MIT
def VGGNet( name: str, architecture: typing.List[ typing.Union[int, str] ], input_shape: typing.Tuple[int], classes: int = 1000 ) -> Model: """ Implementation of the VGGNet architecture. Arguments: name -- name of the architecture architecture -- number of output channel per convolution layers in VGGNet input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras """ # convert input shape into tensor X_input = Input(input_shape) # make convolution layers X = make_conv_layer(X_input, architecture) # flatten the output and make fully connected layers X = Flatten()(X) X = make_dense_layer(X, 4096) X = make_dense_layer(X, 4096) # classification layer X = Dense(units = classes, activation = "softmax")(X) model = Model(inputs = X_input, outputs = X, name = name) return model
Implementation of the VGGNet architecture. Arguments: name -- name of the architecture architecture -- number of output channel per convolution layers in VGGNet input_shape -- shape of the images of the dataset classes -- integer, number of classes Returns: model -- a Model() instance in Keras
VGGNet
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/VGGNet/vggnet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/VGGNet/vggnet.py
MIT
def make_conv_layer( X: tf.Tensor, architecture: typing.List[ typing.Union[int, str] ], activation: str = 'relu' ) -> tf.Tensor: """ Method to create convolution layers for VGGNet. In VGGNet - Kernal is always 3x3 for conv-layer with padding 1 and stride 1. - 2x2 kernel for max pooling with stride of 2. Arguments: X -- input tensor architecture -- number of output channel per convolution layers in VGGNet activation -- type of activation method Returns: X -- output tensor """ for output in architecture: # convolution layer if type(output) == int: out_channels = output X = Conv2D( filters = out_channels, kernel_size = (3, 3), strides = (1, 1), padding = "same" )(X) X = BatchNormalization()(X) X = Activation(activation)(X) # relu activation is added (by default activation) so that all the # negative values are not passed to the next layer # max-pooling layer else: X = MaxPooling2D( pool_size = (2, 2), strides = (2, 2) )(X) return X
Method to create convolution layers for VGGNet. In VGGNet - Kernal is always 3x3 for conv-layer with padding 1 and stride 1. - 2x2 kernel for max pooling with stride of 2. Arguments: X -- input tensor architecture -- number of output channel per convolution layers in VGGNet activation -- type of activation method Returns: X -- output tensor
make_conv_layer
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/VGGNet/vggnet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/VGGNet/vggnet.py
MIT
def make_dense_layer(X: tf.Tensor, output_units: int, dropout = 0.5, activation = 'relu') -> tf.Tensor: """ Method to create dense layer for VGGNet. Arguments: X -- input tensor output_units -- output tensor size dropout -- dropout value for regularization activation -- type of activation method Returns: X -- input tensor """ X = Dense(units = output_units)(X) X = BatchNormalization()(X) X = Activation(activation)(X) X = Dropout(dropout)(X) return X
Method to create dense layer for VGGNet. Arguments: X -- input tensor output_units -- output tensor size dropout -- dropout value for regularization activation -- type of activation method Returns: X -- input tensor
make_dense_layer
python
aladdinpersson/Machine-Learning-Collection
ML/TensorFlow/CNN_architectures/VGGNet/vggnet.py
https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/TensorFlow/CNN_architectures/VGGNet/vggnet.py
MIT
def poisson_disc_sample(array_radius, pad_radius, candidates=100, d=2, seed=None): """Find positions using poisson-disc sampling.""" # See http://bost.ocks.org/mike/algorithms/ rng = np.random.default_rng(seed) uniform = rng.uniform randint = rng.integers # Cache the results key = array_radius, pad_radius, seed if key in XY_CACHE: return XY_CACHE[key] # Start at a fixed point we know will work start = np.zeros(d) samples = [start] queue = [start] while queue: # Pick a sample to expand from s_idx = randint(len(queue)) s = queue[s_idx] for i in range(candidates): # Generate a candidate from this sample coords = uniform(s - 2 * pad_radius, s + 2 * pad_radius, d) # Check the three conditions to accept the candidate in_array = np.sqrt(np.sum(coords ** 2)) < array_radius in_ring = np.all(distance.cdist(samples, [coords]) > pad_radius) if in_array and in_ring: # Accept the candidate samples.append(coords) queue.append(coords) break if (i + 1) == candidates: # We've exhausted the particular sample queue.pop(s_idx) samples = np.array(samples) XY_CACHE[key] = samples return samples
Find positions using poisson-disc sampling.
poisson_disc_sample
python
mwaskom/seaborn
doc/tools/generate_logos.py
https://github.com/mwaskom/seaborn/blob/master/doc/tools/generate_logos.py
BSD-3-Clause
def strip_output(nb): """ Strip the outputs, execution count/prompt number and miscellaneous metadata from a notebook object, unless specified to keep either the outputs or counts. """ keys = {'metadata': [], 'cell': {'metadata': ["execution"]}} nb.metadata.pop('signature', None) nb.metadata.pop('widgets', None) for field in keys['metadata']: pop_recursive(nb.metadata, field) if 'NB_KERNEL' in os.environ: nb.metadata['kernelspec']['name'] = os.environ['NB_KERNEL'] nb.metadata['kernelspec']['display_name'] = os.environ['NB_KERNEL'] for cell in nb.cells: if 'outputs' in cell: cell['outputs'] = [] if 'prompt_number' in cell: cell['prompt_number'] = None if 'execution_count' in cell: cell['execution_count'] = None # Always remove this metadata for output_style in ['collapsed', 'scrolled']: if output_style in cell.metadata: cell.metadata[output_style] = False if 'metadata' in cell: for field in ['collapsed', 'scrolled', 'ExecuteTime']: cell.metadata.pop(field, None) for (extra, fields) in keys['cell'].items(): if extra in cell: for field in fields: pop_recursive(getattr(cell, extra), field) return nb
Strip the outputs, execution count/prompt number and miscellaneous metadata from a notebook object, unless specified to keep either the outputs or counts.
strip_output
python
mwaskom/seaborn
doc/tools/nb_to_doc.py
https://github.com/mwaskom/seaborn/blob/master/doc/tools/nb_to_doc.py
BSD-3-Clause
def bootstrap(*args, **kwargs): """Resample one or more arrays with replacement and store aggregate values. Positional arguments are a sequence of arrays to bootstrap along the first axis and pass to a summary function. Keyword arguments: n_boot : int, default=10000 Number of iterations axis : int, default=None Will pass axis to ``func`` as a keyword argument. units : array, default=None Array of sampling unit IDs. When used the bootstrap resamples units and then observations within units instead of individual datapoints. func : string or callable, default="mean" Function to call on the args that are passed in. If string, uses as name of function in the numpy namespace. If nans are present in the data, will try to use nan-aware version of named function. seed : Generator | SeedSequence | RandomState | int | None Seed for the random number generator; useful if you want reproducible resamples. Returns ------- boot_dist: array array of bootstrapped statistic values """ # Ensure list of arrays are same length if len(np.unique(list(map(len, args)))) > 1: raise ValueError("All input arrays must have the same length") n = len(args[0]) # Default keyword arguments n_boot = kwargs.get("n_boot", 10000) func = kwargs.get("func", "mean") axis = kwargs.get("axis", None) units = kwargs.get("units", None) random_seed = kwargs.get("random_seed", None) if random_seed is not None: msg = "`random_seed` has been renamed to `seed` and will be removed" warnings.warn(msg) seed = kwargs.get("seed", random_seed) if axis is None: func_kwargs = dict() else: func_kwargs = dict(axis=axis) # Initialize the resampler if isinstance(seed, np.random.RandomState): rng = seed else: rng = np.random.default_rng(seed) # Coerce to arrays args = list(map(np.asarray, args)) if units is not None: units = np.asarray(units) if isinstance(func, str): # Allow named numpy functions f = getattr(np, func) # Try to use nan-aware version of function if necessary missing_data = np.isnan(np.sum(np.column_stack(args))) if missing_data and not func.startswith("nan"): nanf = getattr(np, f"nan{func}", None) if nanf is None: msg = f"Data contain nans but no nan-aware version of `{func}` found" warnings.warn(msg, UserWarning) else: f = nanf else: f = func # Handle numpy changes try: integers = rng.integers except AttributeError: integers = rng.randint # Do the bootstrap if units is not None: return _structured_bootstrap(args, n_boot, units, f, func_kwargs, integers) boot_dist = [] for i in range(int(n_boot)): resampler = integers(0, n, n, dtype=np.intp) # intp is indexing dtype sample = [a.take(resampler, axis=0) for a in args] boot_dist.append(f(*sample, **func_kwargs)) return np.array(boot_dist)
Resample one or more arrays with replacement and store aggregate values. Positional arguments are a sequence of arrays to bootstrap along the first axis and pass to a summary function. Keyword arguments: n_boot : int, default=10000 Number of iterations axis : int, default=None Will pass axis to ``func`` as a keyword argument. units : array, default=None Array of sampling unit IDs. When used the bootstrap resamples units and then observations within units instead of individual datapoints. func : string or callable, default="mean" Function to call on the args that are passed in. If string, uses as name of function in the numpy namespace. If nans are present in the data, will try to use nan-aware version of named function. seed : Generator | SeedSequence | RandomState | int | None Seed for the random number generator; useful if you want reproducible resamples. Returns ------- boot_dist: array array of bootstrapped statistic values
bootstrap
python
mwaskom/seaborn
seaborn/algorithms.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/algorithms.py
BSD-3-Clause
def set(self, **kwargs): """Set attributes on each subplot Axes.""" for ax in self.axes.flat: if ax is not None: # Handle removed axes ax.set(**kwargs) return self
Set attributes on each subplot Axes.
set
python
mwaskom/seaborn
seaborn/axisgrid.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py
BSD-3-Clause
def savefig(self, *args, **kwargs): """ Save an image of the plot. This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches="tight" by default. Parameters are passed through to the matplotlib function. """ kwargs = kwargs.copy() kwargs.setdefault("bbox_inches", "tight") self.figure.savefig(*args, **kwargs)
Save an image of the plot. This wraps :meth:`matplotlib.figure.Figure.savefig`, using bbox_inches="tight" by default. Parameters are passed through to the matplotlib function.
savefig
python
mwaskom/seaborn
seaborn/axisgrid.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py
BSD-3-Clause
def tight_layout(self, *args, **kwargs): """Call fig.tight_layout within rect that exclude the legend.""" kwargs = kwargs.copy() kwargs.setdefault("rect", self._tight_layout_rect) if self._tight_layout_pad is not None: kwargs.setdefault("pad", self._tight_layout_pad) self._figure.tight_layout(*args, **kwargs) return self
Call fig.tight_layout within rect that exclude the legend.
tight_layout
python
mwaskom/seaborn
seaborn/axisgrid.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py
BSD-3-Clause
def add_legend(self, legend_data=None, title=None, label_order=None, adjust_subtitles=False, **kwargs): """Draw a legend, maybe placing it outside axes and resizing the figure. Parameters ---------- legend_data : dict Dictionary mapping label names (or two-element tuples where the second element is a label name) to matplotlib artist handles. The default reads from ``self._legend_data``. title : string Title for the legend. The default reads from ``self._hue_var``. label_order : list of labels The order that the legend entries should appear in. The default reads from ``self.hue_names``. adjust_subtitles : bool If True, modify entries with invisible artists to left-align the labels and set the font size to that of a title. kwargs : key, value pairings Other keyword arguments are passed to the underlying legend methods on the Figure or Axes object. Returns ------- self : Grid instance Returns self for easy chaining. """ # Find the data for the legend if legend_data is None: legend_data = self._legend_data if label_order is None: if self.hue_names is None: label_order = list(legend_data.keys()) else: label_order = list(map(utils.to_utf8, self.hue_names)) blank_handle = mpl.patches.Patch(alpha=0, linewidth=0) handles = [legend_data.get(lab, blank_handle) for lab in label_order] title = self._hue_var if title is None else title title_size = mpl.rcParams["legend.title_fontsize"] # Unpack nested labels from a hierarchical legend labels = [] for entry in label_order: if isinstance(entry, tuple): _, label = entry else: label = entry labels.append(label) # Set default legend kwargs kwargs.setdefault("scatterpoints", 1) if self._legend_out: kwargs.setdefault("frameon", False) kwargs.setdefault("loc", "center right") # Draw a full-figure legend outside the grid figlegend = self._figure.legend(handles, labels, **kwargs) self._legend = figlegend figlegend.set_title(title, prop={"size": title_size}) if adjust_subtitles: adjust_legend_subtitles(figlegend) # Draw the plot to set the bounding boxes correctly _draw_figure(self._figure) # Calculate and set the new width of the figure so the legend fits legend_width = figlegend.get_window_extent().width / self._figure.dpi fig_width, fig_height = self._figure.get_size_inches() self._figure.set_size_inches(fig_width + legend_width, fig_height) # Draw the plot again to get the new transformations _draw_figure(self._figure) # Now calculate how much space we need on the right side legend_width = figlegend.get_window_extent().width / self._figure.dpi space_needed = legend_width / (fig_width + legend_width) margin = .04 if self._margin_titles else .01 self._space_needed = margin + space_needed right = 1 - self._space_needed # Place the subplot axes to give space for the legend self._figure.subplots_adjust(right=right) self._tight_layout_rect[2] = right else: # Draw a legend in the first axis ax = self.axes.flat[0] kwargs.setdefault("loc", "best") leg = ax.legend(handles, labels, **kwargs) leg.set_title(title, prop={"size": title_size}) self._legend = leg if adjust_subtitles: adjust_legend_subtitles(leg) return self
Draw a legend, maybe placing it outside axes and resizing the figure. Parameters ---------- legend_data : dict Dictionary mapping label names (or two-element tuples where the second element is a label name) to matplotlib artist handles. The default reads from ``self._legend_data``. title : string Title for the legend. The default reads from ``self._hue_var``. label_order : list of labels The order that the legend entries should appear in. The default reads from ``self.hue_names``. adjust_subtitles : bool If True, modify entries with invisible artists to left-align the labels and set the font size to that of a title. kwargs : key, value pairings Other keyword arguments are passed to the underlying legend methods on the Figure or Axes object. Returns ------- self : Grid instance Returns self for easy chaining.
add_legend
python
mwaskom/seaborn
seaborn/axisgrid.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py
BSD-3-Clause
def _update_legend_data(self, ax): """Extract the legend data from an axes object and save it.""" data = {} # Get data directly from the legend, which is necessary # for newer functions that don't add labeled proxy artists if ax.legend_ is not None and self._extract_legend_handles: handles = get_legend_handles(ax.legend_) labels = [t.get_text() for t in ax.legend_.texts] data.update({label: handle for handle, label in zip(handles, labels)}) handles, labels = ax.get_legend_handles_labels() data.update({label: handle for handle, label in zip(handles, labels)}) self._legend_data.update(data) # Now clear the legend ax.legend_ = None
Extract the legend data from an axes object and save it.
_update_legend_data
python
mwaskom/seaborn
seaborn/axisgrid.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py
BSD-3-Clause
def _get_palette(self, data, hue, hue_order, palette): """Get a list of colors for the hue variable.""" if hue is None: palette = color_palette(n_colors=1) else: hue_names = categorical_order(data[hue], hue_order) n_colors = len(hue_names) # By default use either the current color palette or HUSL if palette is None: current_palette = utils.get_color_cycle() if n_colors > len(current_palette): colors = color_palette("husl", n_colors) else: colors = color_palette(n_colors=n_colors) # Allow for palette to map from hue variable names elif isinstance(palette, dict): color_names = [palette[h] for h in hue_names] colors = color_palette(color_names, n_colors) # Otherwise act as if we just got a list of colors else: colors = color_palette(palette, n_colors) palette = color_palette(colors, n_colors) return palette
Get a list of colors for the hue variable.
_get_palette
python
mwaskom/seaborn
seaborn/axisgrid.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py
BSD-3-Clause
def legend(self): """The :class:`matplotlib.legend.Legend` object, if present.""" try: return self._legend except AttributeError: return None
The :class:`matplotlib.legend.Legend` object, if present.
legend
python
mwaskom/seaborn
seaborn/axisgrid.py
https://github.com/mwaskom/seaborn/blob/master/seaborn/axisgrid.py
BSD-3-Clause