Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|> # Y_test = np.array([test_doc_labels[i] for i in test_doc_codes]) # # DBN # X_train = np.array(load_marshal(args.train_doc_codes)) # Y_train = np.array(load_marshal(args.train_doc_labels)) # X_test = np.array(load_marshal(args.test_doc_codes)) # Y_test = np.arr...
results = retrieval_by_doclength(X_train, Y_train, X_test, Y_test, len_test, fraction=0.001, multilabel=args.multilabel)
Given snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_doc_codes', type=str, help='path to the train doc codes file') parser.add_argument('train_doc_labels', type=str, help='...
train_doc_codes = load_json(args.train_doc_codes)
Next line prediction: <|code_start|> # Y_train = np.array([train_doc_labels[i] for i in train_doc_codes]) # X_test = np.r_[X_test] # Y_test = np.array([test_doc_labels[i] for i in test_doc_codes]) # # DBN # X_train = np.array(load_marshal(args.train_doc_codes)) # Y_train = np.array(load_marshal...
query_docs = load_corpus(args.query_info)['docs']
Continue the code snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--label', type=str, required=True, help='path to the input label file') parser.add_argument('-c', '--corpus', type=str, required=True, help='path...
extract_labels(load_json(args.corpus)['docs'], args.label, args.output)
Here is a snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--label', type=str, required=True, help='path to the input label file') parser.add_argument('-c', '--corpus', type=str, required=True, help='path to the ...
extract_labels(load_json(args.corpus)['docs'], args.label, args.output)
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import def get_doc_codes(model, bow, vocab, avg=True): vec = np.zeros(model.vector_size) count = 0 for idx in bow: word = vocab[int(idx)] val = bow[idx] if word in model: vec += mode...
dump_json(doc_codes, output)
Given snippet: <|code_start|> model.save(filepath, overwrite=True) else: if self.verbose > 0: print('Epoch %05d: %s did not improve' % (epoch, self.monitor)) else: ...
heatmap(weights.T, '%s_%s%s'%(self.filename, epoch, self.ext))
Using the snippet: <|code_start|> model.save_weights(filepath, overwrite=True) else: model.save(filepath, overwrite=True) else: if self.verbose > 0: print('Epoch %05d: %...
weights = unitmatrix(weights, axis=0) # normalize
Predict the next line for this snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--label', type=str, required=True, help='path to the input label file') parser.add_argument('-c', '--corpus', type=str, required=Tru...
extract_labels(load_json(args.corpus)['docs'], load_json(args.label), args.output)
Here is a snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--label', type=str, required=True, help='path to the input label file') parser.add_argument('-c', '--corpus', type=str, required=True, help='path to the ...
extract_labels(load_json(args.corpus)['docs'], load_json(args.label), args.output)
Based on the snippet: <|code_start|> n_samples = X_docs.shape[0] np.random.seed(0) val_idx = np.random.choice(range(n_samples), args.n_val, replace=False) train_idx = list(set(range(n_samples)) - set(val_idx)) X_train = X_docs[train_idx] X_val = X_docs[val_idx] del X_docs # np.random.sh...
ae = AutoEncoder(n_vocab, args.n_dim, comp_topk=args.comp_topk, weights_file=args.load_weights)
Given snippet: <|code_start|> X_val = X_docs[val_idx] del X_docs # np.random.shuffle(X_docs) # n_val = args.n_val ## X_train = np.r_[X_docs[:-n_val]] ## X_val = np.r_[X_docs[-n_val:]] # X_train = np.r_[X_docs[:-n_val]] # del X_docs[:-n_val] # X_val = np.r_[X_docs] # del X_docs ...
if args.save_model:
Here is a snippet: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import def train(args): <|code_end|> . Write the next line using the current file imports: import timeit import argparse import numpy as np from os import path from autoencoder.core.ae import AutoEncoder, l...
corpus = load_corpus(args.input)
Based on the snippet: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import def train(args): corpus = load_corpus(args.input) n_vocab, docs = len(corpus['vocab']), corpus['docs'] corpus.clear() # save memory doc_keys = docs.keys() X_docs = [] for k...
X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0))
Given snippet: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import def train(args): corpus = load_corpus(args.input) n_vocab, docs = len(corpus['vocab']), corpus['docs'] corpus.clear() # save memory doc_keys = docs.keys() X_docs = [] for k in doc...
X_docs.append(vecnorm(doc2vec(docs[k], n_vocab), 'logmax1', 0))
Given the following code snippet before the placeholder: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import def train(args): corpus = load_corpus(args.input) n_vocab, docs = len(corpus['vocab']), corpus['docs'] corpus.clear() # save memory doc_keys = do...
X_docs_noisy = add_gaussian_noise(X_docs, 0.1)
Continue the code snippet: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import def train(args): corpus = load_corpus(args.input) n_vocab, docs = len(corpus['vocab']), corpus['docs'] corpus.clear() # save memory doc_keys = docs.keys() X_docs = [] ...
X_docs_noisy = add_masking_noise(X_docs, 0.01)
Continue the code snippet: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import def train(args): corpus = load_corpus(args.input) n_vocab, docs = len(corpus['vocab']), corpus['docs'] corpus.clear() # save memory doc_keys = docs.keys() X_docs = [] ...
X_docs_noisy = add_salt_pepper_noise(X_docs, 0.1)
Here is a snippet: <|code_start|> if args.noise: # X_train_noisy = X_docs_noisy[:-n_val] # X_val_noisy = X_docs_noisy[-n_val:] X_train_noisy = X_docs_noisy[train_idx] X_val_noisy = X_docs_noisy[val_idx] print 'added %s noise' % args.noise else: X_train_noisy = X_t...
dump_json(dict(zip(doc_keys[train_idx].tolist(), train_doc_codes.tolist())), args.output)
Based on the snippet: <|code_start|> # Y_train = load_pickle(args.train_doc_labels) # X_val = np.array(load_pickle(args.val_doc_codes)) # Y_val = load_pickle(args.val_doc_labels) # X_test = np.array(load_pickle(args.test_doc_codes)) # Y_test = load_pickle(args.test_doc_labels) if args.multilabel...
results = multiclass_classifier(X_train, Y_train, X_val, Y_val, \
Predict the next line after this snippet: <|code_start|> Y_test = [test_doc_labels[i] for i in test_doc_codes] # # DBN # X_train = np.array(load_pickle(args.train_doc_codes)) # Y_train = load_pickle(args.train_doc_labels) # X_val = np.array(load_pickle(args.val_doc_codes)) # Y_val = load_pickle(...
results = multilabel_classifier(X_train, Y_train, X_val, Y_val, \
Given the following code snippet before the placeholder: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_doc_codes', type=str, help='path to the train doc codes file') parser.add_ar...
train_doc_codes = load_json(args.train_doc_codes)
Continue the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.reuters import CorpusIterReuters # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus...
w2v = Word2Vec(args.n_dim, window=args.window_size, \
Predict the next line after this snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.reuters import CorpusIterReuters # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import Corpu...
save_w2v(w2v.model, args.save_model)
Here is a snippet: <|code_start|>''' from __future__ import absolute_import # from autoencoder.datasets.reuters import CorpusIterReuters # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus def train(args): vocab = load_json(args.vo...
doc_codes = doc_word2vec(docs, revdict(vocab_dict), args.load_model, args.output, avg=True)
Based on the snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.reuters import CorpusIterReuters # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus de...
vocab = load_json(args.vocab)
Given snippet: <|code_start|>@author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.reuters import CorpusIterReuters # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus def train(args): vocab = load_j...
corpus = load_corpus(args.corpus[0])
Continue the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.reuters import CorpusIterReuters # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus...
corpus = CorpusIter20News(args.corpus[0], recursive=True, stem=True, with_docname=False)
Here is a snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' def main(): parser T= argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, required=True, help='path to the input corpus dir') parser.add_argument('-o', '--output', type=str, default='./', help='path to the o...
xml2text(args.input, args.output, white_list)
Here is a snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' def main(): parser T= argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, required=True, help='path to the input corpus dir') parser.add_argument('-o', '--output', type=str, default='./', help='path to the o...
white_list = load_json(args.whitelist)
Given the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def train_lda(corpus, vocab_dict, n_topics, n_iter, save_model): lda = LdaModel(corpus, num_topics=n_topics, id2word=vocab_dict, \ passes=n_iter, minimum_probability=1e-3) lda.sav...
dump_json(doc_codes, output)
Continue the code snippet: <|code_start|> def generate_doc_codes(model, corpus, output): model.minimum_probability = 1e-3 n_topics = model.num_topics doc_codes = {} for key, doc_bow in corpus.iteritems(): code = np.zeros(n_topics) for idx, val in model[doc_bow]: code[idx] = v...
weights = unitmatrix(weights) # normalize
Here is a snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from keras.optimizers import Adam def retrieval(X_train, Y_train, X_test, Y_test, fractions=[0.01, 0.5, 1.0], multilabel=False): db_size = len(X_train) n_queries = len(X_test) <|code_end|> ....
X_train = unitmatrix(X_train) # normalize
Given the following code snippet before the placeholder: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import cached_stop_words = init_stopwords() class CorpusIter20News(object): def __init__(self, corpus_path, recursive=False, stem=True, with_docname=False): ...
self.files = get_all_files(corpus_path, recursive)
Continue the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import <|code_end|> . Use current file imports: import os from random import shuffle from collections import defaultdict from ..preprocessing.preprocessing import get_all_files, init_stopwords, tiny...
cached_stop_words = init_stopwords()
Given snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import cached_stop_words = init_stopwords() class CorpusIter20News(object): def __init__(self, corpus_path, recursive=False, stem=True, with_docname=False): self.stem = stem self.with_docna...
words = tiny_tokenize(text, self.stem, cached_stop_words)
Based on the snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, required=True, help='path to the input source file') parser.add_argument('--topn', type=int, default=25, help='keep only topn most...
labeldict = extract_labels(args.input, args.topn)
Given the following code snippet before the placeholder: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, required=True, help='path to the input source file') parser.add_argument('--topn', type=int, de...
dump_json(labeldict, args.output)
Predict the next line after this snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, required=True, help='path to the input corpus file') parser.add_argument('-o', '--output', type=str, default='...
construct_train_test_corpus(args.input, args.test_split, args.output, threshold=10, topn=2000)
Given the code snippet: <|code_start|>''' Created on Nov, 2016 @author: hugo ''' from __future__ import absolute_import def train(args): <|code_end|> , generate the next line using the imports in this file: import argparse import timeit import math import numpy as np from os import path from autoencoder.preproces...
corpus = load_corpus(args.corpus)
Predict the next line after this snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_doc_codes', type=str, help='path to the train doc code file') parser.add_argument('train_doc...
train_doc_codes = load_file(train_doc_codes_path, True)
Predict the next line after this snippet: <|code_start|> parser.add_argument('out_dir', type=str, help='path to the output dir') args = parser.parse_args() train_doc_codes_path = args.train_doc_codes test_doc_codes_path = args.test_doc_codes train_doc_codes = load_file(train_doc_codes_path, True) ...
dump_json(new_train_doc_codes, os.path.join(out_dir, 'new_' + os.path.basename(train_doc_codes_path)))
Predict the next line for this snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_path', type=str, help='path to the train corpus file') parser.add_argument('test_path', type=s...
docs = load_corpus(args.train_path)['docs'].items()
Given the following code snippet before the placeholder: <|code_start|> @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_path', type=str, help='path to the train corpus file') parser.add_argument('test_path', type=str, help...
train = corpus2libsvm(train_docs, doc_labels, os.path.join(args.out_dir, 'train.libsvm'))
Predict the next line for this snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('doc_codes_file', type=str, help='path to the input corpus file') parser.add_argument('doc_labels_fil...
reuters_visualize_pca_2d(load_json(args.doc_codes_file), load_json(args.doc_labels_file), classes_to_visual, args.output)
Given the following code snippet before the placeholder: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('doc_codes_file', type=str, help='path to the input corpus file') parser.add_argumen...
reuters_visualize_tsne(load_json(args.doc_codes_file), load_json(args.doc_labels_file), classes_to_visual, args.output)
Given snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('doc_codes_file', type=str, help='path to the input corpus file') parser.add_argument('doc_labels_file', type=str, help='path ...
reuters_visualize_pca_2d(load_json(args.doc_codes_file), load_json(args.doc_labels_file), classes_to_visual, args.output)
Predict the next line after this snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_doc_codes', type=str, help='path to the train doc code file') parser.add_argument('val_doc_c...
train_doc_codes = load_json(train_doc_codes_path)
Given snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_doc_codes', type=str, help='path to the train doc code file') parser.add_argument('val_doc_codes', type=str, help='path...
dump_json(train_doc_codes, os.path.join(out_dir, 'new_' + os.path.basename(train_doc_codes_path)))
Predict the next line for this snippet: <|code_start|> parser.add_argument('-cv', '--cross_validation', type=int, help='k-fold cross validation') args = parser.parse_args() # autoencoder # train_doc_codes = load_json(args.train_doc_codes) # train_doc_labels = load_json(args.train_doc_labels) # t...
results = neural_regression(X_new_train, Y_new_train, X_new_val, Y_new_val, \
Given the following code snippet before the placeholder: <|code_start|> @author: hugo ''' from __future__ import absolute_import def main(): parser = argparse.ArgumentParser() parser.add_argument('train_doc_codes', type=str, help='path to the train doc codes file') parser.add_argument('train_doc_labels',...
X_train = np.array(load_pickle(args.train_doc_codes))
Given snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus # from autoencoder.datasets.reuters import CorpusIterReuters def train...
d2v = MyDoc2Vec(args.n_dim, window=args.window_size, \
Given snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus # from autoencoder.datasets.reuters import CorpusIterReuters def train...
save_doc2vec(d2v.model, args.save_model)
Here is a snippet: <|code_start|> def train(args): vocab = load_json(args.vocab) # import pdb;pdb.set_trace() # load corpus corpus = CorpusIter20News(args.corpus[0], recursive=True, stem=True, with_docname=True) # corpus = CorpusIterMRD(args.corpus[0], load_json(args.docnames), stem=True, with_docna...
d2v = load_doc2vec(args.load_model)
Continue the code snippet: <|code_start|>def train(args): vocab = load_json(args.vocab) # import pdb;pdb.set_trace() # load corpus corpus = CorpusIter20News(args.corpus[0], recursive=True, stem=True, with_docname=True) # corpus = CorpusIterMRD(args.corpus[0], load_json(args.docnames), stem=True, wit...
doc_codes = predict(d2v, corpus_iter)
Given the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus # from autoencoder.datasets.reuters import CorpusIterReuters ...
vocab = load_json(args.vocab)
Predict the next line for this snippet: <|code_start|> vocab = load_json(args.vocab) # import pdb;pdb.set_trace() # load corpus corpus = CorpusIter20News(args.corpus[0], recursive=True, stem=True, with_docname=True) # corpus = CorpusIterMRD(args.corpus[0], load_json(args.docnames), stem=True, with_do...
dump_json(doc_codes, args.output)
Using the snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import # from autoencoder.datasets.movie_review_data import CorpusIterMRD # from autoencoder.datasets.wiki10plus import CorpusIterWiki10plus # from autoencoder.datasets.reuters import CorpusIterReuters def t...
corpus = CorpusIter20News(args.corpus[0], recursive=True, stem=True, with_docname=True)
Given the following code snippet before the placeholder: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-train', '--train_path', type=str, required=True, help='path to the training corpus') parser.add_argument('-test', '--te...
train_corpus, test_corpus = construct_train_test_corpus(args.train_path, args.test_path, args.out_dir, threshold=args.threshold, topn=args.topn)
Predict the next line after this snippet: <|code_start|>''' Created on Dec, 2016 @author: hugo ''' def main(): parser = argparse.ArgumentParser() parser.add_argument('-train', '--train_path', type=str, required=True, help='path to the training corpus') parser.add_argument('-test', '--test_path', type=...
train_labels = generate_20news_doc_labels(train_corpus['docs'].keys(), os.path.join(args.out_dir, 'train.labels'))
Using the snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import pattern = r'>([^<>]+)<' prog = re.compile(pattern) <|code_end|> , determine the next line of code. You have imports: import os import re import numpy as np import pdb;pdb.set_trace() from random i...
cached_stop_words = init_stopwords()
Using the snippet: <|code_start|> self.stem = stem self.train_docs = train_docs self.with_docname = with_docname self.files = get_all_files(corpus_dir, False) def __iter__(self): shuffle(self.files) count = 0 for filename in self.files: doc_name = ...
contents = tiny_tokenize_xml(contents, False, cached_stop_words)
Predict the next line after this snippet: <|code_start|>@author: hugo ''' from __future__ import absolute_import pattern = r'>([^<>]+)<' prog = re.compile(pattern) cached_stop_words = init_stopwords() class CorpusIterWiki10plus(object): def __init__(self, corpus_dir, train_docs, stem=True, with_docname=False):...
words = tiny_tokenize(text, self.stem, cached_stop_words)
Continue the code snippet: <|code_start|>''' Created on Jan, 2017 @author: hugo ''' from __future__ import absolute_import pattern = r'>([^<>]+)<' prog = re.compile(pattern) cached_stop_words = init_stopwords() class CorpusIterWiki10plus(object): def __init__(self, corpus_dir, train_docs, stem=True, with_docn...
self.files = get_all_files(corpus_dir, False)
Next line prediction: <|code_start|> corpus = {} files = get_all_files(corpus_dir, False) cached_stop_words = [] # cached_stop_words = init_stopwords() count = 0 for filename in files: try: with open(filename, 'r') as fp: text = fp.read().lower() ...
train_word_freq = count_words(train_data.values())
Based on the snippet: <|code_start|> cached_stop_words = [] # cached_stop_words = init_stopwords() count = 0 for filename in files: try: with open(filename, 'r') as fp: text = fp.read().lower() # remove punctuations, stopwords and *unnecessary digits*, ...
train_docs, vocab_dict, train_word_freq = construct_corpus(train_data, train_word_freq, True, threshold=threshold, topn=topn)
Next line prediction: <|code_start|> count = 0 for filename in files: try: with open(filename, 'r') as fp: text = fp.read().lower() # remove punctuations, stopwords and *unnecessary digits*, stemming words = tiny_tokenize(text, stem, cached_stop...
dump_json(train_corpus, os.path.join(output, 'train.corpus'))
Based on the snippet: <|code_start|> try: word_count[vocab_dict[word]] = freq except: # word is not in vocab, i.e., this word should be discarded continue docs[key] = word_count return docs def build_vocab(word_freq, threshold=5, topn=None, start_idx=...
dump_json(train_corpus, os.path.join(output, 'train.corpus'))
Continue the code snippet: <|code_start|> # doc_name = os.path.basename(filename) parent_name, child_name = os.path.split(filename) doc_name = os.path.split(parent_name)[-1] + '_' + child_name for i in range(len(words)): # doc-word frequ...
corpus = load_json(corpus_path)
Given the code snippet: <|code_start|> if freq < threshold: return vocab_dict vocab_dict[word] = idx idx += 1 return vocab_dict def construct_train_test_corpus(train_path, test_path, output, threshold=5, topn=None): train_docs, vocab_dict, train_word_freq = co...
write_file(data, output)
Using the snippet: <|code_start|> features: Number of neurons in each layer, and number of layers (given by length of sequence) + one layer for softmax. train: If model is being evaluated in training mode or not. init_fn: Initialization function used for dense layers. activation_fn: Activ...
kernel_init=init.sparse_init(
Based on the snippet: <|code_start|> features = (32, 32), train=True, init_fn = flax.deprecated.nn.initializers.kaiming_normal, activation_fn = flax.deprecated.nn.relu, masks = None, masked_layer_indices = None, dropout_rate = 0.): "...
masks = masked.generate_model_masks(depth, masks,
Predict the next line for this snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICE...
self._dataset = cifar10.CIFAR10Dataset(
Predict the next line after this snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
dataset = dataset_factory.create_dataset(
Next line prediction: <|code_start|># limitations under the License. # Lint as: python3 """Weight Symmetry: Train model with randomly shuffled sparse mask.""" # TODO: Refactor drivers to separate logic from flags/IO. experiment_dir = '{}/{}/'.format(FLAGS.experiment_dir, work_unit_id) logging.info('Saving exper...
base_model, _ = model_factory.create_model(
Given the following code snippet before the placeholder: <|code_start|> host_count = jax.host_count() local_device_count = jax.local_device_count() logging.info('Device count: %d, host count: %d, local device count: %d', jax.device_count(), host_count, local_device_count) if jax.host_id() == 0: ...
mask = mask_factory.create_mask(FLAGS.mask_type, base_model, mask_rng,
Here is a snippet: <|code_start|> rng, ((input_shape, jnp.float32),), num_classes=dataset.num_classes) logging.info('Generating random mask based on model') # Re-initialize the RNG to maintain same training pattern (as in prune code). mask_rng = jax.random.PRNGKey(FLAGS.mask_randomseed) mask = mas...
mask = masked.propagate_masks(mask)
Using the snippet: <|code_start|> jax.device_count(), host_count, local_device_count) if jax.host_id() == 0: summary_writer = tensorboard.SummaryWriter(experiment_dir) dataset = dataset_factory.create_dataset( FLAGS.dataset, FLAGS.batch_size, FLAGS.batch_size_test, shuffl...
mask_stats = symmetry.get_mask_stats(mask)
Continue the code snippet: <|code_start|> rng, ((input_shape, jnp.float32),), num_classes=dataset.num_classes, masks=mask) if FLAGS.optimizer == 'Adam': optimizer = flax.optim.Adam( learning_rate=FLAGS.lr, weight_decay=FLAGS.weight_decay) elif FLAGS.optimizer == 'Momentum': optimiz...
trainer = training.Trainer(
Next line prediction: <|code_start|> input_shape = (1,) + dataset.shape base_model, _ = model_factory.create_model( FLAGS.model, rng, ((input_shape, jnp.float32),), num_classes=dataset.num_classes) logging.info('Generating random mask based on model') # Re-initialize the RNG to maintain same ...
utils.dump_dict_json(
Predict the next line for this snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
fixed_param.main([])
Next line prediction: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
dataset = dataset_factory.create_dataset(
Here is a snippet: <|code_start|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Weight Symmetry: Train model with randomly sampled sparse mask.""" experiment_dir =...
base_model, _ = model_factory.create_model(
Given the following code snippet before the placeholder: <|code_start|> host_count = jax.host_count() local_device_count = jax.local_device_count() logging.info('Device count: %d, host count: %d, local device count: %d', jax.device_count(), host_count, local_device_count) if jax.host_id() == 0: ...
mask = mask_factory.create_mask(FLAGS.mask_type, base_model, mask_rng,
Here is a snippet: <|code_start|> num_classes=dataset.num_classes, masked_layer_indices=FLAGS.masked_layer_indices) logging.info('Generating random mask based on model') # Re-initialize the RNG to maintain same training pattern (as in prune code). mask_rng = jax.random.PRNGKey(FLAGS.mask_randomseed) ...
mask = masked.propagate_masks(mask)
Given snippet: <|code_start|> if jax.host_id() == 0: summary_writer = tensorboard.SummaryWriter(experiment_dir) dataset = dataset_factory.create_dataset( FLAGS.dataset, FLAGS.batch_size, FLAGS.batch_size_test, shuffle_buffer_size=FLAGS.shuffle_buffer_size) logging.info('Training %s o...
mask_stats = symmetry.get_mask_stats(mask)
Given the following code snippet before the placeholder: <|code_start|> rng, ((input_shape, jnp.float32),), num_classes=dataset.num_classes, masks=mask) if FLAGS.optimizer == 'Adam': optimizer = flax.optim.Adam( learning_rate=FLAGS.lr, weight_decay=FLAGS.weight_decay) elif FLAGS.optimi...
trainer = training.Trainer(
Here is a snippet: <|code_start|> base_model, _ = model_factory.create_model( FLAGS.model, rng, ((input_shape, jnp.float32),), num_classes=dataset.num_classes, masked_layer_indices=FLAGS.masked_layer_indices) logging.info('Generating random mask based on model') # Re-initialize the RNG to...
utils.dump_dict_json(
Given snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
return isinstance(layer, utils.PRUNING_WRAPPER) and layer.trainable
Using the snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
dataset = dataset_factory.create_dataset(
Based on the snippet: <|code_start|> # Lint as: python3 """Weight Symmetry: Train models with fixed param, but diff. depth and width.""" experiment_dir = path.join(FLAGS.experiment_dir, str(work_unit_id)) logging.info('Saving experimental results to %s', experiment_dir) host_count = jax.host_count() local_de...
features = mnist_fc.feature_dim_for_param(
Using the snippet: <|code_start|> host_count = jax.host_count() local_device_count = jax.local_device_count() logging.info('Device count: %d, host count: %d, local device count: %d', jax.device_count(), host_count, local_device_count) if jax.host_id() == 0: summary_writer = tensorboard.Summa...
base_model, _ = model_factory.create_model(
Using the snippet: <|code_start|> rng = jax.random.PRNGKey(FLAGS.random_seed) input_shape = (1,) + dataset.shape input_len = functools.reduce(operator.mul, dataset.shape) features = mnist_fc.feature_dim_for_param( input_len, FLAGS.param_count, FLAGS.depth) logging.info('Model Configurati...
mask = masked.shuffled_mask(
Next line prediction: <|code_start|> features = mnist_fc.feature_dim_for_param( input_len, FLAGS.param_count, FLAGS.depth) logging.info('Model Configuration: %s', str(features)) base_model, _ = model_factory.create_model( MODEL, rng, ((input_shape, jnp.float32),), num_classes...
mask_stats = symmetry.get_mask_stats(mask)
Next line prediction: <|code_start|> features=features, masks=mask) if FLAGS.opt == 'Adam': optimizer = flax.optim.Adam( learning_rate=FLAGS.lr, weight_decay=FLAGS.weight_decay) elif FLAGS.opt == 'Momentum': optimizer = flax.optim.Momentum( learning_rate=FLAGS.lr, beta=FLAGS.mo...
trainer = training.Trainer(
Given the code snippet: <|code_start|> if jax.host_id() == 0: summary_writer = tensorboard.SummaryWriter(experiment_dir) dataset = dataset_factory.create_dataset( FLAGS.dataset, FLAGS.batch_size, FLAGS.batch_size_test, shuffle_buffer_size=FLAGS.shuffle_buffer_size) logging.info('Train...
model_param_count = utils.count_param(base_model, ('kernel',))
Based on the snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and #...
_, initial_params = mnist_fc.MNISTFC.init_by_shape(
Continue the code snippet: <|code_start|> invalid_masks = { 'MaskedModule_0': { 'kernel': jnp.zeros((self._batch_size, 5 * 5 * 16)) } } with self.assertRaisesRegex( ValueError, 'Mask is invalid for model.'): mnist_fc.MNISTFC.init_by_shape( ...
total_size = utils.count_param(model, PARAM_COUNT_PARAM)
Given the code snippet: <|code_start|># coding=utf-8 # Copyright 2022 RigL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
jnp.array], float], masked.MaskType]
Continue the code snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed ...
_, initial_params = mnist_cnn.MNISTCNN.init_by_shape(