repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
imaging_MLPs
imaging_MLPs-master/compressed_sensing/networks/vision_transformer.py
''' This code is modified from https://github.com/facebookresearch/convit. To adapt the vit/convit to image reconstruction, variable input sizes, and patch sizes for both spatial dimensions. ''' import torch import torch.nn as nn from functools import partial import torch.nn.functional as F from timm.models.helpers im...
15,082
39.007958
186
py
imaging_MLPs
imaging_MLPs-master/compressed_sensing/networks/recon_net.py
import torch.nn as nn import torch.nn.functional as F from math import ceil, floor from .unet import Unet from .vision_transformer import VisionTransformer class ReconNet(nn.Module): def __init__(self, net): super().__init__() self.net = net def pad(self, x): _, _, h, w = x.shape ...
1,932
25.847222
90
py
imaging_MLPs
imaging_MLPs-master/compressed_sensing/networks/unet.py
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import torch from torch import nn from torch.nn import functional as F class Unet(nn.Module): """ PyTorch implementation of a U-Net...
5,979
31.677596
88
py
imaging_MLPs
imaging_MLPs-master/compressed_sensing/networks/__init__.py
from .recon_net import ReconNet from .vision_transformer import VisionTransformer from .img2img_mixer import Img2Img_Mixer from .unet import Unet
146
28.4
49
py
imaging_MLPs
imaging_MLPs-master/untrained/networks/original_mixer.py
import torch import torch.nn as nn from torch.nn import init import torch.nn.init as init import einops from einops.layers.torch import Rearrange from einops import rearrange class PatchEmbeddings(nn.Module): def __init__( self, patch_size: int, hidden_dim: int, channels: int ...
3,674
26.840909
93
py
imaging_MLPs
imaging_MLPs-master/untrained/networks/img2img_mixer.py
import torch import torch.nn as nn from torch.nn import init import torch.nn.init as init import einops from einops.layers.torch import Rearrange from einops import rearrange class PatchEmbedding(nn.Module): def __init__( self, patch_size: int, embed_dim: int, channels: int ...
3,618
27.054264
127
py
imaging_MLPs
imaging_MLPs-master/untrained/networks/vit.py
''' This code is modified from https://github.com/facebookresearch/convit. To adapt the vit/convit to image reconstruction, variable input sizes, and patch sizes for both spatial dimensions. ''' import torch import torch.nn as nn from functools import partial import torch.nn.functional as F from timm.models.helpers im...
15,082
39.007958
186
py
imaging_MLPs
imaging_MLPs-master/untrained/networks/recon_net.py
import torch.nn as nn import torch.nn.functional as F from math import ceil, floor class ReconNet(nn.Module): def __init__(self, net): super().__init__() self.net = net def pad(self, x): _, _, h, w = x.shape hp, wp = self.net.patch_size f1 = ( (wp - w % wp) % wp ) / 2 ...
810
26.033333
90
py
imaging_MLPs
imaging_MLPs-master/untrained/networks/unet.py
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import torch from torch import nn from torch.nn import functional as F class Unet(nn.Module): """ PyTorch implementation of a U-Net ...
5,981
32.79661
88
py
imaging_MLPs
imaging_MLPs-master/untrained/networks/__init__.py
from .img2img_mixer import * from .original_mixer import * from .unet import * from .recon_net import ReconNet from .vit import VisionTransformer
146
23.5
34
py
subgraph-counts-hoeffding
subgraph-counts-hoeffding-main/estimate_N.py
#Download the data and compute the lower bound for N from Corollary 5 of our paper. import sys import math import argparse import pandas as pd import numpy as np parser=argparse.ArgumentParser() parser.add_argument("--h", type=int, help="number of vertices in H") parser.add_argument("--i_T", type=int, help="number of ...
2,501
42.894737
188
py
conker
conker-main/driver.py
""" Copyright (C) 2021 Gebri Mishtaku This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope ...
3,468
28.649573
74
py
conker
conker-main/calibrate.py
""" Copyright (C) 2021 Gebri Mishtaku This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope ...
10,318
30.750769
83
py
conker
conker-main/src/parser.py
""" Copyright (C) 2021 Gebri Mishtaku This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope ...
7,093
46.932432
88
py
conker
conker-main/src/centerfinder.py
""" Copyright (C) 2021 Gebri Mishtaku This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope ...
18,655
32.67509
105
py
conker
conker-main/src/utils.py
""" Copyright (C) 2020 Gebri Mishtaku This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope ...
4,645
34.19697
93
py
conker
conker-main/src/correlator.py
""" Copyright (C) 2021 Gebri Mishtaku This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope ...
14,519
28.156627
84
py
conker
conker-main/src/plotter.py
import numpy as np import matplotlib.pyplot as plt plt.rc('figure', figsize=[9,9]) plt.rc('font', family='serif') plt.rc('axes', titlesize=18) plt.rc('axes', labelsize=12) plt.rc('xtick', top=True) plt.rc('xtick.minor', visible=True) plt.rc('ytick', right=True) plt.rc('ytick.minor', visible=True) def _plot_slice(cf,...
3,772
31.525862
83
py
conker
conker-main/src/kernel.py
""" Copyright (C) 2021 Gebri Mishtaku This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope ...
11,022
37.010345
93
py
DeepIR
DeepIR-main/demo.py
#!/usr/bin/env python import os import sys from pprint import pprint # Pytorch requires blocking launch for proper working if sys.platform == 'win32': os.environ['CUDA_LAUNCH_BLOCKING'] = '1' import numpy as np from scipy import io import torch import torch.nn torch.backends.cudnn.enabled = True torch.backends...
2,636
31.555556
80
py
DeepIR
DeepIR-main/modules/losses.py
#!/usr/bin/env python import torch class TVNorm(): def __init__(self, mode='l1'): self.mode = mode def __call__(self, img): grad_x = img[..., 1:, 1:] - img[..., 1:, :-1] grad_y = img[..., 1:, 1:] - img[..., :-1, 1:] if self.mode == 'isotropic': #return torc...
1,586
30.117647
80
py
DeepIR
DeepIR-main/modules/utils.py
#!/usr/bin/env python ''' Miscellaneous utilities that are extremely helpful but cannot be clubbed into other modules. ''' import torch # Scientific computing import numpy as np import scipy.linalg as lin from scipy import io # Plotting import cv2 import matplotlib.pyplot as plt def nextpow2(x): ''' ...
6,530
21.996479
85
py
DeepIR
DeepIR-main/modules/dataset.py
#!/usr/bin/env python import os import sys import tqdm import pdb import math import configparser import numpy as np import torch from torch import nn import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset from PIL import Image from torchvision.transforms import Resize, Compose, ToTensor, ...
7,382
27.287356
81
py
DeepIR
DeepIR-main/modules/thermal.py
#!/usr/bin/env python ''' Routines for dealing with thermal images ''' import tqdm import copy import cv2 import numpy as np from skimage.metrics import structural_similarity as ssim_func import torch import kornia import torch.nn.functional as F import utils import losses import motion import deep_prior def ...
21,820
37.485009
84
py
DeepIR
DeepIR-main/modules/motion.py
#!/usr/bin/env python ''' Subroutines for estimating motion between images ''' import os import sys import tqdm import pdb import math import numpy as np from scipy import linalg from scipy import interpolate import torch from torch import nn import torch.nn.functional as F from torch.utils.data import DataLoad...
23,853
33.772595
137
py
DeepIR
DeepIR-main/modules/deep_prior.py
#!/usr/bin/env ''' One single file for all things Deep Image Prior ''' import os import sys import tqdm import pdb import numpy as np import torch from torch import nn import torchvision import cv2 from dmodels.skip import skip from dmodels.texture_nets import get_texture_nets from dmodels.resnet import ResNet...
8,713
33.995984
138
py
DeepIR
DeepIR-main/modules/dmodels/skip.py
import torch import torch.nn as nn from .common import * def skip( num_input_channels=2, num_output_channels=3, num_channels_down=[16, 32, 64, 128, 128], num_channels_up=[16, 32, 64, 128, 128], num_channels_skip=[4, 4, 4, 4, 4], filter_size_down=3, filter_size_up=3, filter_skip_size=1, ...
3,744
36.079208
144
py
DeepIR
DeepIR-main/modules/dmodels/resnet.py
import torch import torch.nn as nn from numpy.random import normal from numpy.linalg import svd from math import sqrt import torch.nn.init from .common import * class ResidualSequential(nn.Sequential): def __init__(self, *args): super(ResidualSequential, self).__init__(*args) def forward(self, x): ...
2,943
29.350515
195
py
DeepIR
DeepIR-main/modules/dmodels/downsampler.py
import numpy as np import torch import torch.nn as nn class Downsampler(nn.Module): ''' http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf ''' def __init__(self, n_planes, factor, kernel_type, phase=0, kernel_width=None, support=None, sigma=None, preserve_size=False): ...
5,379
30.83432
129
py
DeepIR
DeepIR-main/modules/dmodels/dcgan.py
import torch import torch.nn as nn def dcgan(inp=2, ndf=32, num_ups=4, need_sigmoid=True, need_bias=True, pad='zero', upsample_mode='nearest', need_convT = True): layers= [nn.ConvTranspose2d(inp, ndf, kernel_size=3, stride=1, padding=0, bias=False), nn.BatchNorm2d(ndf), ...
1,244
35.617647
112
py
DeepIR
DeepIR-main/modules/dmodels/texture_nets.py
import torch import torch.nn as nn from .common import * normalization = nn.BatchNorm2d def conv(in_f, out_f, kernel_size, stride=1, bias=True, pad='zero'): if pad == 'zero': return nn.Conv2d(in_f, out_f, kernel_size, stride, padding=(kernel_size - 1) / 2, bias=bias) elif pad == 'reflection': ...
2,315
27.95
146
py
DeepIR
DeepIR-main/modules/dmodels/common.py
import torch import torch.nn as nn import numpy as np from .downsampler import Downsampler def add_module(self, module): self.add_module(str(len(self) + 1), module) torch.nn.Module.add = add_module class Concat(nn.Module): def __init__(self, dim, *args): super(Concat, self).__init__() sel...
3,531
27.483871
128
py
DeepIR
DeepIR-main/modules/dmodels/unet.py
import torch.nn as nn import torch import torch.nn as nn import torch.nn.functional as F from .common import * class ListModule(nn.Module): def __init__(self, *args): super(ListModule, self).__init__() idx = 0 for module in args: self.add_module(str(idx), module) id...
7,324
36.953368
164
py
DeepIR
DeepIR-main/modules/dmodels/__init__.py
from .skip import skip from .texture_nets import get_texture_nets from .resnet import ResNet from .unet import UNet import torch.nn as nn def get_net(input_depth, NET_TYPE, pad, upsample_mode, n_channels=3, act_fun='LeakyReLU', skip_n33d=128, skip_n33u=128, skip_n11=4, num_scales=5, downsample_mode='stride'): if ...
1,639
50.25
172
py
rude-carnie
rude-carnie-master/export.py
import tensorflow as tf from model import select_model, get_checkpoint from utils import RESIZE_AOI, RESIZE_FINAL from tensorflow.python.framework import graph_util from tensorflow.contrib.learn.python.learn.utils import export from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.pyt...
5,970
43.559701
118
py
rude-carnie
rude-carnie-master/detect.py
import numpy as np import cv2 FACE_PAD = 50 class ObjectDetector(object): def __init__(self): pass def run(self, image_file): pass # OpenCV's cascade object detector class ObjectDetectorCascadeOpenCV(ObjectDetector): def __init__(self, model_name, basename='frontal-face', tgtdir='.', min_...
2,287
39.140351
112
py
rude-carnie
rude-carnie-master/yolodetect.py
from detect import ObjectDetector import numpy as np import tensorflow as tf import cv2 class YOLOBase(ObjectDetector): def __init__(self): pass def _conv_layer(self, idx, inputs, filters, size, stride): channels = inputs.get_shape()[3] weight = tf.Variable(tf.truncated_normal([size, ...
12,603
43.380282
117
py
rude-carnie
rude-carnie-master/filter_by_face.py
import numpy as np import tensorflow as tf import os import cv2 import time import sys from utils import * import csv # YOLO tiny #python fd.py --filename /media/dpressel/xdata/insights/converted/ --face_detection_model weights/YOLO_tiny.ckpt --face_detection_type yolo_tiny --target yolo.csv # CV2 #python fd.py --fi...
2,721
34.350649
177
py
rude-carnie
rude-carnie-master/utils.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import six.moves from datetime import datetime import sys import math import time from data import inputs, standardize_image import numpy as np import tensorflow as tf from detect import * import re RESIZE_AOI...
5,920
32.078212
90
py
rude-carnie
rude-carnie-master/model.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import time import os import numpy as np import tensorflow as tf from data import distorted_inputs import re from tensorflow.contrib.layers import * from tensorflow.contrib.slim.p...
8,852
44.168367
144
py
rude-carnie
rude-carnie-master/data.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import os import numpy as np import tensorflow as tf from distutils.version import LooseVersion VERSION_GTE_0_12_0 = LooseVersion(tf.__version__) >= LooseVersion('0.12.0') # Nam...
8,764
36.139831
92
py
rude-carnie
rude-carnie-master/preproc.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange from datetime import datetime import os import random import sys import threading import numpy as np import tensorflow as tf import json RESIZE_HEIGHT = 256 RESIZE_WIDTH = 256 tf....
12,580
38.071429
137
py
rude-carnie
rude-carnie-master/dlibdetect.py
from detect import ObjectDetector import dlib import cv2 FACE_PAD = 50 class FaceDetectorDlib(ObjectDetector): def __init__(self, model_name, basename='frontal-face', tgtdir='.'): self.tgtdir = tgtdir self.basename = basename self.detector = dlib.get_frontal_face_detector() self.pr...
1,853
36.836735
112
py
rude-carnie
rude-carnie-master/eval.py
""" At each tick, evaluate the latest checkpoint against some validation data. Or, you can run once by passing --run_once. OR, you can pass a --requested_step_seq of comma separated checkpoint #s that already exist that it can run in a row. This program expects a training base directory with the data, and md.json fil...
8,021
40.138462
165
py
rude-carnie
rude-carnie-master/train.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange from datetime import datetime import time import os import numpy as np import tensorflow as tf from data import distorted_inputs from model import select_model import json import re...
7,702
38.911917
130
py
rude-carnie
rude-carnie-master/guess.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import math import time from data import inputs import numpy as np import tensorflow as tf from model import select_model, get_checkpoint from utils import * import os import json ...
8,091
37.903846
136
py
AdaptiveGCL
AdaptiveGCL-main/Params.py
import argparse def ParseArgs(): parser = argparse.ArgumentParser(description='Model Params') parser.add_argument('--lr', default=1e-3, type=float, help='learning rate') parser.add_argument('--batch', default=4096, type=int, help='batch size') parser.add_argument('--tstBat', default=256, type=int, help='number of ...
1,788
62.892857
107
py
AdaptiveGCL
AdaptiveGCL-main/DataHandler.py
import pickle import numpy as np from scipy.sparse import csr_matrix, coo_matrix, dok_matrix from Params import args import scipy.sparse as sp from Utils.TimeLogger import log import torch as t import torch.utils.data as data import torch.utils.data as dataloader class DataHandler: def __init__(self): if args.data ...
3,205
29.245283
103
py
AdaptiveGCL
AdaptiveGCL-main/Main.py
import torch import Utils.TimeLogger as logger from Utils.TimeLogger import log from Params import args from Model import Model, vgae_encoder, vgae_decoder, vgae, DenoisingNet from DataHandler import DataHandler import numpy as np from Utils.Utils import calcRegLoss, pairPredict import os from copy import deepcopy impo...
6,846
29.9819
143
py
AdaptiveGCL
AdaptiveGCL-main/Model.py
from torch import nn import torch.nn.functional as F import torch from Params import args from copy import deepcopy import numpy as np import math import scipy.sparse as sp from Utils.Utils import contrastLoss, calcRegLoss, pairPredict import time import torch_sparse init = nn.init.xavier_uniform_ class Model(nn.Modu...
11,377
29.180371
126
py
AdaptiveGCL
AdaptiveGCL-main/Utils/TimeLogger.py
import datetime logmsg = '' timemark = dict() saveDefault = False def log(msg, save=None, oneline=False): global logmsg global saveDefault time = datetime.datetime.now() tem = '%s: %s' % (time, msg) if save != None: if save: logmsg += tem + '\n' elif saveDefault: logmsg += tem + '\n' if oneline: print(...
476
16.666667
43
py
AdaptiveGCL
AdaptiveGCL-main/Utils/Utils.py
import torch as t import torch.nn.functional as F def innerProduct(usrEmbeds, itmEmbeds): return t.sum(usrEmbeds * itmEmbeds, dim=-1) def pairPredict(ancEmbeds, posEmbeds, negEmbeds): return innerProduct(ancEmbeds, posEmbeds) - innerProduct(ancEmbeds, negEmbeds) def calcRegLoss(model): ret = 0 for W in model.par...
694
29.217391
79
py
wcep-mds-dataset
wcep-mds-dataset-master/experiments/summarizer.py
import utils from nltk import word_tokenize, bigrams from sent_splitter import SentenceSplitter from data import Sentence, Article class Summarizer: def _deduplicate(self, sents): seen = set() uniq_sents = [] for s in sents: if s.text not in seen: seen.add(s.te...
2,737
30.471264
74
py
wcep-mds-dataset
wcep-mds-dataset-master/experiments/baselines.py
import utils import random import collections import numpy as np import networkx as nx import warnings from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from sklearn.cluster import MiniBatchKMeans from summarizer import Summarizer warnings.filterwarning...
11,786
33.364431
80
py
wcep-mds-dataset
wcep-mds-dataset-master/experiments/evaluate.py
import argparse import collections import numpy as np import utils from newsroom.analyze.rouge import ROUGE_L, ROUGE_N def print_mean(results, rouge_types): for rouge_type in rouge_types: precs = results[rouge_type]['p'] recalls = results[rouge_type]['r'] fscores = results[rouge_type]['f']...
3,425
29.589286
78
py
wcep-mds-dataset
wcep-mds-dataset-master/experiments/utils.py
import json import gzip import pickle def read_lines(path): with open(path) as f: for line in f: yield line def read_json(path): with open(path) as f: object = json.loads(f.read()) return object def write_json(object, path): with open(path, 'w') as f: f.write(js...
1,835
20.6
60
py
wcep-mds-dataset
wcep-mds-dataset-master/experiments/oracles.py
import argparse from collections import Counter from nltk import word_tokenize, ngrams from summarizer import Summarizer import utils def compute_rouge_n(hyp, ref, rouge_n=1, tokenize=True): hyp_words = word_tokenize(hyp) if tokenize else hyp ref_words = word_tokenize(ref) if tokenize else ref if rouge_n...
8,710
33.027344
78
py
wcep-mds-dataset
wcep-mds-dataset-master/experiments/data.py
import string from spacy.lang.en import STOP_WORDS STOP_WORDS |= set(string.punctuation) class Article: def __init__(self, title, sents): self.title = title self.sents = sents def words(self): if self.title is None: return [w for s in self.sents for w in s.words] e...
724
25.851852
74
py
wcep-mds-dataset
wcep-mds-dataset-master/experiments/sent_splitter.py
import re from nltk import sent_tokenize class SentenceSplitter: """ NLTK sent_tokenize + some fixes for common errors in news articles. """ def unglue(self, x): g = x.group(0) fixed = '{} {}'.format(g[0], g[1]) return fixed def fix_glued_sents(self, text): return ...
766
25.448276
71
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_reproduction/extract_cc_articles.py
import argparse import pathlib import logging import json import subprocess import multiprocessing import newspaper import sys import time import utils from warcio.archiveiterator import ArchiveIterator def read_warc_gz(path): with open(path, 'rb') as f: for record in ArchiveIterator(f): # rec...
6,569
29.137615
78
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_reproduction/combine_and_split.py
import argparse import json import pathlib import shutil import utils from collections import defaultdict def get_article_to_cluster_mappings(clusters): url_to_cluster_idxs = defaultdict(list) id_to_cluster_idx = {} for i, c in enumerate(clusters): for a in c['wcep_articles']: url_to_c...
5,119
32.907285
89
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_reproduction/utils.py
import json def read_lines(path): with open(path) as f: for line in f: yield line.strip() def read_jsonl(path): with open(path) as f: for line in f: yield json.loads(line) def write_jsonl(items, path, mode='a'): assert mode in ['w', 'a'] lines = [json.dumps(...
421
18.181818
42
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_reproduction/extract_wcep_articles.py
import argparse import multiprocessing import time import pathlib import random import newspaper import json import numpy as np import utils def extract_article(todo_article): url = todo_article['archive_url'] extracted = newspaper.Article(url) try: extracted.download() extracted.parse() ...
3,803
25.601399
74
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_generation/step5_combine_dataset.py
import argparse from general import utils def load_urls(path): url_to_arc = {} arc_to_url = {} with open(path) as f: for line in f: parts = line.split() if len(parts) == 2: url, arc_url = parts url_to_arc[url] = arc_url arc_to...
1,505
25.421053
65
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_generation/step2_process_wcep_html.py
import argparse import datetime import calendar import pathlib import collections import arrow import json import uuid from bs4 import BeautifulSoup def make_month_to_int(): month_to_int = {} for i, month in enumerate(calendar.month_name): if i > 0: month_to_int[month] = i return month...
6,015
29.231156
80
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_generation/step4_scrape_sources.py
import argparse import multiprocessing import json import os import time import pathlib import random import newspaper import json import numpy as np def scrape_article(url): a = newspaper.Article(url) error = None try: a.download() a.parse() if a.publish_date is None: ...
3,582
23.710345
79
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_generation/step1_store_wcep_html.py
import requests import argparse import pathlib from bs4 import BeautifulSoup ROOT_URL = 'https://en.wikipedia.org/wiki/Portal:Current_events' def extract_month_urls(): html = requests.get(ROOT_URL).text soup = BeautifulSoup(html, 'html.parser') e = soup.find('div', class_='NavContent hlist') urls = [...
1,096
26.425
80
py
wcep-mds-dataset
wcep-mds-dataset-master/dataset_generation/step3_snapshot_source_urls.py
import argparse import savepagenow import json import os import random import time from requests.exceptions import ConnectionError def read_jsonl(path): with open(path) as f: for line in f: yield json.loads(line) def write_jsonl(items, path, batch_size=100, override=True): if override: ...
2,971
27.576923
79
py
SARS-CoV-2_origins
SARS-CoV-2_origins-master/scripts/python/ACE2.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 5 12:49:25 2020 @author: Erwan Sallard erwan.sallard@ens.psl.eu """ '''goal: this program compares the ACE2 proteins of various organisms with a reference ACE2 (one of the sequences in the alignment) and identify their level of similarity on the...
2,773
33.246914
79
py
SARS-CoV-2_origins
SARS-CoV-2_origins-master/scripts/python/detection_insertion.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 26 14:41:12 2020 @author: erwan """ import sys alignment=sys.argv[1] reference=sys.argv[2] filename=sys.argv[3] '''identifies the insertions in the sequence "reference" out of a multiple alignment file in .clw format. Is considered an insertion ev...
2,581
32.102564
75
py
SARS-CoV-2_origins
SARS-CoV-2_origins-master/scripts/python/mutation_analyser.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 25 21:38:57 2020 @author: erwan """ import sys import matplotlib.pyplot as plt from Bio import pairwise2 from Bio.Seq import Seq from Bio.SubsMat import MatrixInfo as matlist ''' This program compares two nucleotide sequences, identifies indels, s...
4,657
38.142857
102
py
RG
RG-master/Image Classification/main.py
from __future__ import print_function import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn from torch.autograd import Variable import torchvision import torchvision.transforms as transforms import os import argparse import random from re...
4,105
30.343511
109
py
RG
RG-master/Image Classification/resnet.py
'''ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable cla...
3,941
32.982759
102
py
RG
RG-master/Image Classification/utils.py
import os import sys import time term_width = 5 TOTAL_BAR_LENGTH = 20. last_time = time.time() begin_time = last_time def progress_bar(current, total, msg=None): global last_time, begin_time if current == 0: begin_time = time.time() # Reset for new bar. cur_len = int(TOTAL_BAR_LENGTH*current/tota...
2,068
23.927711
64
py
RG
RG-master/pix2pix/pix2pix.py
import argparse import os import numpy as np import math import itertools import time import datetime import sys import random import torchvision.transforms as transforms from torchvision.utils import save_image from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variab...
7,224
36.827225
123
py
RG
RG-master/pix2pix/datasets.py
import glob import random import os import numpy as np from torch.utils.data import Dataset from PIL import Image import torchvision.transforms as transforms class ImageDataset(Dataset): def __init__(self, root, transforms_=None, mode='train'): self.transform = transforms.Compose(transforms_) sel...
1,056
28.361111
85
py
RG
RG-master/pix2pix/models.py
import torch.nn as nn import torch.nn.functional as F import torch def weights_init_normal(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: torch.nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm2d') != -1: torch.nn.init.normal_(m.weight.data, 1.0...
4,289
32.515625
81
py
RG
RG-master/Semantic Segmentation/model.py
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch import numpy as np affine_par = True import torch.nn.functional as F def outS(i): i = int(i) i = (i+1)/2 i = int(np.ceil((i+1)/2.0)) i = (i+1)/2 return i def conv3x3(in_planes, out_planes, stride=1): "3x3 ...
11,339
36.549669
139
py
RG
RG-master/Semantic Segmentation/train.py
import datetime import os import random import time from math import sqrt import torchvision.transforms as standard_transforms import torchvision.utils as vutils # from tensorboard import SummaryWriter from torch import optim from torch.autograd import Variable from torch.backends import cudnn from torch.optim.lr_sched...
9,955
38.19685
219
py
metacorps-nn
metacorps-nn-master/different_layers_experiment.py
import sys import pandas as pd from modelrun import ModelRun verbose = True n_nodes = 500 # Keeping a ModelRun allows us to not have to re-load GoogleNews model. rows = [] # Used to build data frame and latex table. w2v_model_loc='GoogleNews-vectors-negative300.bin' if len(sys.argv) > 1: run_directory = sys.a...
1,460
28.22
105
py
metacorps-nn
metacorps-nn-master/test_util.py
from util import get_window from nose.tools import eq_ def test_get_window(): word = 'attack' window_size = 5 # Test when we have enough space on both sides for full window. text = 'he has to go on the attack if he wants to win the debate' window = get_window(text, word, window_size) eq_(win...
1,256
38.28125
99
py
metacorps-nn
metacorps-nn-master/modelrun.py
''' ''' from uuid import uuid4 # Command-line interface: read it CLIck. import click import numpy as np import os import tensorflow as tf # See https://radimrehurek.com/gensim/models/keyedvectors.html import gensim from eval import Eval from model import train_network from util import MetaphorData # WORKFLOW # 1....
5,085
31.602564
81
py
metacorps-nn
metacorps-nn-master/model.py
''' Following Do Dinh, E.-L., & Gurevych, I. (2016) using TensorFlow. Do Dinh, E.-L., & Gurevych, I. (2016). Token-Level Metaphor Detection using Neural Networks. Proceedings of the Fourth Workshop on Metaphor in NLP, (June), 28–33. Author: Matthew A. Turner Date: 2017-12-11 ''' import tensorflow as tf def ...
5,240
35.908451
77
py
metacorps-nn
metacorps-nn-master/util.py
''' Utilities for training a neural network for automated identification of metaphorical violence. Author: Matthew A. Turner Date: 2017-11-21 ''' import itertools import numpy as np import pandas as pd import random import warnings def get_window(text, focal_token, window_size): ''' Given some text and a tok...
11,959
34.176471
79
py
metacorps-nn
metacorps-nn-master/prepare_csv_input.py
''' Export script to create tabular dataset from the metacorps web app's MongoDB database. A mongodump of this database is available at http://metacorps.io/static/data/nov-15-2017-metacorps-dump.zip (594M) ''' import numpy as np import pandas as pd from nltk.tokenize import RegexpTokenizer from pymongo import MongoCli...
2,717
26.18
77
py
metacorps-nn
metacorps-nn-master/eval.py
''' Code to evaluate a particular trained network. Think about formatting results here well to be tables in the paper. ''' import sklearn.metrics as skmetrics from collections import Counter from util import get_window class Eval: ''' Methods to evaluate different models. ''' def __init__(self, test...
3,028
32.285714
79
py
metacorps-nn
metacorps-nn-master/n_layers_experiment.py
import sys import pandas as pd from modelrun import ModelRun verbose = True n_nodes = 500 # Keeping a ModelRun allows us to not have to re-load GoogleNews model. rows = [] # Used to build data frame and latex table. w2v_model_loc='GoogleNews-vectors-negative300.bin' if len(sys.argv) > 1: run_directory = sys.a...
1,344
27.020833
71
py
CD-Flow
CD-Flow-main/main.py
import torch from trainnet import trainNet import pandas as pd import argparse def parse_config(): parser = argparse.ArgumentParser() parser.add_argument("--seed", type=int, default=100) parser.add_argument("--resume_path", type=str, default=None) parser.add_argument("--learning_rate", type=float, defa...
3,377
48.676471
175
py
CD-Flow
CD-Flow-main/test.py
import time from EMA import EMA import torch from torch.utils.data import DataLoader from model import CDFlow from DataLoader import CD_128 from coeff_func import * import os from loss import createLossAndOptimizer from torch.autograd import Variable import torchvision import torch.autograd as autograd from function im...
4,109
41.8125
117
py
CD-Flow
CD-Flow-main/flow.py
import torch from torch import nn from torch.nn import functional as F from math import log, pi, exp import numpy as np from scipy import linalg as la logabs = lambda x: torch.log(torch.abs(x)) class ActNorm(nn.Module): def __init__(self, in_channel, logdet=True): super().__init__() self.loc = nn....
10,847
28.720548
88
py
CD-Flow
CD-Flow-main/DataLoader.py
import os import torch import random import numpy as np from torch.utils.data import Dataset from PIL import Image from torchvision import transforms import torchvision class CD_128(Dataset): def __init__(self, jnd_info, root_dir, test=False): self.ref_name = jnd_info[:, 0] self.test_name = jnd_inf...
1,425
30
81
py
CD-Flow
CD-Flow-main/loss.py
import torch import numpy as np import torch.optim as optim import torch.nn as nn import torch.nn.functional as F def createLossAndOptimizer(net, learning_rate, scheduler_step, scheduler_gamma): loss = LossFunc() # optimizer = optim.Adam([{'params': net.parameters(), 'lr':learning_rate}], lr = learning_rate, w...
909
34
119
py
CD-Flow
CD-Flow-main/model.py
import math import time import torch import torch.nn as nn from flow import * import os class CDFlow(nn.Module): def __init__(self): super(CDFlow, self).__init__() self.glow = Glow(3, 8, 6, affine=True, conv_lu=True) def coordinate_transform(self, x_hat, rev=False): if not rev: ...
3,702
47.090909
122
py
CD-Flow
CD-Flow-main/EMA.py
class EMA(): def __init__(self, model, decay): self.model = model self.decay = decay self.shadow = {} self.backup = {} def register(self): for name, param in self.model.named_parameters(): if param.requires_grad: self.shadow[name] = param...
1,138
32.5
94
py
CD-Flow
CD-Flow-main/function.py
import shutil import random import torch import numpy as np def setup_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True def copy_codes(trainpath1,trainpath2,trainpath3,trainpath4, path1,path2,path3,...
484
25.944444
85
py
CD-Flow
CD-Flow-main/coeff_func.py
from cgi import print_form import numpy as np import pandas as pd from scipy.stats.stats import pearsonr, spearmanr, kendalltau from scipy.optimize import fmin from math import sqrt from sklearn.metrics import mean_squared_error def logistic(t, x): return 0.5 - (1 / (1 + np.exp(t * x))) def fitfun(t, x): res...
1,583
23
78
py
CD-Flow
CD-Flow-main/trainnet.py
import time from EMA import EMA import torch from torch.utils.data import DataLoader from model import CDFlow from DataLoader import CD_128 from coeff_func import * import os from loss import createLossAndOptimizer from torch.autograd import Variable import torch.autograd as autograd from function import setup_seed, co...
11,783
44.85214
156
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/setup.py
from distutils.core import setup """ install the packages """ setup(name='rl_utils', version='0.0', description='rl utils for the rl algorithms', author='Tianhong Dai', author_email='xxx@xxx.com', url='no', packages=['rl_utils'], )
275
17.4
51
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/arguments.py
import argparse def get_args(): parse = argparse.ArgumentParser() parse.add_argument('--gamma', type=float, default=0.99, help='the discount factor of RL') parse.add_argument('--seed', type=int, default=123, help='the random seeds') parse.add_argument('--env-name', type=str, default='PongNoFrameskip-v4...
2,247
73.933333
129
py
reinforcement-learning-algorithms
reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/utils.py
import numpy as np import random # linear exploration schedule class linear_schedule: def __init__(self, total_timesteps, final_ratio, init_ratio=1.0): self.total_timesteps = total_timesteps self.final_ratio = final_ratio self.init_ratio = init_ratio def get_value(self, timestep): ...
1,621
28.490909
115
py