code
stringlengths
17
6.64M
def plot_heatmap(model_dir, name, features, labels, num_classes): 'Plot heatmap of cosine simliarity for all features. ' (features_sort, _) = utils.sort_dataset(features, labels, classes=num_classes, stack=False) features_sort_ = np.vstack(features_sort) sim_mat = np.abs((features_sort_ @ features_sor...
def plot_transform(model_dir, inputs, outputs, name): (fig, ax) = plt.subplots(ncols=2) inputs = inputs.permute(1, 2, 0) outputs = outputs.permute(1, 2, 0) outputs = ((outputs - outputs.min()) / (outputs.max() - outputs.min())) ax[0].imshow(inputs) ax[0].set_title('inputs') ax[1].imshow(ou...
def plot_channel_image(model_dir, features, name): def normalize(x): out = (x - x.min()) out = (out / (out.max() - out.min())) return out (fig, ax) = plt.subplots() ax.imshow(normalize(features), cmap='gray') save_dir = os.path.join(model_dir, 'figures', 'images') os.maked...
def plot_nearest_image(model_dir, image, nearest_images, values, name, grid_size=(4, 4)): (fig, ax) = plt.subplots(*grid_size, figsize=(10, 10)) idx = 1 for i in range(grid_size[0]): for j in range(grid_size[1]): if ((i == 0) and (j == 0)): ax[(i, j)].imshow(image) ...
def plot_image(model_dir, image, name): (fig, ax) = plt.subplots(1, 1, figsize=(10, 10)) if (image.shape[2] == 1): ax.imshow(image, cmap='gray') else: ax.imshow(image) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout() save_dir = os.path.join(model_dir, 'figures', 'imag...
def save_image(image, save_path): (fig, ax) = plt.subplots(1, 1, figsize=(10, 10)) if (image.shape[2] == 1): ax.imshow(image, cmap='gray') else: ax.imshow(image) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout() fig.savefig(save_path) print(f'Plot saved to: {save_p...
class ReduLayer(nn.Module): def __init__(self): super(ReduLayer, self).__init__() def __name__(self): return 'ReduNet' def forward(self, Z): raise NotImplementedError def zero(self): state_dict = self.state_dict() state_dict['E.weight'] = torch.zeros_like(se...
def ReduNetVector(num_classes, num_layers, d, eta, eps, lmbda): redunet = ReduNet(*[Vector(eta, eps, lmbda, num_classes, d) for _ in range(num_layers)]) return redunet
def ReduNet1D(num_classes, num_layers, channels, timesteps, eta, eps, lmbda): redunet = ReduNet(*[Fourier1D(eta, eps, lmbda, num_classes, (channels, timesteps)) for _ in range(num_layers)]) return redunet
def ReduNet2D(num_classes, num_layers, channels, height, width, eta, eps, lmbda): redunet = ReduNet(*[Fourier2D(eta, eps, lmbda, num_classes, (channels, height, width)) for _ in range(num_layers)]) return redunet
class MultichannelWeight(nn.Module): def __init__(self, channels, *dimension, dtype=torch.complex64): super(MultichannelWeight, self).__init__() self.weight = nn.Parameter(torch.randn(channels, channels, *dimension, dtype=dtype)) self.shape = self.weight.shape self.dtype = dtype ...
class Lift(nn.Module): def __init__(self, in_channel, out_channel, kernel_size, init_mode='gaussian1.0', stride=1, trainable=False, relu=True, seed=0): super(Lift, self).__init__() self.in_channel = in_channel self.out_channel = out_channel self.kernel_size = kernel_size s...
class Lift1D(Lift): def __init__(self, in_channel, out_channel, kernel_size, init_mode='gaussian1.0', stride=1, trainable=False, relu=True, seed=0): super(Lift1D, self).__init__(in_channel, out_channel, kernel_size, init_mode, stride, trainable, relu, seed) self.size = (out_channel, in_channel, k...
class Lift2D(Lift): def __init__(self, in_channel, out_channel, kernel_size, init_mode='gaussian1.0', stride=1, trainable=False, relu=True, seed=0): super(Lift2D, self).__init__(in_channel, out_channel, kernel_size, init_mode, stride, trainable, relu, seed) self.size = (out_channel, in_channel, k...
class ReduNet(nn.Sequential): def __init__(self, *modules): super(ReduNet, self).__init__(*modules) self._init_loss() def init(self, inputs, labels): with torch.no_grad(): return self.forward(inputs, labels, init=True, loss=True) def update(self, inputs, labels, tau=...
def sort_dataset(data, labels, classes, stack=False): 'Sort dataset based on classes.\n \n Parameters:\n data (np.ndarray): data array\n labels (np.ndarray): one dimensional array of class labels\n classes (int): number of classes\n stack (bol): combine sorted data into one numpy...
def save_params(model_dir, params, name='params', name_prefix=None): 'Save params to a .json file. Params is a dictionary of parameters.' if name_prefix: model_dir = os.path.join(model_dir, name_prefix) os.makedirs(model_dir, exist_ok=True) path = os.path.join(model_dir, f'{name}.json') wi...
def load_params(model_dir): 'Load params.json file in model directory and return dictionary.' path = os.path.join(model_dir, 'params.json') with open(path, 'r') as f: _dict = json.load(f) return _dict
def update_params(model_dir, dict_): params = load_params(model_dir) for key in dict_.keys(): params[key] = dict_[key] save_params(model_dir, params) return params
def create_csv(model_dir, filename, headers): 'Create .csv file with filename in model_dir, with headers as the first line \n of the csv. ' csv_path = os.path.join(model_dir, f'{filename}.csv') if os.path.exists(csv_path): os.remove(csv_path) with open(csv_path, 'w+') as f: f.write(...
def append_csv(model_dir, filename, entries): 'Save entries to csv. Entries is list of numbers. ' csv_path = os.path.join(model_dir, f'{filename}.csv') assert os.path.exists(csv_path), 'CSV file is missing in project directory.' with open(csv_path, 'a') as f: f.write(('\n' + ','.join(map(str, ...
def save_loss(model_dir, name, loss_dict): save_dir = os.path.join(model_dir, 'loss') os.makedirs(save_dir, exist_ok=True) file_path = os.path.join(save_dir, '{}.csv'.format(name)) pd.DataFrame(loss_dict).to_csv(file_path)
def save_features(model_dir, name, features, labels, layer=None): save_dir = os.path.join(model_dir, 'features') os.makedirs(save_dir, exist_ok=True) np.save(os.path.join(save_dir, f'{name}_features.npy'), features) np.save(os.path.join(save_dir, f'{name}_labels.npy'), labels)
def save_ckpt(model_dir, name, net): 'Save PyTorch checkpoint to model_dir/checkpoints/ directory in model directory. ' os.makedirs(os.path.join(model_dir, 'checkpoints'), exist_ok=True) torch.save(net.state_dict(), os.path.join(model_dir, 'checkpoints', '{}.pt'.format(name)))
def load_ckpt(model_dir, name, net, eval_=True): "Load checkpoint from model directory. Checkpoints should be stored in \n `model_dir/checkpoints/'.\n " ckpt_path = os.path.join(model_dir, 'checkpoints', f'{name}.pt') print('Loading checkpoint: {}'.format(ckpt_path)) state_dict = torch.load(ckpt...
def sample_trunc_beta(a, b, lower, upper): '\n Samples from a truncated beta distribution in log space\n\n Parameters\n ----------\n a, b: float\n Canonical parameters of the beta distribution\n lower, upper: float\n Lower and upper truncations of the beta distribution\n\n Returns\...
def check_MH_criterion(log_labels_given_ps_prev, log_labels_given_ps_new, log_update, log_revert): '\n Checks the Metropolis-Hastings criterion for accepting an MCMC move\n\n Parameters\n ----------\n log_labels_given_ps_prev: float\n log P(\theta \\mid p, A) before the proposed MCMCc move\n ...
def get_log_posterior_layered(N_nodes, layer_ms, layer_Ms, layer_ns, layer_ps): '\n Calculates the log posterior of the layered core-periphery model\n\n Parameters\n ----------\n N_nodes: int\n Number of nodes in the network\n layer_ms: 1D array\n Array counting the number of edges th...
def get_log_posterior_hubspoke(N_nodes, block_ms, block_Ms, block_ns, block_ps): '\n Calculates the log posterior of the hub-and-spoke core-periphery model\n\n Parameters\n ----------\n N_nodes: int\n Number of nodes in the network\n block_ms: 2D array\n Matrix counting the number of ...
def xlogy(x, y): if ((x == 0) and (y == 0)): return 0 elif (y == 0): return ((- 1) * np.inf) elif (y < 0): return else: return (x * np.log(y))
def log_likelihood_layered(layer_ms, layer_Ms, layer_ps): '\n Calculates the log likelihood of the layered core-periphery model.\n\n Parameters\n ----------\n layer_ms: 1D array\n Array counting the number of edges that connect to each layer\n layer_Ms: 1D array\n Array counting the m...
def log_likelihood_hubspoke(block_ms, block_Ms, block_ps): '\n Calculates the log likelihood of the hub-and-spoke core-periphery model.\n\n Parameters\n ----------\n block_ms: 2D array\n Matrix counting the number of edges between and within each block\n block_Ms: 2D array\n Matrix co...
def log_labels_prior_layered(N_nodes, block_ns, n_layers): '\n Calculates the prior on the node labels for the layered modeel\n\n Parameters\n ----------\n N_nodes: int\n The number of nodes in the network\n block_ns: 1D array\n Array counting the number of nodes in each block\n n_...
def log_labels_prior_hubspoke(N_nodes, block_ns): '\n Calculates the prior on the node labels for the hub-and-spoke model\n\n Parameters\n ----------\n N_nodes: int\n The number of nodes in the network\n block_ns: 1D array\n Array counting the number of nodes in each block\n ' ...
def log_ps_prior_layered(layer_ps): '\n Calculates the prior on the ps for the layered model\n\n Parameters\n ----------\n layer_ps: 1D array\n Array recording the density of each layer\n ' if np.all((layer_ps[:(- 1)] >= layer_ps[1:])): return loggamma(len(layer_ps)) else: ...
def log_ps_prior_hubspoke(block_ps): '\n Calculates the prior on the ps for the hub-and-spoke model\n\n Parameters\n ----------\n block_ps: 2D array\n Matrix recording the density of each block\n ' if ((block_ps[(0, 0)] >= block_ps[(0, 1)]) and (block_ps[(0, 1)] >= block_ps[(1, 1)])): ...
def log_labels_given_ps_layered(N_nodes, block_ns, layer_ms, layer_Ms, layer_ps): '\n Calculates P(\theta \\mid A, p) for the layered model\n\n Parameters\n ----------\n N_nodes: int\n Number of nodes in the network\n block_ns: 1D array\n Array counting the number of nodes in each blo...
def log_labels_given_ps_hubspoke(N_nodes, block_ns, block_ms, block_Ms, block_ps): '\n Calculates P(\theta \\mid A, p) for the hub-and-spoke model\n\n Parameters\n ----------\n N_nodes: int\n Number of nodes in the network\n block_ns: 1D array\n Array counting the number of nodes in e...
def get_max_edges(block_r, block_s, block_ns): '\n Calculates the maximum number of edges that could possibly exist between two\n blocks\n\n Parameters\n ----------\n block_r, block_s: int\n Blocks to get the maximum number of edges between\n block_ns: 1D array\n Array counting the...
def get_ordered_block_stats(G, node_labels, n_blocks=None): '\n Calculates fundamental statistics for working with the block matrix of a\n network and then orders them according to the on-diagonal densities\n\n Parameters\n ----------\n G: NetworkX graph\n The graph for which to get block st...
def get_block_stats(G, node_labels, n_blocks=None): '\n Calculates fundamental statistics for working with the block matrix of a\n network\n\n Parameters\n ----------\n G: NetworkX graph\n The graph for which to get block statistics\n node_labels: 1D array\n An array of the block l...
def get_layered_stats(block_ns, block_ms): '\n Collapses block edge counts down to layer edge counts\n\n Parameters\n ----------\n block_ns: 1D array\n Array counting the number of nodes in each block\n block_ms: 2D array\n Matrix counting the number of edges that exist between pairs ...
def get_on_diagonal_densities(block_ms, block_ns): '\n Calculates the densities within each block (densities of on diagonals of the\n block matrix)\n\n Parameters\n ----------\n block_ms: 2D array\n Matrix counting the number of edges that exist between pairs of blocks\n block_ns: 1D arra...
def reorder_blocks(node_labels, block_ns, block_ms, block_Ms): '\n Sorts the fundamental block statistics according to the within block\n densities such that the highest density is indexed as 0, and so on\n\n Parameters\n ----------\n node_labels: 1D array\n An array of the block label for e...
def adam(lr, tparams, grads, inp, cost): gshared = [theano.shared((p.get_value() * 0.0), name=('%s_grad' % k)) for (k, p) in tparams.iteritems()] gsup = [(gs, g) for (gs, g) in zip(gshared, grads)] f_grad_shared = theano.function(inp, cost, updates=gsup, profile=False) lr0 = 0.0002 b1 = 0.1 b2...
def zipp(params, tparams): '\n Push parameters to Theano shared variables\n ' for (kk, vv) in params.iteritems(): tparams[kk].set_value(vv)
def unzip(zipped): '\n Pull parameters from Theano shared variables\n ' new_params = OrderedDict() for (kk, vv) in zipped.iteritems(): new_params[kk] = vv.get_value() return new_params
def itemlist(tparams): '\n Get the list of parameters. \n Note that tparams must be OrderedDict\n ' return [vv for (kk, vv) in tparams.iteritems()]
def _p(pp, name): '\n Make prefix-appended name\n ' return ('%s_%s' % (pp, name))
def init_tparams(params): '\n Initialize Theano shared variables according to the initial parameters\n ' tparams = OrderedDict() for (kk, pp) in params.iteritems(): tparams[kk] = theano.shared(params[kk], name=kk) return tparams
def load_params(path, params): '\n Load parameters\n ' pp = numpy.load(path) for (kk, vv) in params.iteritems(): if (kk not in pp): warnings.warn(('%s is not in the archive' % kk)) continue params[kk] = pp[kk] return params
def ortho_weight(ndim): '\n Orthogonal weight init, for recurrent layers\n ' W = numpy.random.randn(ndim, ndim) (u, s, v) = numpy.linalg.svd(W) return u.astype('float32')
def norm_weight(nin, nout=None, scale=0.1, ortho=True): '\n Uniform initalization from [-scale, scale]\n If matrix is square and ortho=True, use ortho instead\n ' if (nout == None): nout = nin if ((nout == nin) and ortho): W = ortho_weight(nin) else: W = numpy.random.u...
def tanh(x): '\n Tanh activation function\n ' return tensor.tanh(x)
def relu(x): '\n ReLU activation function\n ' return (x * (x > 0))
def linear(x): '\n Linear activation function\n ' return x
def concatenate(tensor_list, axis=0): '\n Alternative implementation of `theano.tensor.concatenate`.\n ' concat_size = sum((tt.shape[axis] for tt in tensor_list)) output_shape = () for k in range(axis): output_shape += (tensor_list[0].shape[k],) output_shape += (concat_size,) for...
def build_dictionary(text): '\n Build a dictionary\n text: list of sentences (pre-tokenized)\n ' wordcount = OrderedDict() for cc in text: words = cc.split() for w in words: if (w not in wordcount): wordcount[w] = 0 wordcount[w] += 1 wor...
def load_dictionary(loc='/ais/gobi3/u/rkiros/bookgen/book_dictionary_large.pkl'): '\n Load a dictionary\n ' with open(loc, 'rb') as f: worddict = pkl.load(f) return worddict
def save_dictionary(worddict, wordcount, loc): '\n Save a dictionary to the specified location \n ' with open(loc, 'wb') as f: pkl.dump(worddict, f) pkl.dump(wordcount, f)
def tokenize(sentence, grams): words = sentence.split() tokens = [] for gram in grams: for i in range(((len(words) - gram) + 1)): tokens += ['_*_'.join(words[i:(i + gram)])] return tokens
def build_dict(X, grams): dic = Counter() for sentence in X: dic.update(tokenize(sentence, grams)) return dic
def compute_ratio(poscounts, negcounts, alpha=1): alltokens = list(set((poscounts.keys() + negcounts.keys()))) dic = dict(((t, i) for (i, t) in enumerate(alltokens))) d = len(dic) (p, q) = ((np.ones(d) * alpha), (np.ones(d) * alpha)) for t in alltokens: p[dic[t]] += poscounts[t] q[...
def process_text(text, dic, r, grams): '\n Return sparse feature matrix\n ' X = lil_matrix((len(text), len(dic))) for (i, l) in enumerate(text): tokens = tokenize(l, grams) indexes = [] for t in tokens: try: indexes += [dic[t]] except K...
def init_params(options): '\n Initialize all parameters\n ' params = OrderedDict() params['Wemb'] = norm_weight(options['n_words'], options['dim_word']) params = get_layer(options['encoder'])[0](options, params, prefix='encoder', nin=options['dim_word'], dim=options['dim']) params = get_laye...
def build_model(tparams, options): '\n Computation graph for the model\n ' opt_ret = dict() trng = RandomStreams(1234) x = tensor.matrix('x', dtype='int64') x_mask = tensor.matrix('x_mask', dtype='float32') y = tensor.matrix('y', dtype='int64') y_mask = tensor.matrix('y_mask', dtype=...
def build_encoder(tparams, options): '\n Computation graph, encoder only\n ' opt_ret = dict() trng = RandomStreams(1234) x = tensor.matrix('x', dtype='int64') x_mask = tensor.matrix('x_mask', dtype='float32') n_timesteps = x.shape[0] n_samples = x.shape[1] emb = tparams['Wemb'][x...
def build_encoder_w2v(tparams, options): '\n Computation graph for encoder, given pre-trained word embeddings\n ' opt_ret = dict() trng = RandomStreams(1234) embedding = tensor.tensor3('embedding', dtype='float32') x_mask = tensor.matrix('x_mask', dtype='float32') proj = get_layer(option...
def adam(lr, tparams, grads, inp, cost): gshared = [theano.shared((p.get_value() * 0.0), name=('%s_grad' % k)) for (k, p) in tparams.iteritems()] gsup = [(gs, g) for (gs, g) in zip(gshared, grads)] f_grad_shared = theano.function(inp, cost, updates=gsup, profile=False) lr0 = 0.0002 b1 = 0.1 b2...
def zipp(params, tparams): '\n Push parameters to Theano shared variables\n ' for (kk, vv) in params.iteritems(): tparams[kk].set_value(vv)
def unzip(zipped): '\n Pull parameters from Theano shared variables\n ' new_params = OrderedDict() for (kk, vv) in zipped.iteritems(): new_params[kk] = vv.get_value() return new_params
def itemlist(tparams): '\n Get the list of parameters. \n Note that tparams must be OrderedDict\n ' return [vv for (kk, vv) in tparams.iteritems()]
def _p(pp, name): '\n Make prefix-appended name\n ' return ('%s_%s' % (pp, name))
def init_tparams(params): '\n Initialize Theano shared variables according to the initial parameters\n ' tparams = OrderedDict() for (kk, pp) in params.iteritems(): tparams[kk] = theano.shared(params[kk], name=kk) return tparams
def load_params(path, params): '\n Load parameters\n ' pp = numpy.load(path) for (kk, vv) in params.iteritems(): if (kk not in pp): warnings.warn(('%s is not in the archive' % kk)) continue params[kk] = pp[kk] return params
def ortho_weight(ndim): '\n Orthogonal weight init, for recurrent layers\n ' W = numpy.random.randn(ndim, ndim) (u, s, v) = numpy.linalg.svd(W) return u.astype('float32')
def norm_weight(nin, nout=None, scale=0.1, ortho=True): '\n Uniform initalization from [-scale, scale]\n If matrix is square and ortho=True, use ortho instead\n ' if (nout == None): nout = nin if ((nout == nin) and ortho): W = ortho_weight(nin) else: W = numpy.random.u...
def tanh(x): '\n Tanh activation function\n ' return tensor.tanh(x)
def linear(x): '\n Linear activation function\n ' return x
def concatenate(tensor_list, axis=0): '\n Alternative implementation of `theano.tensor.concatenate`.\n ' concat_size = sum((tt.shape[axis] for tt in tensor_list)) output_shape = () for k in range(axis): output_shape += (tensor_list[0].shape[k],) output_shape += (concat_size,) for...
def build_dictionary(text): '\n Build a dictionary\n text: list of sentences (pre-tokenized)\n ' wordcount = OrderedDict() for cc in text: words = cc.split() for w in words: if (w not in wordcount): wordcount[w] = 0 wordcount[w] += 1 wor...
def load_dictionary(loc='/ais/gobi3/u/rkiros/bookgen/book_dictionary_large.pkl'): '\n Load a dictionary\n ' with open(loc, 'rb') as f: worddict = pkl.load(f) return worddict
def save_dictionary(worddict, wordcount, loc): '\n Save a dictionary to the specified location \n ' with open(loc, 'wb') as f: pkl.dump(worddict, f) pkl.dump(wordcount, f)
def load_dataset(name='f8k', load_train=True): '\n Load captions and image features\n Possible options: f8k, f30k, coco\n ' loc = ((path_to_data + name) + '/') (train_caps, dev_caps, test_caps) = ([], [], []) if load_train: with open(((loc + name) + '_train_caps.txt'), 'rb') as f: ...
def adam(lr, tparams, grads, inp, cost): gshared = [theano.shared((p.get_value() * 0.0), name=('%s_grad' % k)) for (k, p) in tparams.iteritems()] gsup = [(gs, g) for (gs, g) in zip(gshared, grads)] f_grad_shared = theano.function(inp, cost, updates=gsup, profile=False) b1 = 0.1 b2 = 0.001 e = ...
def build_dictionary(text): '\n Build a dictionary\n text: list of sentences (pre-tokenized)\n ' wordcount = OrderedDict() for cc in text: words = cc.split() for w in words: if (w not in wordcount): wordcount[w] = 0 wordcount[w] += 1 wor...
def load_dictionary(loc='/ais/gobi3/u/rkiros/bookgen/book_dictionary_large.pkl'): '\n Load a dictionary\n ' with open(loc, 'rb') as f: worddict = pkl.load(f) return worddict
def save_dictionary(worddict, wordcount, loc): '\n Save a dictionary to the specified location \n ' with open(loc, 'wb') as f: pkl.dump(worddict, f) pkl.dump(wordcount, f)
def yuv_import(filename, dims, numfrm, startfrm): fp = open(filename, 'rb') blk_size = ((np.prod(dims) * 3) / 2) fp.seek(int((blk_size * startfrm)), 0) d00 = (dims[0] // 2) d01 = (dims[1] // 2) Y = np.zeros((numfrm, dims[0], dims[1]), np.uint8, 'C') U = np.zeros((numfrm, d00, d01), np.uint...
def yuv2rgb(Y, U, V, height, width): U = imresize(U, [height, width], 'bilinear', mode='F') V = imresize(V, [height, width], 'bilinear', mode='F') Y = Y rf = (Y + (1.4075 * (V - 128.0))) gf = ((Y - (0.3455 * (U - 128.0))) - (0.7169 * (V - 128.0))) bf = (Y + (1.779 * (U - 128.0))) for m in ...
class ConvLSTMCell_orig(tf.nn.rnn_cell.RNNCell): 'A LSTM cell with convolutions instead of multiplications.\n Reference:\n Xingjian, S. H. I., et al. "Convolutional LSTM network: A machine learning approach for precipitation nowcasting." Advances in Neural Information Processing Systems. 2015.\n ' def _...
class QGConvLSTMCell(tf.nn.rnn_cell.RNNCell): 'A LSTM cell with convolutions instead of multiplications.\n Reference:\n Xingjian, S. H. I., et al. "Convolutional LSTM network: A machine learning approach for precipitation nowcasting." Advances in Neural Information Processing Systems. 2015.\n ' def __in...
class ConvGRUCell(tf.nn.rnn_cell.RNNCell): 'A GRU cell with convolutions instead of multiplications.' def __init__(self, shape, filters, kernel, activation=tf.tanh, normalize=True, data_format='channels_last', reuse=None): super(ConvGRUCell, self).__init__(_reuse=reuse) self._filters = filter...
def yuv_import(filename, dims, numfrm, startfrm): fp = open(filename, 'rb') blk_size = ((np.prod(dims) * 3) / 2) fp.seek(np.int((blk_size * startfrm)), 0) d00 = (dims[0] // 2) d01 = (dims[1] // 2) Y = np.zeros((numfrm, dims[0], dims[1]), np.uint8, 'C') U = np.zeros((numfrm, d00, d01), np.u...
def validate_parts(parts): if (type(parts) is int): sys.exit("Single value is not accepted for --parts as it's ambiguous between wanting only that exact part or that number of parts starting from 0. Please use a range instead like 0:2") parts_bounds = parts.split(':') try: parts_bounds = [...
def validate_part_format(pattern): format_variables = [tup[1] for tup in string.Formatter().parse(pattern) if (tup[1] is not None)] if ((len(format_variables) != 1) or (format_variables[0] != 'part')): sys.exit(f'Your pattern "{pattern}" is not valid as it should contain the "part" variable such as "{...
def main(): 'Main entry point' fire.Fire({'download': snip_download, 'compress': snip_compress, 'index': snip_index})
def snip_download(outfolder='data/downloaded', start=0, end=2313, dl_dedup_set=True): "Download and deduplicate a dataset.\n\n Parameters\n ----------\n outfolder : str, optional\n Where to put the downloaded metadata\n start : int, optional\n Start index of the metadata\n end : int, ...
def snip_index(parts='0:2', snip_feats='snip_feats/{part:04d}.npy', snip_base_index_path='snip_models/snip_vitl14_deep_IVFPQ_M4_base.index', index_outdir='snip_index', shard_size=1): 'Build a sharded index from SNIP compressed features\n\n Parameters\n ----------\n parts : str\n Parts to index, us...
def test(): import unittest from hypothesis import Settings, Verbosity from tests import testsuite as _testsuite unittest.TextTestRunner(verbosity=2).run(_testsuite)