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 class_encoding(): """Creates a set of functions to add a new class, convert a class into an integer, and the integer back to a class.""" class_to_int_map = {} int_to_class_map = None def add_class(c): global int_to_class_map int_to_class_map = None ...
Creates a set of functions to add a new class, convert a class into an integer, and the integer back to a class.
class_encoding
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py
MIT
def to_categorical(y, num_classes=None): """Converts a class vector (integers) to binary class matrix. """ y = np.array(y, dtype='int') input_shape = y.shape if input_shape and input_shape[-1] == 1 and len(input_shape) > 1: input_shape = tuple(input_shape[:-1]) ...
Converts a class vector (integers) to binary class matrix.
to_categorical
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py
MIT
def _iterdump(connection): """ Returns an iterator to the dump of the database in an SQL text format. Used to produce an SQL dump of the database. Useful to save an in-memory database for later restoration. This function should not be called directly but instead called from the Connection method,...
Returns an iterator to the dump of the database in an SQL text format. Used to produce an SQL dump of the database. Useful to save an in-memory database for later restoration. This function should not be called directly but instead called from the Connection method, iterdump().
_iterdump
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/lib/dump.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/lib/dump.py
MIT
def _sqlite_try_max_variable_number(num): """ Tests whether SQLite can handle num variables """ db = sqlite3.connect(':memory:') try: db.cursor().execute( "SELECT 1 IN (" + ",".join(["?"] * num) + ")", ([0] * num) ).fetchall() return num except BaseExcepti...
Tests whether SQLite can handle num variables
_sqlite_try_max_variable_number
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def __new__(cls, *args, **kwargs): """ Returns a concatenated magnitude object, if Magnitude parameters """ if len(args) > 0 and isinstance(args[0], Magnitude): obj = object.__new__(ConcatenatedMagnitude, *args, **kwargs) obj.__init__(*args, **kwargs) else: ob...
Returns a concatenated magnitude object, if Magnitude parameters
__new__
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _db(self, force_new=False): """Returns a cursor to the database. Each thread gets its own cursor. """ identifier = threading.current_thread().ident conn_exists = identifier in self._cursors if not conn_exists or force_new: if self.fd: if os...
Returns a cursor to the database. Each thread gets its own cursor.
_db
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _key_t(self, key): """Transforms a key to lower case depending on case sensitivity. """ if self.case_insensitive and (isinstance(key, str) or isinstance(key, unicode)): return key.lower() return key
Transforms a key to lower case depending on case sensitivity.
_key_t
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _oov_key_t(self, key): """Transforms a key for out-of-vocabulary lookup. """ is_str = isinstance(key, str) or isinstance(key, unicode) if is_str: key = Magnitude.BOW + self._key_t(key) + Magnitude.EOW return is_str, self._key_shrunk_2(key) return is_st...
Transforms a key for out-of-vocabulary lookup.
_oov_key_t
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _oov_english_stem_english_ixes(self, key): """Strips away common English prefixes and suffixes.""" key_lower = key.lower() start_idx = 0 end_idx = 0 for p in Magnitude.ENGLISH_PREFIXES: if key_lower[:len(p)] == p: start_idx = len(p) ...
Strips away common English prefixes and suffixes.
_oov_english_stem_english_ixes
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _oov_stem(self, key): """Strips away common prefixes and suffixes.""" if self.language == 'en': return self._oov_english_stem_english_ixes(key) return key
Strips away common prefixes and suffixes.
_oov_stem
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _db_query_similar_keys_vector(self, key, orig_key, topn=3): """Finds similar keys in the database and gets the mean vector.""" def _sql_escape_single(s): return s.replace("'", "''") def _sql_escape_fts(s): return ''.join("\\" + c if c in Magnitude.FTS_SPECIAL ...
Finds similar keys in the database and gets the mean vector.
_db_query_similar_keys_vector
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _seed(self, val): """Returns a unique seed for val and the (optional) namespace.""" if self._namespace: return xxhash.xxh32(self._namespace + Magnitude.RARE_CHAR + val.encode('utf-8')).intdigest() else: return xxhash.xxh32(val.encode('u...
Returns a unique seed for val and the (optional) namespace.
_seed
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _out_of_vocab_vector(self, key): """Generates a random vector based on the hash of the key.""" orig_key = key is_str, key = self._oov_key_t(key) if not is_str: seed = self._seed(type(key).__name__) Magnitude.OOV_RNG_LOCK.acquire() np.random.seed(se...
Generates a random vector based on the hash of the key.
_out_of_vocab_vector
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _db_batch_generator(self, params): """ Generates batches of paramaters that respect SQLite's MAX_VARIABLE_NUMBER """ if len(params) <= Magnitude.SQLITE_MAX_VARIABLE_NUMBER: yield params else: it = iter(params) for batch in \ ite...
Generates batches of paramaters that respect SQLite's MAX_VARIABLE_NUMBER
_db_batch_generator
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _db_full_result_to_vec(self, result, put_cache=True): """Converts a full database result to a vector.""" result_key = result[0] if self._query_is_cached(result_key): return (result_key, self.query(result_key)) else: vec = self._db_result_to_vec(result[1:]) ...
Converts a full database result to a vector.
_db_full_result_to_vec
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _vector_for_key(self, key): """Queries the database for a single key.""" result = self._db().execute( """ SELECT * FROM `magnitude` WHERE key = ? ORDER BY key = ? COLLATE BINARY DESC LIMIT 1;""", ...
Queries the database for a single key.
_vector_for_key
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _vectors_for_keys(self, keys): """Queries the database for multiple keys.""" unseen_keys = tuple(key for key in keys if not self._query_is_cached(key)) unseen_keys_map = {} if len(unseen_keys) > 0: unseen_keys_map = {self._key_t(k): i for i, k ...
Queries the database for multiple keys.
_vectors_for_keys
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _key_for_index(self, index, return_vector=True): """Queries the database the key at a single index.""" columns = "key" if return_vector: columns = "*" result = self._db().execute( """ SELECT """ + columns + """ FROM `magnitude` ...
Queries the database the key at a single index.
_key_for_index
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _keys_for_indices(self, indices, return_vector=True): """Queries the database for the keys of multiple indices.""" unseen_indices = tuple(int(index + 1) for index in indices if self._key_for_index_cached._cache.get(((index,), # noqa ...
Queries the database for the keys of multiple indices.
_keys_for_indices
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def query(self, q, pad_to_length=None, pad_left=None, truncate_left=None): """Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys. """ pad_to_length = pad_to_length or self.pad_to_length pad_left = pad_left or self.pad_left...
Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys.
query
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def index(self, q, return_vector=True): """Gets a key for an index or multiple indices.""" if isinstance(q, list) or isinstance(q, tuple): return self._keys_for_indices(q, return_vector=return_vector) else: return self._key_for_index_cached(q, return_vector=return_vector)
Gets a key for an index or multiple indices.
index
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _query_numpy(self, key): """Returns the query for a key, forcibly converting the resulting vector to a numpy array. """ key_is_ndarray = isinstance(key, np.ndarray) key_is_list = isinstance(key, list) key_len_ge_0 = key_is_list and len(key) > 0 key_0_is_number...
Returns the query for a key, forcibly converting the resulting vector to a numpy array.
_query_numpy
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _query_is_cached(self, key): """Checks if the query been cached by Magnitude.""" return ((self._vector_for_key_cached._cache.get((key,)) is not None) or ( # noqa self._out_of_vocab_vector_cached._cache.get((key,)) is not None))
Checks if the query been cached by Magnitude.
_query_is_cached
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def distance(self, key, q): """Calculates the distance from key to the key(s) in q.""" a = self._query_numpy(key) if not isinstance(q, list): b = self._query_numpy(q) return np.linalg.norm(a - b) else: return [np.linalg.norm(a - self._query_numpy(b)) f...
Calculates the distance from key to the key(s) in q.
distance
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def similarity(self, key, q): """Calculates the similarity from key to the key(s) in q.""" a = self._query_numpy(key) if not isinstance(q, list): b = self._query_numpy(q) return np.inner(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) else: bs = [self....
Calculates the similarity from key to the key(s) in q.
similarity
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def most_similar_to_given(self, key, q): """Calculates the most similar key in q to key.""" distances = self.distance(key, q) min_index, _ = min(enumerate(distances), key=operator.itemgetter(1)) return q[min_index]
Calculates the most similar key in q to key.
most_similar_to_given
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def doesnt_match(self, q): """Given a set of keys, figures out which key doesn't match the rest. """ mean_vector = np.mean(self._query_numpy([[sq] for sq in q]), axis=0) mean_unit_vector = mean_vector / np.linalg.norm(mean_vector) distances = [np.linalg.norm(mean_unit_vec...
Given a set of keys, figures out which key doesn't match the rest.
doesnt_match
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _db_query_similarity( self, positive, negative, min_similarity=None, topn=10, exclude_keys=set(), return_similarities=False, method='distance', effort=1.0): """Runs a database query to find vectors cl...
Runs a database query to find vectors close to vector.
_db_query_similarity
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def most_similar(self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True): """Finds the topn most similar vectors under or equal to max distance. """ positive, negative = self._handle_pos_neg_args(positive, negative) return self._...
Finds the topn most similar vectors under or equal to max distance.
most_similar
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def most_similar_cosmul(self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True): """Finds the topn most similar vectors under or equal to max distance using 3CosMul: [Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618) """...
Finds the topn most similar vectors under or equal to max distance using 3CosMul: [Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618)
most_similar_cosmul
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def most_similar_approx( self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True, effort=1.0): """Approximates the topn most similar vectors under or equal to max distance using Annoy: ...
Approximates the topn most similar vectors under or equal to max distance using Annoy: https://github.com/spotify/annoy
most_similar_approx
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def closer_than(self, key, q, topn=None): """Finds all keys closer to key than q is to key.""" epsilon = (10.0 / 10**6) min_similarity = self.similarity(key, q) + epsilon return self.most_similar(key, topn=topn, min_similarity=min_similarity, return_simi...
Finds all keys closer to key than q is to key.
closer_than
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def get_vectors_mmap(self): """Gets a numpy.memmap of all vectors, blocks if it is still being built. """ if self._all_vectors is None: while True: if not self.setup_for_mmap: self._setup_for_mmap() try: ...
Gets a numpy.memmap of all vectors, blocks if it is still being built.
get_vectors_mmap
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def get_approx_index_chunks(self): """Gets decompressed chunks of the AnnoyIndex of the vectors from the database.""" try: db = self._db(force_new=True) with lz4.frame.LZ4FrameDecompressor() as decompressor: chunks = db.execute( """ ...
Gets decompressed chunks of the AnnoyIndex of the vectors from the database.
get_approx_index_chunks
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def get_approx_index(self): """Gets an AnnoyIndex of the vectors from the database.""" chunks = self.get_approx_index_chunks() if self._approx_index is None: while True: if not self.setup_for_mmap: self._setup_for_mmap() try: ...
Gets an AnnoyIndex of the vectors from the database.
get_approx_index
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _iter(self, put_cache): """Yields keys and vectors for all vectors in the store.""" try: db = self._db(force_new=True) results = db.execute( """ SELECT * FROM `magnitude` """) for result in re...
Yields keys and vectors for all vectors in the store.
_iter
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def __getitem__(self, q): """Performs the index method when indexed.""" if isinstance(q, slice): return self.index(list(range(*q.indices(self.length))), return_vector=True) else: return self.index(q, return_vector=True)
Performs the index method when indexed.
__getitem__
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _take(self, q, multikey, i): """Selects only the i'th element from the inner-most axis and reduces the dimensions of the tensor q by 1. """ if multikey == -1: return q else: cut = np.take(q, [i], axis=multikey) result = np.reshape(cut, np.s...
Selects only the i'th element from the inner-most axis and reduces the dimensions of the tensor q by 1.
_take
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _hstack(self, l, use_numpy): """Horizontally stacks NumPy arrays or Python lists""" if use_numpy: return np.concatenate(l, axis=-1) else: return list(chain.from_iterable(l))
Horizontally stacks NumPy arrays or Python lists
_hstack
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _dstack(self, l, use_numpy): """Depth stacks NumPy arrays or Python lists""" if use_numpy: return np.concatenate(l, axis=-1) else: return [self._hstack((l3[example] for l3 in l), use_numpy=use_numpy) for example in xrange(len(l[0]))] ...
Depth stacks NumPy arrays or Python lists
_dstack
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def query(self, q, pad_to_length=None, pad_left=None, truncate_left=None): """Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys. """ # Check if keys are specified for each concatenated model multikey = -1 if isin...
Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys.
query
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def batchify(X, y, batch_size): # noqa: N803 """ Creates an iterator that chunks `X` and `y` into batches that each contain `batch_size` elements and loops forever""" X_batch_generator = cycle([X[i: i + batch_size] # noqa: N806 for i in xrange(0, len(X), batc...
Creates an iterator that chunks `X` and `y` into batches that each contain `batch_size` elements and loops forever
batchify
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def class_encoding(): """Creates a set of functions to add a new class, convert a class into an integer, and the integer back to a class.""" class_to_int_map = {} int_to_class_map = None def add_class(c): global int_to_class_map int_to_class_map = None ...
Creates a set of functions to add a new class, convert a class into an integer, and the integer back to a class.
class_encoding
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def to_categorical(y, num_classes=None): """Converts a class vector (integers) to binary class matrix. """ y = np.array(y, dtype='int') input_shape = y.shape if input_shape and input_shape[-1] == 1 and len(input_shape) > 1: input_shape = tuple(input_shape[:-1]) ...
Converts a class vector (integers) to binary class matrix.
to_categorical
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src2/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src2/__init__.py
MIT
def _sqlite_try_max_variable_number(num): """ Tests whether SQLite can handle num variables """ db = sqlite3.connect(':memory:') try: db.cursor().execute( "SELECT 1 IN (" + ",".join(["?"] * num) + ")", ([0] * num) ).fetchall() return num except BaseExcepti...
Tests whether SQLite can handle num variables
_sqlite_try_max_variable_number
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def __new__(cls, *args, **kwargs): """ Returns a concatenated magnitude object, if Magnitude parameters """ if len(args) > 0 and isinstance(args[0], Magnitude): obj = object.__new__(ConcatenatedMagnitude, *args, **kwargs) obj.__init__(*args, **kwargs) else: ob...
Returns a concatenated magnitude object, if Magnitude parameters
__new__
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _db(self, force_new=False): """Returns a cursor to the database. Each thread gets its own cursor. """ identifier = threading.current_thread().ident conn_exists = identifier in self._cursors if not conn_exists or force_new: if self.fd: if os...
Returns a cursor to the database. Each thread gets its own cursor.
_db
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _key_t(self, key): """Transforms a key to lower case depending on case sensitivity. """ if self.case_insensitive and (isinstance(key, str) or isinstance(key, unicode)): return key.lower() return key
Transforms a key to lower case depending on case sensitivity.
_key_t
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _oov_key_t(self, key): """Transforms a key for out-of-vocabulary lookup. """ is_str = isinstance(key, str) or isinstance(key, unicode) if is_str: key = Magnitude.BOW + self._key_t(key) + Magnitude.EOW return is_str, self._key_shrunk_2(key) return is_st...
Transforms a key for out-of-vocabulary lookup.
_oov_key_t
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _oov_english_stem_english_ixes(self, key): """Strips away common English prefixes and suffixes.""" key_lower = key.lower() start_idx = 0 end_idx = 0 for p in Magnitude.ENGLISH_PREFIXES: if key_lower[:len(p)] == p: start_idx = len(p) ...
Strips away common English prefixes and suffixes.
_oov_english_stem_english_ixes
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _oov_stem(self, key): """Strips away common prefixes and suffixes.""" if self.language == 'en': return self._oov_english_stem_english_ixes(key) return key
Strips away common prefixes and suffixes.
_oov_stem
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _db_query_similar_keys_vector(self, key, orig_key, topn=3): """Finds similar keys in the database and gets the mean vector.""" def _sql_escape_single(s): return s.replace("'", "''") def _sql_escape_fts(s): return ''.join("\\" + c if c in Magnitude.FTS_SPECIAL ...
Finds similar keys in the database and gets the mean vector.
_db_query_similar_keys_vector
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _seed(self, val): """Returns a unique seed for val and the (optional) namespace.""" if self._namespace: return xxhash.xxh32(self._namespace + Magnitude.RARE_CHAR + val.encode('utf-8')).intdigest() else: return xxhash.xxh32(val.encode('u...
Returns a unique seed for val and the (optional) namespace.
_seed
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _out_of_vocab_vector(self, key): """Generates a random vector based on the hash of the key.""" orig_key = key is_str, key = self._oov_key_t(key) if not is_str: seed = self._seed(type(key).__name__) Magnitude.OOV_RNG_LOCK.acquire() np.random.seed(se...
Generates a random vector based on the hash of the key.
_out_of_vocab_vector
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _db_batch_generator(self, params): """ Generates batches of paramaters that respect SQLite's MAX_VARIABLE_NUMBER """ if len(params) <= Magnitude.SQLITE_MAX_VARIABLE_NUMBER: yield params else: it = iter(params) for batch in \ ite...
Generates batches of paramaters that respect SQLite's MAX_VARIABLE_NUMBER
_db_batch_generator
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _db_full_result_to_vec(self, result, put_cache=True): """Converts a full database result to a vector.""" result_key = result[0] if self._query_is_cached(result_key): return (result_key, self.query(result_key)) else: vec = self._db_result_to_vec(result[1:]) ...
Converts a full database result to a vector.
_db_full_result_to_vec
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _vector_for_key(self, key): """Queries the database for a single key.""" result = self._db().execute( """ SELECT * FROM `magnitude` WHERE key = ? ORDER BY key = ? COLLATE BINARY DESC LIMIT 1;""", ...
Queries the database for a single key.
_vector_for_key
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _vectors_for_keys(self, keys): """Queries the database for multiple keys.""" unseen_keys = tuple(key for key in keys if not self._query_is_cached(key)) unseen_keys_map = {} if len(unseen_keys) > 0: unseen_keys_map = {self._key_t(k): i for i, k ...
Queries the database for multiple keys.
_vectors_for_keys
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _key_for_index(self, index, return_vector=True): """Queries the database the key at a single index.""" columns = "key" if return_vector: columns = "*" result = self._db().execute( """ SELECT """ + columns + """ FROM `magnitude` ...
Queries the database the key at a single index.
_key_for_index
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _keys_for_indices(self, indices, return_vector=True): """Queries the database for the keys of multiple indices.""" unseen_indices = tuple(int(index + 1) for index in indices if self._key_for_index_cached._cache.get(((index,), # noqa ...
Queries the database for the keys of multiple indices.
_keys_for_indices
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def query(self, q, pad_to_length=None, pad_left=None, truncate_left=None): """Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys. """ pad_to_length = pad_to_length or self.pad_to_length pad_left = pad_left or self.pad_left...
Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys.
query
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def index(self, q, return_vector=True): """Gets a key for an index or multiple indices.""" if isinstance(q, list) or isinstance(q, tuple): return self._keys_for_indices(q, return_vector=return_vector) else: return self._key_for_index_cached(q, return_vector=return_vector)
Gets a key for an index or multiple indices.
index
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _query_numpy(self, key): """Returns the query for a key, forcibly converting the resulting vector to a numpy array. """ key_is_ndarray = isinstance(key, np.ndarray) key_is_list = isinstance(key, list) key_len_ge_0 = key_is_list and len(key) > 0 key_0_is_number...
Returns the query for a key, forcibly converting the resulting vector to a numpy array.
_query_numpy
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _query_is_cached(self, key): """Checks if the query been cached by Magnitude.""" return ((self._vector_for_key_cached._cache.get((key,)) is not None) or ( # noqa self._out_of_vocab_vector_cached._cache.get((key,)) is not None))
Checks if the query been cached by Magnitude.
_query_is_cached
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def distance(self, key, q): """Calculates the distance from key to the key(s) in q.""" a = self._query_numpy(key) if not isinstance(q, list): b = self._query_numpy(q) return np.linalg.norm(a - b) else: return [np.linalg.norm(a - self._query_numpy(b)) f...
Calculates the distance from key to the key(s) in q.
distance
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def similarity(self, key, q): """Calculates the similarity from key to the key(s) in q.""" a = self._query_numpy(key) if not isinstance(q, list): b = self._query_numpy(q) return np.inner(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) else: bs = [self....
Calculates the similarity from key to the key(s) in q.
similarity
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def most_similar_to_given(self, key, q): """Calculates the most similar key in q to key.""" distances = self.distance(key, q) min_index, _ = min(enumerate(distances), key=operator.itemgetter(1)) return q[min_index]
Calculates the most similar key in q to key.
most_similar_to_given
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def doesnt_match(self, q): """Given a set of keys, figures out which key doesn't match the rest. """ mean_vector = np.mean(self._query_numpy([[sq] for sq in q]), axis=0) mean_unit_vector = mean_vector / np.linalg.norm(mean_vector) distances = [np.linalg.norm(mean_unit_vec...
Given a set of keys, figures out which key doesn't match the rest.
doesnt_match
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _db_query_similarity( self, positive, negative, min_similarity=None, topn=10, exclude_keys=set(), return_similarities=False, method='distance', effort=1.0): """Runs a database query to find vectors cl...
Runs a database query to find vectors close to vector.
_db_query_similarity
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def most_similar(self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True): """Finds the topn most similar vectors under or equal to max distance. """ positive, negative = self._handle_pos_neg_args(positive, negative) return self._...
Finds the topn most similar vectors under or equal to max distance.
most_similar
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def most_similar_cosmul(self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True): """Finds the topn most similar vectors under or equal to max distance using 3CosMul: [Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618) """...
Finds the topn most similar vectors under or equal to max distance using 3CosMul: [Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618)
most_similar_cosmul
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def most_similar_approx( self, positive, negative=[], topn=10, min_similarity=None, return_similarities=True, effort=1.0): """Approximates the topn most similar vectors under or equal to max distance using Annoy: ...
Approximates the topn most similar vectors under or equal to max distance using Annoy: https://github.com/spotify/annoy
most_similar_approx
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def closer_than(self, key, q, topn=None): """Finds all keys closer to key than q is to key.""" epsilon = (10.0 / 10**6) min_similarity = self.similarity(key, q) + epsilon return self.most_similar(key, topn=topn, min_similarity=min_similarity, return_simi...
Finds all keys closer to key than q is to key.
closer_than
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def get_vectors_mmap(self): """Gets a numpy.memmap of all vectors, blocks if it is still being built. """ if self._all_vectors is None: while True: if not self.setup_for_mmap: self._setup_for_mmap() try: ...
Gets a numpy.memmap of all vectors, blocks if it is still being built.
get_vectors_mmap
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def get_approx_index_chunks(self): """Gets decompressed chunks of the AnnoyIndex of the vectors from the database.""" try: db = self._db(force_new=True) with lz4.frame.LZ4FrameDecompressor() as decompressor: chunks = db.execute( """ ...
Gets decompressed chunks of the AnnoyIndex of the vectors from the database.
get_approx_index_chunks
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def get_approx_index(self): """Gets an AnnoyIndex of the vectors from the database.""" chunks = self.get_approx_index_chunks() if self._approx_index is None: while True: if not self.setup_for_mmap: self._setup_for_mmap() try: ...
Gets an AnnoyIndex of the vectors from the database.
get_approx_index
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _iter(self, put_cache): """Yields keys and vectors for all vectors in the store.""" try: db = self._db(force_new=True) results = db.execute( """ SELECT * FROM `magnitude` """) for result in re...
Yields keys and vectors for all vectors in the store.
_iter
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def __getitem__(self, q): """Performs the index method when indexed.""" if isinstance(q, slice): return self.index(list(range(*q.indices(self.length))), return_vector=True) else: return self.index(q, return_vector=True)
Performs the index method when indexed.
__getitem__
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _take(self, q, multikey, i): """Selects only the i'th element from the inner-most axis and reduces the dimensions of the tensor q by 1. """ if multikey == -1: return q else: cut = np.take(q, [i], axis=multikey) result = np.reshape(cut, np.s...
Selects only the i'th element from the inner-most axis and reduces the dimensions of the tensor q by 1.
_take
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _hstack(self, l, use_numpy): """Horizontally stacks NumPy arrays or Python lists""" if use_numpy: return np.concatenate(l, axis=-1) else: return list(chain.from_iterable(l))
Horizontally stacks NumPy arrays or Python lists
_hstack
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def _dstack(self, l, use_numpy): """Depth stacks NumPy arrays or Python lists""" if use_numpy: return np.concatenate(l, axis=-1) else: return [self._hstack((l3[example] for l3 in l), use_numpy=use_numpy) for example in xrange(len(l[0]))] ...
Depth stacks NumPy arrays or Python lists
_dstack
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def query(self, q, pad_to_length=None, pad_left=None, truncate_left=None): """Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys. """ # Check if keys are specified for each concatenated model multikey = -1 if isin...
Handles a query of keys which could be a single key, a 1-D list of keys, or a 2-D list of keys.
query
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def batchify(X, y, batch_size): # noqa: N803 """ Creates an iterator that chunks `X` and `y` into batches that each contain `batch_size` elements and loops forever""" X_batch_generator = cycle([X[i: i + batch_size] # noqa: N806 for i in xrange(0, len(X), batc...
Creates an iterator that chunks `X` and `y` into batches that each contain `batch_size` elements and loops forever
batchify
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def class_encoding(): """Creates a set of functions to add a new class, convert a class into an integer, and the integer back to a class.""" class_to_int_map = {} int_to_class_map = None def add_class(c): global int_to_class_map int_to_class_map = None ...
Creates a set of functions to add a new class, convert a class into an integer, and the integer back to a class.
class_encoding
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def to_categorical(y, num_classes=None): """Converts a class vector (integers) to binary class matrix. """ y = np.array(y, dtype='int') input_shape = y.shape if input_shape and input_shape[-1] == 1 and len(input_shape) > 1: input_shape = tuple(input_shape[:-1]) ...
Converts a class vector (integers) to binary class matrix.
to_categorical
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/src3/__init__.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/src3/__init__.py
MIT
def get_size(obj, seen=None): """Recursively finds size of objects Source: https://goshippo.com/blog/measure-real-size-any-python-object/ """ size = sys.getsizeof(obj) if seen is None: seen = set() obj_id = id(obj) if obj_id in seen: return 0 # Important mark as seen *...
Recursively finds size of objects Source: https://goshippo.com/blog/measure-real-size-any-python-object/
get_size
python
plasticityai/magnitude
tests/benchmark.py
https://github.com/plasticityai/magnitude/blob/master/tests/benchmark.py
MIT
def get_channel_dim(input_tensor, data_format='INVALID'): """Returns the number of channels in the input tensor.""" shape = input_tensor.get_shape().as_list() assert data_format != 'INVALID' assert len(shape) == 4 if data_format == 'NHWC': return int(shape[3]) elif data_format == 'NCHW': return int(...
Returns the number of channels in the input tensor.
get_channel_dim
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds a block for phoenix. Args: input_tensors: A list of input tensors. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: T...
Builds a block for phoenix. Args: input_tensors: A list of input tensors. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: The training HParams. Returns: output_tensors: A list of the output tensors....
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def is_input_order_important(self): """Is the order of the entries in the input tensor important. Returns: A bool specifying if the order of the entries in the input is important. Examples where the order is important: Input for a cnn layer. (e.g., pixels an image). Examples when the order is...
Is the order of the entries in the input tensor important. Returns: A bool specifying if the order of the entries in the input is important. Examples where the order is important: Input for a cnn layer. (e.g., pixels an image). Examples when the order is not important: Input for a dense lay...
is_input_order_important
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def __init__(self, max_output_size=100, max_number_of_parameters=None, apply_batch_norm=False, residual_connection_type=None, **kwargs): """Initializes a new FullyConnectedBlock instance. Args: max_output_size: The maximum number ...
Initializes a new FullyConnectedBlock instance. Args: max_output_size: The maximum number of output neurons. max_number_of_parameters: The maximum number of parameters allowed. apply_batch_norm: Whether to apply batch normalization to the layer. residual_connection_type: The ResidualConnect...
__init__
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def _add_residual_connection(self, input_tensor, output_tensor): """Creates the residual connection between the input and the output.""" if self._residual_connection_type == ResidualConnectionType.NONE: return output_tensor in_shape = input_tensor.shape[-1] out_shape = output_tensor.shape[-1] ...
Creates the residual connection between the input and the output.
_add_residual_connection
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Applies 2d max pooling on the input tensor.""" input_tensor = input_tensors[-1] if input_tensor.get_shape().as_list()[2] < self._pool_size: return input_tensors max_pool = tf.keras.layers.MaxPool2D( pool_siz...
Applies 2d max pooling on the input tensor.
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Returns a ReLU activated output of a residual unit with 2 sub layers.""" input_tensor = input_tensors[-1] net1 = tf.keras.layers.Conv2D( get_channel_dim(input_tensor), kernel_size=self._kernel_size, nam...
Returns a ReLU activated output of a residual unit with 2 sub layers.
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Custom (wide) convolution block with some pooling.""" # Guard so that we won't have zero channels input_tensor = input_tensors[-1] if get_channel_dim(input_tensor) < 6: return input_tensors reduced = tf.keras.la...
Custom (wide) convolution block with some pooling.
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds a basic rnn block. Args: input_tensors: A tf.Tensor with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: ...
Builds a basic rnn block. Args: input_tensors: A tf.Tensor with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: hparams for the build. Returns: output tensor
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds a one dimensional convolutional block. Args: input_tensors: A tf.Tensor with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the ba...
Builds a one dimensional convolutional block. Args: input_tensors: A tf.Tensor with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: hparams for the build. Returns: output tensor
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds as LSTM block. Args: input_tensors: A list of tf.Tensors with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hpar...
Builds as LSTM block. Args: input_tensors: A list of tf.Tensors with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: hparams for the build. Returns: output tensor
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds as LSTM block. Args: input_tensors: A list of tf.Tensors with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hpar...
Builds as LSTM block. Args: input_tensors: A list of tf.Tensors with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: hparams for the build. Returns: output tensor
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def search_space(blocks_to_use=None): """Returns required search space for all blocks.""" search_space = ms_hparameters.Hyperparameters() for block_type in BlockType: if block_type == BlockType.EMPTY_BLOCK: continue if blocks_to_use is None or block_type.name in blocks_to_use: ta...
Returns required search space for all blocks.
search_space
python
google/model_search
model_search/block_builder.py
https://github.com/google/model_search/blob/master/model_search/block_builder.py
Apache-2.0
def replay_is_training_a_tower(self, my_id): """Returns True if we are training a new tower in a replay run. Example: 1. In adaptive ensembling, every trial is training one new tower, so the return value is always True. 2. In a non-adaptive ensembling, every trial except the last one is ...
Returns True if we are training a new tower in a replay run. Example: 1. In adaptive ensembling, every trial is training one new tower, so the return value is always True. 2. In a non-adaptive ensembling, every trial except the last one is training a new tower, whereas the last trial just e...
replay_is_training_a_tower
python
google/model_search
model_search/controller.py
https://github.com/google/model_search/blob/master/model_search/controller.py
Apache-2.0