code stringlengths 17 6.64M |
|---|
def best_cluster_fit(y_true, y_pred):
y_true = y_true.astype(np.int64)
D = (max(y_pred.max(), y_true.max()) + 1)
w = np.zeros((D, D), dtype=np.int64)
for i in range(y_pred.size):
w[(y_pred[i], y_true[i])] += 1
ind = la.linear_assignment((w.max() - w))
best_fit = []
for i in range(y... |
def cluster_acc(y_true, y_pred):
(_, ind, w) = best_cluster_fit(y_true, y_pred)
return ((sum([w[(i, j)] for (i, j) in ind]) * 1.0) / y_pred.size)
|
def plot(x, y, plot_id, names=None, n_clusters=10):
viz_df = pd.DataFrame(data=x[:5000])
viz_df['Label'] = y[:5000]
if (names is not None):
viz_df['Label'] = viz_df['Label'].map(names)
plt.subplots(figsize=(8, 5))
sns.scatterplot(x=0, y=1, hue='Label', legend='full', hue_order=sorted(viz_d... |
class n2d():
'\n n2d: Class for n2d\n\n Parameters:\n ------------\n\n input_dim: int\n dimensions of input\n\n manifold_learner: initialized class, such as UmapGMM\n the manifold learner and clustering algorithm. Class should have at\n least fi... |
def save_n2d(obj, encoder_id, manifold_id):
'\n save_n2d: save n2d objects\n --------------------------\n\n description: Saves the encoder to an h5 file and the manifold learner/clusterer\n to a pickle.\n\n parameters:\n\n - obj: the fitted n2d object\n - encoder_id: what to save the ... |
def load_n2d(encoder_id, manifold_id):
'\n load_n2d: load n2d objects\n --------------------------\n\n description: loads fitted n2d objects from files. Note you CANNOT train\n these objects further, the only method which will perform correctly is `.predict`\n\n parameters:\n\n - encoder_id:... |
class manifold_cluster_generator(N2D.UmapGMM):
def __init__(self, manifold_class, manifold_args, cluster_class, cluster_args):
self.manifold_in_embedding = manifold_class(**manifold_args)
self.cluster_manifold = cluster_class(**cluster_args)
proba = getattr(self.cluster_manifold, 'predict... |
class autoencoder_generator(N2D.AutoEncoder):
def __init__(self, model_levels=(), x_lambda=(lambda x: x)):
self.Model = Model(model_levels[0], model_levels[2])
self.encoder = Model(model_levels[0], model_levels[1])
self.x_lambda = x_lambda
def fit(self, x, batch_size, epochs, loss, o... |
def load_clip_cpu(backbone_name):
model_path = 'path_to_CLIP_ViT-B-16_pre-trained_parameters'
try:
model = torch.jit.load(model_path, map_location='cpu').eval()
state_dict = None
except RuntimeError:
state_dict = torch.load(model_path, map_location='cpu')
model = clip.build_mod... |
def transform_center():
interp_mode = Image.BICUBIC
tfm_test = []
tfm_test += [Resize(224, interpolation=interp_mode)]
tfm_test += [CenterCrop((224, 224))]
tfm_test += [ToTensor()]
normalize = Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])
tfm... |
def get_videos(vidname, read_path):
allframes = []
videoins = (read_path + vidname)
vvv = cv2.VideoCapture(videoins)
if (not vvv.isOpened()):
print('Video is not opened! {}'.format(videoins))
else:
fps = vvv.get(cv2.CAP_PROP_FPS)
totalFrameNumber = vvv.get(cv2.CAP_PROP_FRAM... |
@lru_cache()
def default_bpe():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bpe_simple_vocab_16e6.txt.gz')
|
@lru_cache()
def bytes_to_unicode():
"\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B toke... |
def get_pairs(word):
'Return set of symbol pairs in a word.\n Word is represented as tuple of symbols (symbols being variable-length strings).\n '
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
|
def basic_clean(text):
text = ftfy.fix_text(text)
text = html.unescape(html.unescape(text))
return text.strip()
|
def whitespace_clean(text):
text = re.sub('\\s+', ' ', text)
text = text.strip()
return text
|
class SimpleTokenizer(object):
def __init__(self, bpe_path: str=default_bpe()):
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for (k, v) in self.byte_encoder.items()}
merges = gzip.open(bpe_path).read().decode('utf-8').split('\n')
merges = merges[1:(((49152 - 25... |
def setup_path(args):
prefix = args.prefix
postfix = args.postfix
openset = args.openset
temporal = args.temporal
tfmlayers = args.tfm_layers
batchsize = args.batchsize
numFrames = args.numFrames
iters = args.num_iterations
verbose = (args.verbose if args.verbose else 'none')
d... |
def setup_dataloader(args):
if (args.dataset == 'HMDB51-feature-30fps-center'):
feature_root = '../feat/HMDB'
else:
raise ValueError('Unknown dataset.')
if args.dataset.startswith('HMDB'):
(trainactions, valactions) = ([], [])
trn_dataset = readFeatureHMDB51(root=feature_ro... |
def main(args):
np.random.seed(args.seed)
torch.manual_seed(args.seed)
device = ('cuda' if torch.cuda.is_available() else 'cpu')
[logPath, modelPath] = cg.setup_path(args)
args.model_path = modelPath
logger = SummaryWriter(logdir=logPath)
args.return_intermediate_text_feature = 0
[trn_... |
def convert_to_token(xh):
xh_id = clip.tokenize(xh).cpu().data.numpy()
return xh_id
|
def text_prompt(dataset='HMDB51', clipbackbone='ViT-B/16', device='cpu'):
(actionlist, actionprompt, actiontoken) = ([], {}, [])
numC = {'HMDB51-feature-30fps-center': 51}
(clipmodel, _) = clip.load(clipbackbone, device=device, jit=False)
for paramclip in clipmodel.parameters():
paramclip.requ... |
def set_learning_rate(optimizer, lr):
for g in optimizer.param_groups:
g['lr'] = lr
|
def readtxt(metapath, datapath):
(vidDir, vidLabel) = ([], [])
f = open(metapath, 'rb')
path = f.readlines()
f.close()
for p in path:
psplit = p.decode('utf-8').strip('\n').split(',')
vidDir += [os.path.join(datapath, psplit[0])]
vidLabel += [[int(psplit[1]), psplit[2], int... |
def save_checkpoint(state, is_best=0, gap=1, filename='checkpoint.pth.tar', keep_all=False):
torch.save(state, filename)
last_epoch_path = os.path.join(os.path.dirname(filename), ('checkpoint_iter%s.pth.tar' % str((state['iteration'] - gap))))
if (not keep_all):
try:
os.remove(last_epo... |
class _RepeatSampler(object):
' Sampler that repeats forever.\n Args:\n sampler (Sampler)\n '
def __init__(self, sampler):
self.sampler = sampler
def __iter__(self):
while True:
(yield from iter(self.sampler))
|
class FastDataLoader(torch.utils.data.dataloader.DataLoader):
'for reusing cpu workers, to save time'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
self.iterator = super().__iter__()... |
def main():
mode = argv[1]
e = Evaluator()
if (mode == 'wikt'):
e.read_all_wiktionary()
e.compare_with_triangles_stdin()
elif (mode == 'feat'):
e.write_labels(argv[2])
e.featurize_and_uniq_triangles_stdin()
|
def scan_stdin(args):
stats = {'punct': 0, 'punct ok': 0, 'sum': 0, 'invalid': 0}
for l in stdin:
stats['sum'] += 1
try:
(wc1, w1, wc2, w2) = l.decode('utf8').strip().split('\t')[0:4]
if args['punct']:
if (abs((len(punct_re.findall(w1)) - len(punct_re.fi... |
def read_unigrams(fn):
with open(fn) as f:
for l in f:
(wc, c, cnt) = l.decode('utf8').split('\t')
unigrams[wc][c] = int(cnt)
sum_[wc] += int(cnt)
|
def main():
args = docopt(__doc__, version='Wikt2Dict - Find anomalies 1.0')
if args['unigram']:
read_unigrams(args['<unigram_file>'])
scan_stdin(args)
|
def read_pairs(wc_filter=None, input_files=None, use_stdin=False):
tri = defaultdict(set)
if use_stdin:
for l in stdin:
add_pair(l, tri, wc_filter)
elif input_files:
for fn in input_files:
with open(fn) as f:
for l in f:
add_pair(... |
def add_pair(l, tri, wc_filter):
try:
(wc1, w1, wc2, w2) = l.decode('utf8').strip().split('\t')[0:4]
if (wc_filter and ((not (wc1 in wc_filter)) or (not (wc2 in wc_filter)))):
return
tri[(wc1, w1)].add((wc2, w2))
tri[(wc2, w2)].add((wc1, w1))
except ValueError:
... |
def find_k_long_polygons(pairs, k):
if (k == 1):
for word in pairs.keys():
(yield [word])
else:
for polygon in find_k_long_polygons(pairs, (k - 1)):
for word in pairs[polygon[(- 1)]]:
if (not (word in polygon[1:])):
(yield (polygon + ... |
def find_and_print_polygons(pairs, found=None, k=4, mode='polygons'):
for polygon in find_k_long_polygons(pairs, (k + 1)):
if (polygon[0] == polygon[(- 1)]):
output(pairs, found=polygon, mode=mode)
|
def find_k_clicks(pairs, k):
if (k == 1):
for word in pairs.keys():
(yield [word])
else:
for click in find_k_clicks(pairs, (k - 1)):
if (len(click) > (k - 1)):
continue
for word in pairs[click[(- 1)]]:
if (word in click):
... |
def find_and_print_clicks(pairs, k=4):
for click in find_k_clicks(pairs, k):
output(pairs, found=sorted(click), mode='clicks')
|
def output(pairs, found, mode):
(edge_density, new_pairs) = edge_density_and_new_pairs(pairs, found)
if ((mode == 'clicks') and (edge_density == 1.0)):
if arguments['--illustrate']:
print(' --> '.join((', '.join([i, j]) for (i, j) in found)).encode('utf8'))
else:
print(... |
def edge_density_and_new_pairs(pairs, cycle):
new_pairs = list()
all_pairs = list()
for (i, e1) in enumerate(cycle):
for e2 in cycle[(i + 1):(- 1)]:
all_pairs.append(sorted([e1, e2]))
if ((not (e2 in pairs[e1])) and (not (e1 in pairs[e2]))):
new_pairs.append... |
def main():
if arguments['--wc-filter']:
with open(arguments['--wc-filter']) as f:
wc_filter = set([wc.strip() for wc in f])
else:
wc_filter = None
k = int(arguments['--k'])
if arguments['<input>']:
pairs = read_pairs(wc_filter, input_files=arguments['<input>'])
... |
def read_table(fn):
mapping = defaultdict(set)
with open(fn) as f:
for l in f:
fd = l.decode('utf8').strip().split('\t')
id_ = int(fd[0])
for (i, lang) in enumerate(['en', 'hu', 'la', 'pl']):
if (fd[(i + 1)] == '#'):
continue
... |
def read_words(fn):
words = set()
with open(fn) as f:
for l in f:
fd = l.decode('utf8').strip().split('\t')
if (len(fd) >= 2):
words.add((fd[0], fd[1]))
if (len(fd) >= 4):
words.add((fd[2], fd[3]))
return words
|
def find_translations(words):
iter_no = 0
for l in stdin:
iter_no += 1
if ((iter_no % 1000000) == 0):
stderr.write('{}\n'.format(iter_no))
try:
fd = l.decode('utf8').strip().split('\t')
pair1 = (fd[0], fd[1])
pair2 = (fd[2], fd[3])
... |
def add_orig_bindings(mapping, translations):
for ((wc, word), ids) in mapping.iteritems():
for id_ in ids:
translations[id_][wc].add(word)
|
def find_translations_to_table(mapping):
iter_no = 0
translations = defaultdict((lambda : defaultdict(set)))
add_orig_bindings(mapping, translations)
for l in stdin:
iter_no += 1
if ((iter_no % 1000000) == 0):
stderr.write('{}\n'.format(iter_no))
try:
fd... |
def main():
mode = (argv[2] if (len(argv) > 2) else 'direct')
if (mode == 'direct'):
words = read_words(argv[1])
find_translations(words)
elif (mode == 'collect'):
table = read_table(argv[1])
find_translations_to_table(table)
|
def main():
if ((len(argv) > 2) and (not (argv[2] == 'all'))):
filter_wc = set([wc.strip() for wc in argv[2:]])
else:
filter_wc = None
cfg_fn = argv[1]
logger = logging.getLogger('wikt2dict')
cfg = ConfigHandler('general', cfg_fn)
logger = LogHandler(cfg)
with open(cfg['wik... |
def main():
unigrams = defaultdict((lambda : defaultdict(int)))
for l in stdin:
try:
(wc1, w1, wc2, w2) = l.decode('utf8').strip().split('\t')[0:4]
for c in w1:
unigrams[wc1][c] += 1
for c in w2:
unigrams[wc2][c] += 1
except V... |
class SectionAndArticleParser(ArticleParser):
'\n Class for parsing Wiktionaries that have translation tables\n in foreign articles too and section-level parsing is required.\n e.g. dewiktionary has a translation section in the article\n about the English word dog. Therefore, we need to recognize\n ... |
class LangnamesArticleParser(ArticleParser):
'\n Class for parsing Wiktionaries that use simple lists for translations\n instead of templates '
def __init__(self, wikt_cfg, parser_cfg, filter_langs=None):
ArticleParser.__init__(self, wikt_cfg, parser_cfg, filter_langs)
self.read_langnam... |
class DefaultArticleParser(ArticleParser):
def extract_translations(self, title, text):
translations = list()
for tr in self.cfg.trad_re.finditer(text):
wc = tr.group(self.cfg.wc_field)
if ((not wc) or (not wc.strip()) or (not (wc in self.wikt_cfg.wikicodes))):
... |
def err(msg):
' Prints a message to stderr, terminating it with a newline '
sys.stderr.write((msg + '\n'))
|
class Article():
' Stores the contents of a Wikipedia article '
def __init__(self, title, markup, is_redirect):
self.title = title
self.markup = markup
self.is_redirect = is_redirect
|
class WikiParser():
'Parses the Wikipedia XML and extracts the relevant data,\n such as sentences and vocabulary'
def __init__(self, callback, ignore_redirects=True):
self.callback = callback
self.ignore_redirects = ignore_redirects
self.buffer_size = ((10 * 1024) * 1024)
... |
class Triangulator(object):
def __init__(self, triangle_wc):
self.wikicodes = set(triangle_wc)
self.cfg = config.WiktionaryConfig()
self.pairs = defaultdict((lambda : defaultdict((lambda : defaultdict((lambda : defaultdict(list)))))))
self.triangles = defaultdict(list)
sel... |
class Wiktionary(object):
def __init__(self, cfg):
self.cfg = cfg
self.init_parsers()
self.pairs = list()
def init_parsers(self):
self.parsers = list()
for (parser_cl, parser_cfg) in self.cfg.parsers:
self.parsers.append(parser_cl(self.cfg, parser_cfg))
... |
def EmbedWord2Vec(walks, dimension):
time_start = time.time()
print('Creating embeddings.')
model = Word2Vec(walks, size=dimension, window=5, min_count=0, sg=1, workers=32, iter=1)
node_ids = model.wv.index2word
node_embeddings = model.wv.vectors
print('Embedding generation runtime: ', (time.t... |
def EmbedPoincare(relations, epochs, dimension):
model = PoincareModel(relations, size=dimension, workers=32)
model.train(epochs)
node_ids = model.index2entity
node_embeddings = model.vectors
return (node_ids, node_embeddings)
|
def TraverseAndSelect(length, num_walks, hyperedges, vertexMemberships, alpha=1.0, beta=0):
walksTAS = []
for hyperedge_index in hyperedges:
hyperedge = hyperedges[hyperedge_index]
walk_hyperedge = []
for _ in range(num_walks):
curr_vertex = random.choice(hyperedge['members... |
def SubsampleAndTraverse(length, num_walks, hyperedges, vertexMemberships, alpha=1.0, beta=0):
walksSAT = []
for hyperedge_index in hyperedges:
hyperedge = hyperedges[hyperedge_index]
walk_vertex = []
curr_vertex = random.choice(hyperedge['members'])
for _ in range(num_walks):
... |
def getFeaturesTrainingData():
i = 0
lists = []
labels = []
for vertex in G.nodes:
vertex_embedding_list = []
lists.append({'f': vertex_features[vertex].tolist()})
labels.append(vertex_labels[vertex])
X_unshuffled = []
for hlist in lists:
x = np.zeros((feature_d... |
def getTrainingData():
i = 0
lists = []
labels = []
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
ver... |
def getMLPTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
lists.append({'h': hyperedge_embeddings[hyperedge_ids.index(h)].tolist(), 'f': vertex_features[h].tolist()})
label = np.zeros((n... |
def getDSTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
... |
def hyperedgesTrain(X_train, Y_train, num_epochs):
deephyperedges_transductive_model.load_weights((('models/' + dataset_name) + '/deephyperedges_transductive_model.h5'))
history = deephyperedges_transductive_model.fit(X_train, Y_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_split=0... |
def MLPTrain(X_MLP_transductive_train, Y_MLP_transductive_train, num_epochs):
MLP_transductive_model.load_weights((('models/' + dataset_name) + '/MLP_transductive_model.h5'))
history = MLP_transductive_model.fit(X_MLP_transductive_train, Y_MLP_transductive_train, epochs=num_epochs, batch_size=batch_size, shuf... |
def DeepSetsTrain(X_deepset_transductive_train, Y_deepset_transductive_train, num_epochs):
deepsets_transductive_model.load_weights((('models/' + dataset_name) + '/deepsets_transductive_model.h5'))
history = deepsets_transductive_model.fit(X_deepset_transductive_train, Y_deepset_transductive_train, epochs=num... |
def testModel(model, X_tst, Y_tst):
from sklearn.metrics import classification_report, accuracy_score
target_names = ['Neural Networks', 'Case Based', 'Reinforcement Learning', 'Probabilistic Methods', 'Genetic Algorithms', 'Rule Learning', 'Theory']
y_pred = model.predict(X_tst, batch_size=16, verbose=0)... |
def RunAllTests(percentTraining, num_times, num_epochs):
for i in range(num_times):
print('percent: ', percentTraining, ', iteration: ', (i + 1), ', model: deep hyperedges')
(X, Y) = getTrainingData()
(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, train_size=percentTraining, t... |
def getFeaturesTrainingData():
i = 0
lists = []
labels = []
for vertex in G.nodes:
vertex_embedding_list = []
lists.append({'f': vertex_features[vertex].tolist()})
labels.append(vertex_labels[vertex])
X_unshuffled = []
for hlist in lists:
x = np.zeros((feature_d... |
def getTrainingData():
i = 0
lists = []
labels = []
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
ver... |
def getMLPTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
lists.append({'h': hyperedge_embeddings[hyperedge_ids.index(h)].tolist(), 'f': vertex_features[h].tolist()})
label = np.zeros((n... |
def getDSTrainingData():
i = 0
lists = []
labels = []
maxi = 0
for h in hyperedges:
vertex_embedding_list = []
hyperedge = hyperedges[h]
for vertex in hyperedge['members']:
i += 1
if ((i % 100000) == 0):
print(i)
try:
... |
def hyperedgesTrain(X_train, Y_train):
deephyperedges_transductive_model.load_weights((('models/' + dataset_name) + '/deephyperedges_transductive_model.h5'))
history = deephyperedges_transductive_model.fit(X_train, Y_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_split=0, verbose=0)... |
def MLPTrain(X_MLP_transductive_train, Y_MLP_transductive_train):
MLP_transductive_model.load_weights((('models/' + dataset_name) + '/MLP_transductive_model.h5'))
history = MLP_transductive_model.fit(X_MLP_transductive_train, Y_MLP_transductive_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, va... |
def DeepSetsTrain(X_deepset_transductive_train, Y_deepset_transductive_train):
deepsets_transductive_model.load_weights((('models/' + dataset_name) + '/deepsets_transductive_model.h5'))
history = deepsets_transductive_model.fit(X_deepset_transductive_train, Y_deepset_transductive_train, epochs=num_epochs, bat... |
def testModel(model, X_tst, Y_tst):
from sklearn.metrics import classification_report, accuracy_score
target_names = target_names = ['Type-1 Diabetes', 'Type-2 Diabetes', 'Type-3 Diabetes']
y_pred = model.predict(X_tst, batch_size=16, verbose=0)
finals_pred = []
finals_test = []
for p in y_pre... |
def RunAllTests(percentTraining, num_times=10):
for i in range(num_times):
print('percent: ', percentTraining, ', iteration: ', (i + 1), ', model: deep hyperedges')
(X, Y) = getTrainingData()
(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, train_size=percentTraining, test_size=... |
def smooth(scalars, weight):
last = scalars[0]
smoothed = list()
for point in scalars:
smoothed_val = ((last * weight) + ((1 - weight) * point))
smoothed.append(smoothed_val)
last = smoothed_val
return smoothed
|
def plot(deephyperedges_directory, MLP_directory, deepsets_directory, metric, dataset):
dhe_metrics = pd.read_csv(deephyperedges_directory)
x = []
y = []
for (index, row) in dhe_metrics.iterrows():
x.append(float(row['Step']))
y.append(float(row['Value']))
mlp_metrics = pd.read_csv... |
def plotAll(dataset):
metric = 'run-.-tag-categorical_accuracy.csv'
deephyperedges_directory = ((('images/paper/' + dataset) + '/deephyperedges/') + metric)
MLP_directory = ((('images/paper/' + dataset) + '/MLP/') + metric)
deepsets_directory = ((('images/paper/' + dataset) + '/deepsets/') + metric)
... |
def iter_graph(root, callback):
queue = [root]
seen = set()
while queue:
fn = queue.pop()
if (fn in seen):
continue
seen.add(fn)
for (next_fn, _) in fn.next_functions:
if (next_fn is not None):
queue.append(next_fn)
callback(f... |
def register_hooks(var):
fn_dict = {}
def hook_cb(fn):
def register_grad(grad_input, grad_output):
fn_dict[fn] = grad_input
fn.register_hook(register_grad)
iter_graph(var.grad_fn, hook_cb)
def is_bad_grad(grad_output):
grad_output = grad_output.data
retur... |
class Checkpoints():
def __init__(self, args):
self.dir_save = args.save
self.dir_load = args.resume
if (os.path.isdir(self.dir_save) == False):
os.makedirs(self.dir_save)
def latest(self, name):
if (name == 'resume'):
if (self.dir_load == None):
... |
class Dataloader():
def __init__(self, args):
self.args = args
self.loader_input = args.loader_input
self.loader_label = args.loader_label
self.split_test = args.split_test
self.split_train = args.split_train
self.dataset_test_name = args.dataset_test
self.... |
class FileList(data.Dataset):
def __init__(self, ifile, lfile=None, split_train=1.0, split_test=0.0, train=True, transform_train=None, transform_test=None, loader_input=loaders.loader_image, loader_label=loaders.loader_torch):
self.ifile = ifile
self.lfile = lfile
self.train = train
... |
def is_image_file(filename):
return any((filename.endswith(extension) for extension in IMG_EXTENSIONS))
|
def make_dataset(classlist, labellist=None):
images = []
labels = []
classes = utils.readtextfile(ifile)
classes = [x.rstrip('\n') for x in classes]
classes.sort()
for i in len(classes):
for fname in os.listdir(classes[i]):
if is_image_file(fname):
label = {... |
class FolderList(data.Dataset):
def __init__(self, ifile, lfile=None, split_train=1.0, split_test=0.0, train=True, transform_train=None, transform_test=None, loader_input=loaders.loader_image, loader_label=loaders.loader_torch):
(imagelist, labellist) = make_dataset(ifile, lfile)
if (len(imagelis... |
def loader_image(path):
return Image.open(path).convert('RGB')
|
def loader_torch(path):
return torch.load(path)
|
def loader_numpy(path):
return np.load(path)
|
class Classification():
def __init__(self, topk=(1,)):
self.topk = topk
def forward(self, output, target):
'Computes the precision@k for the specified values of k'
maxk = max(self.topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
p... |
class Classification(nn.Module):
def __init__(self):
super(Classification, self).__init__()
self.loss = nn.CrossEntropyLoss()
def forward(self, input, target):
loss = self.loss(input, target)
return loss
|
class Regression(nn.Module):
def __init__(self):
super(Regression, self).__init__()
self.loss = nn.MSELoss()
def forward(self, input, target):
loss = self.loss.forward(input, target)
return loss
|
def weights_init(m):
if isinstance(m, nn.Conv2d):
n = ((m.kernel_size[0] * m.kernel_size[1]) * m.out_channels)
m.weight.data.normal_(0, math.sqrt((2.0 / n)))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
|
class Model():
def __init__(self, args):
self.cuda = args.cuda
self.nfilters = args.nfilters
self.nclasses = args.nclasses
self.nchannels = args.nchannels
self.nblocks = args.nblocks
self.nlayers = args.nlayers
self.level = args.level
self.nchannels... |
class NoiseLayer(nn.Module):
def __init__(self, in_planes, out_planes, level):
super(NoiseLayer, self).__init__()
self.noise = torch.randn(1, in_planes, 1, 1)
self.level = level
self.layers = nn.Sequential(nn.ReLU(True), nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1), n... |
class NoiseModel(nn.Module):
def __init__(self, nblocks, nlayers, nchannels, nfilters, nclasses, level):
super(NoiseModel, self).__init__()
self.num = nfilters
self.level = level
layers = []
layers.append(NoiseLayer(3, nfilters, self.level))
for i in range(1, nlaye... |
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.