code
stringlengths
101
5.91M
def test_rnd_paper_count(): rnd_entries = rldb.find_all({'source-title': 'Exploration by Random Network Distillation'}) assert (len(rnd_entries) == (((0 + 6) + 6) + 6))
class FreeModuleAltForm(FreeModuleTensor): def __init__(self, fmodule, degree, name=None, latex_name=None): FreeModuleTensor.__init__(self, fmodule, (0, degree), name=name, latex_name=latex_name, antisym=range(degree), parent=fmodule.dual_exterior_power(degree)) def _repr_(self): if (self._tenso...
def test_nested_ListArray_NumpyArray(): v2a = ak.contents.ListOffsetArray(ak.index.Index64(np.array([0, 1, 4], dtype=np.int64)), ak.contents.listarray.ListArray(ak.index.Index(np.array([999, 4, 100, 1], np.int64)), ak.index.Index(np.array([999, 7, 100, 3, 200], np.int64)), ak.contents.numpyarray.NumpyArray(np.array...
class DBSCAN(ClusterMixin, BaseEstimator): _parameter_constraints: dict = {'eps': [Interval(Real, 0.0, None, closed='neither')], 'min_samples': [Interval(Integral, 1, None, closed='left')], 'metric': [StrOptions((set(_VALID_METRICS) | {'precomputed'})), callable], 'metric_params': [dict, None], 'algorithm': [StrOpt...
class Model(nn.Module): def __init__(self, use_pytorch_checkpoint=False, use_fairseq_checkpoint=False): super().__init__() torch.manual_seed(0) self.use_pytorch_checkpoint = use_pytorch_checkpoint self.ffn = nn.Sequential(nn.Linear(32, 128), nn.Dropout(p=0.5), nn.Linear(128, 32)) ...
def prepro_for_zhang(dataname, split, seed, args): balance = args.balance k = args.k np.random.seed(seed) data = defaultdict(list) label_set = set() with open(os.path.join(args.data_dir, 'TextClassificationDatasets', DATA_DICT[dataname], '{}.csv'.format(split)), 'r') as f: for dp in csv....
_model_architecture('delight_transformer_lm', 'delight_transformer_lm') def base_lm_architecture(args): args.adaptive_input = getattr(args, 'adaptive_input', False) args.adaptive_input_factor = getattr(args, 'adaptive_input_factor', ADAPTIVE_SCALE_FACTOR) args.adaptive_input_cutoff = getattr(args, 'adaptive...
def get_env_info(): run_lambda = run (pip_version, pip_list_output) = get_pip_packages(run_lambda) return SystemEnv(torch_version=torch.__version__, is_debug_build=torch.version.debug, python_version='{}.{}'.format(sys.version_info[0], sys.version_info[1]), is_cuda_available=torch.cuda.is_available(), cuda_...
class DoubleConv(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.double_conv = nn.Sequential(Conv3x3BNReLU(in_channels, out_channels, stride=1), Conv3x3BNReLU(out_channels, out_channels, stride=1)) def forward(self, x): return self.double_conv(x)
class RemBertForMaskedLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def test_ast_resolver_wrong_ti(): import taichi taichi.init() fake_ti = namedtuple('FakeTi', ['kernel']) ti = fake_ti(kernel='fake') node = ast.parse('ti.kernel', mode='eval').body assert (not ASTResolver.resolve_to(node, taichi.kernel, locals()))
def _fit_sag(X, y, eta, alpha, loss, max_iter, rng): if sparse.issparse(X): X = X.toarray() (n_samples, n_features) = X.shape n_vectors = y.shape[1] g = np.empty((n_samples, n_features)) coef_ = np.zeros((n_vectors, n_features)) for i in range(n_samples): p = coef_.dot(X[i]) ...
class RelativeRiskResult(): relative_risk: float exposed_cases: int exposed_total: int control_cases: int control_total: int def confidence_interval(self, confidence_level=0.95): if (not (0 <= confidence_level <= 1)): raise ValueError('confidence_level must be in the interval...
def get_document(document_lines, args): document_state = OntoNotesDocumentState(document_lines[0]) tokenizer = args.tokenizer word_idx = (- 1) orig_word_idx = (- 1) last_speaker = '-' for line in document_lines[1]: row = line.split() sentence_end = (len(row) == 0) if (not...
class genextreme_gen(rv_continuous): def _argcheck(self, c): return np.isfinite(c) def _shape_info(self): return [_ShapeInfo('c', False, ((- np.inf), np.inf), (False, False))] def _get_support(self, c): _b = np.where((c > 0), (1.0 / np.maximum(c, _XMIN)), np.inf) _a = np.wher...
class ZFilter(Filter): def __init__(self, shape, demean=True, destd=True, clip=10.0): self.demean = demean self.destd = destd self.clip = clip self.rs = RunningStat(shape) def __call__(self, x, update=True): if update: self.rs.push(x) if self.demean: ...
_connect.numpy.implements('prod') def _nep_18_impl_prod(a, axis=None, dtype=UNSUPPORTED, out=UNSUPPORTED, keepdims=False, initial=UNSUPPORTED, where=UNSUPPORTED): return prod(a, axis=axis, keepdims=keepdims)
def result_folder(): import sbibm.third_party.kgof.config as config results_path = config.expr_configs['expr_results_path'] return results_path
def unwrap_model(model_wrapper): if hasattr(model_wrapper, 'module'): model = model_wrapper.module else: model = model_wrapper return model
def compute_metrics_on_files(gt, pred, ifhd=True, ifasd=True): def metrics(img_gt, img_pred, ifhd=True, ifasd=True): if (img_gt.ndim != img_pred.ndim): raise ValueError("The arrays 'img_gt' and 'img_pred' should have the same dimension, {} against {}".format(img_gt.ndim, img_pred.ndim)) ...
class ElastodynamicsLinearTSC(ElastodynamicsBasicTSC): name = 'tsc.ed_linear' _parameters = (ElastodynamicsBasicTSC._parameters + [('fred', 'float', 1.0, False, 'Additional step size reduction factor w.r.t. `tsc.ed_basic`.'), ('inc_wait', 'int', 10, False, 'The number of consecutive accepted steps to wait befor...
class Evaluater(BaseTrainer): def __init__(self, model, loss, metrics, config, data_loader): super().__init__(model, loss, metrics, None, config) self.config = config self.data_loader = data_loader self.log_step = config['evaluater'].get('log_step', int(np.sqrt(data_loader.batch_size...
def test_ufunc_isnan_c(): _numpy_output(check_dtype=True) def ufunc_isnan_c(A: dace.complex64[10]): A[0] = np.inf A[1] = np.NaN return np.isnan(A) args = dace.Config.get('compiler', 'cpu', 'args') print(args) if (args.find('-ffast-math') >= 0): new_args = args.replace...
def readJSON(url): response = request.urlopen(url) data = json.loads(response.read()) return data
class GatherRecord(ModelLayer): def __init__(self, model, input_record, name='gather_record', **kwargs): super(GatherRecord, self).__init__(model, name, input_record, **kwargs) assert ('indices' in input_record) assert ('record' in input_record) self.output_schema = schema.NewRecord(...
(scope='function') def function_analysis() -> FunctionAnalysisVisitor: return FunctionAnalysisVisitor()
class Detect(): def __init__(self, nc: int=80, ch: List[int]=(), name: str=''): self.nc = nc self.nl = len(ch) self.reg_max = 16 self.no = (nc + (self.reg_max * 4)) self.feat_sizes = [80, 40, 20] self.stride_sizes = [8, 16, 32] img_size = 640 (nd0, nd1...
class Macaulay2FunctionElement(FunctionElement): def _instancedoc_(self): P = self._obj.parent() r = P.eval('help prepend({0}, select(methods {0}, m->instance({1}, m#1)))'.format(self._name, self._obj._name)) end = r.rfind('\n\nDIV') if (end != (- 1)): r = r[:end] ...
_kl(Uniform, Exponential) def _kl_uniform_exponetial(p, q): result = (((q.rate * (p.high + p.low)) / 2) - ((p.high - p.low) * q.rate).log()) result[(p.low < q.support.lower_bound)] = inf return result
def spawn_3D_maze(map, base_pos=5): blocks = [] for k in range(len(map)): for j in range(len(map[k])): for i in range(len(map[k][j])): item = get_tile(map[k][j][i]) blocks.append(Block(position=Point(x=i, y=(k + 5), z=j), type=item, orientation=NORTH)) CLI...
class TwitterManagerReplyToTweet(VirtualFunctionTool): name = 'TwitterManagerReplyToTweet' summary = 'Reply to a tweet by its ID.' parameters: List[ArgParameter] = [{'name': 'tweet_id', 'type': 'string', 'description': 'The unique identifier of the tweet to reply to.', 'required': True}, {'name': 'content',...
class WatchdogReloaderLoop(ReloaderLoop): def __init__(self, *args, **kwargs): ReloaderLoop.__init__(self, *args, **kwargs) from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler self.observable_paths = set() def _check_modification(filenam...
.parametrize('inspecs', pairwise_inspecs_params()) .parametrize('op', ['logical_and', 'logical_or', 'logical_xor', 'greater', 'greater_equal', 'less', 'less_equal', 'equal', 'not_equal']) def test_pairwise_logical(inspecs, op, nnabla_opts): func = getattr(F, op) fb = FunctionBenchmark(func, inspecs, [], {}, nna...
def is_in_span(index, all_entity_spans): for span in all_entity_spans: if (span[0] <= index < span[1]): return True return False
class OPRAVideoPath(Dataset): def __init__(self, root, split, save_dir, num_gpus): super().__init__() videos = get_opra_videos(root, split) save_dirs = to_affominer_dirs(videos, save_dir) (self.videos, self.save_dirs) = ([], []) for (video, save_dir) in zip(videos, save_dirs)...
class ReverseLSTMLayer(jit.ScriptModule): def __init__(self, cell, *cell_args): super(ReverseLSTMLayer, self).__init__() self.cell = cell(*cell_args) _method def forward(self, input, state): inputs = reverse(input.unbind(0)) outputs = jit.annotate(List[Tensor], []) fo...
def is_model_only_checkpoint(checkpoint): if is_pl_trainer_checkpoint(checkpoint): return ('state_dict' not in checkpoint) else: return ('model' not in checkpoint)
_warnings(category=ConvergenceWarning) def process_single_scan(args, dataset, gt_path: Path, cat_id_to_feature, valid_ids): scan = os.path.splitext(gt_path.name)[0] print(f'Start processing scan = {scan!r}') scan_path = (dataset / scan) scene_pcd = o3d.io.read_point_cloud(str((scan_path / f'{scan}_vh_cl...
class GOT10kVideo(Video): def __init__(self, name, root, video_dir, init_rect, img_names, gt_rect, attr, load_img=False): super(GOT10kVideo, self).__init__(name, root, video_dir, init_rect, img_names, gt_rect, attr, load_img)
def vectorize_sequence(sequence: str, feature_length: int, w2v_model: Word2Vec) -> np.ndarray: vector = np.zeros((feature_length, W2V_VEC_LENGTH)) for (i, word) in enumerate(sequence.split()): if (i >= feature_length): break try: vector[i] = w2v_model.wv[word] exc...
class Benchmark(srdata.SRData): def __init__(self, args, name='', train=True, benchmark=True): super(Benchmark, self).__init__(args, name=name, train=train, benchmark=True) def _set_filesystem(self, dir_data): self.apath = os.path.join(dir_data, 'benchmark', self.name) self.dir_hr = os.p...
(dace.uint32[(H + 1)], dace.uint32[nnz], dace.float32[nnz], dace.float32[W], dace.float32[H]) def spmv(A_row, A_col, A_val, x, b): (_[0:H]) def compute_row(i): (_[A_row[i]:A_row[(i + 1)]]) def compute(j): (a << A_val[j]) (in_x << x[A_col[j]]) (out >> b(1, (lam...
def _combine_images_with_annotations(dataset_name: str, image_root: str, img_datas: Iterable[Dict[(str, Any)]], ann_datas: Iterable[Iterable[Dict[(str, Any)]]]): dataset_dicts = [] def get_file_name(img_root, img_dict): (split_folder, file_name) = img_dict['coco_url'].split('/')[(- 2):] return o...
def bmprofile_analyze(input_dir: str, output_dir: str, out_format: str='html', options={}): parser = BMProfileParser() parsed_data = parser.parse(input_dir) generator = BMProfileGenerator() generator.generate(parsed_data, output_dir, out_format, options)
def _forward(config): assert config.load test_data = read_data(config, config.forward_name, True) update_config(config, [test_data]) _config_debug(config) if config.use_glove_for_unk: word2vec_dict = (test_data.shared['lower_word2vec'] if config.lower_word else test_data.shared['word2vec']) ...
def parse_videos(html): try: page_info_str = [l for l in html.split('\n') if ('ytInitialData = ' in l)][0] page_info_str = page_info_str.split('ytInitialData = ')[1].split('</script>')[0].rstrip(';') page_info_d = json.loads(page_info_str) vid_l = [] for tab_d in page_info_d[...
class MIRNet_v2(nn.Module): def __init__(self, inp_channels=3, out_channels=3, n_feat=80, chan_factor=1.5, n_RRG=4, n_MRB=2, height=3, width=2, scale=1, bias=False, task=None): super(MIRNet_v2, self).__init__() kernel_size = 3 self.task = task self.conv_in = nn.Conv2d(inp_channels, n...
def main(): print(__doc__) print() stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) for x in stirling_series(8)[::(- 1)]] taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) for x in taylor_series_at_1(23)[::(- 1)]] print('Stirling series coefficients') print('') pri...
def test_jagged_axis1(): array = ak.highlevel.Array([[[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]], [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]]]) assert (ak.operations.min(array, axis=1).to_list() == [[1, 2, 3.3], [1, 2, 3.3]]) assert (ak.operations.argmin(array, axis=1).to_list() == [...
def generate_y_true_calibrated(y_prob: NDArray, random_state: int=1) -> NDArray: generator = check_random_state(random_state) uniform = generator.uniform(size=len(y_prob)) y_true = (uniform <= y_prob).astype(float) return y_true
() ('--network', 'network_pkl', help='Network pickle filename', required=True) ('--rows', 'row_seeds', type=legacy.num_range, help='Random seeds to use for image rows', required=True) ('--cols', 'col_seeds', type=legacy.num_range, help='Random seeds to use for image columns', required=True) ('--styles', 'col_styles', t...
def NodesGTEDegree_PUndirNet(Graph, Threshold=0): return _snap.NodesGTEDegree_PUndirNet(Graph, Threshold)
class TemplateModel(BaseModel): def modify_commandline_options(parser, is_train=True): parser.set_defaults(dataset_mode='aligned') if is_train: parser.add_argument('--lambda_regression', type=float, default=1.0, help='weight for the regression loss') return parser def __init_...
class Tfidf(TransformBase): def __init__(self, **kwargs): super().__init__() self.tfidf = sklearn.feature_extraction.text.TfidfVectorizer(**kwargs) def fit(self, x: Text, **kwargs): self.tfidf.fit(x.values) return self def transform(self, x: Text): assert (self.tfidf ...
def test_float_input_holes(): float_test = np.random.rand(5, 5) with testing.raises(TypeError): remove_small_holes(float_test)
def main(): if (len(sys.argv) <= 1): print('Usage: {:s} path/to/your/video/file.mp4'.format(sys.argv[0])) sys.exit(1) movie_path = sys.argv[1] print('Detecting objects in movie {}'.format(movie_path)) movie_name = os.path.splitext(os.path.basename(movie_path))[0] sc = sp.Client() ...
def run_demo(cfg, frame_provider): np.random.seed(cfg.RNG_SEED) torch.manual_seed(cfg.RNG_SEED) logging.setup_logging(cfg.OUTPUT_DIR) logger.info('Run demo with config:') logger.info(cfg) common_classes = (cfg.DEMO.COMMON_CLASS_NAMES if (len(cfg.DEMO.LABEL_FILE_PATH) != 0) else None) video_v...
class TreeVisitor(object): def __init__(self): super(TreeVisitor, self).__init__() self.dispatch_table = {} self.access_path = [] def dump_node(self, node): ignored = (list((node.child_attrs or [])) + [u'child_attrs', u'pos', u'gil_message', u'cpp_message', u'subexprs']) ...
_context() class Task(object): TASK_SETUP = 'task_setup' TASK_INSTANCE_SETUP = 'task_instance_setup' REPORT_STEP = 'report_step' _global_names_used = set() def _get_next_name(node, group, name): basename = ((str(node) + '/') + str(name)) names_used = (Task._global_names_used if (grou...
def log_likelihood(covariance, precision): assert (covariance.shape == precision.shape) (dim, _) = precision.shape log_likelihood_ = (((- np.sum((covariance * precision))) + fast_logdet(precision)) - (dim * np.log((2 * np.pi)))) log_likelihood_ /= 2.0 return log_likelihood_
def _get_bases_name(m: nn.Module) -> List[str]: return [b.__name__ for b in m.__class__.__bases__]
class TestResult(SnipsTest): def test_should_serialize_results(self): input_ = 'hello world' intent = intent_classification_result('world', 0.5) slots = [unresolved_slot([3, 5], 'slot_value', 'slot_entity', 'slot_name')] result = parsing_result(input=input_, intent=intent, slots=slot...
def unpack(path, dest='.'): with WheelFile(path) as wf: namever = wf.parsed_filename.group('namever') destination = os.path.join(dest, namever) print('Unpacking to: {}...'.format(destination), end='') sys.stdout.flush() wf.extractall(destination) print('OK')
class NoneOf(object): def __init__(self, values, message=None, values_formatter=None): self.values = values self.message = message if (values_formatter is None): values_formatter = self.default_values_formatter self.values_formatter = values_formatter def __call__(sel...
(frozen=True) class TorchMiniBatch(): observations: TorchObservation actions: torch.Tensor rewards: torch.Tensor next_observations: TorchObservation returns_to_go: torch.Tensor terminals: torch.Tensor intervals: torch.Tensor device: str numpy_batch: Optional[TransitionMiniBatch] = No...
def conv_nd(dims, *args, **kwargs): if (dims == 1): return nn.Conv1d(*args, **kwargs) elif (dims == 2): return nn.Conv2d(*args, **kwargs) elif (dims == 3): return nn.Conv3d(*args, **kwargs) raise ValueError(f'unsupported dimensions: {dims}')
def imageList(path, multiDir=False, imageExtension=['*.jpg', '*.png', '*.jpeg', '*.tif', '*.bmp']): imageList = [] for ext in imageExtension: if (multiDir == True): imageList.extend(glob.glob(((path + '*/') + ext))) else: imageList.extend(glob.glob((path + ext))) ...
def find_parent_directory_containing_directory(base: Path, target: str) -> Optional[Path]: def is_directory(path: pathlib.Path) -> bool: return path.is_dir() return _find_parent_directory_containing(base, target, predicate=is_directory)
class InternalError(ExecutionEvent): is_terminal = True type: InternalErrorType subtype: (SchemaErrorType | None) title: str message: str extras: list[str] exception_type: str exception: str exception_with_traceback: str thread_id: int = field(default_factory=threading.get_ident)...
def hook_adapavgpool1d(m, x, y): x = x[0] out_size = m.output_size k = math.ceil((x.size(2) / out_size)) flops_per_ele = k flops = (flops_per_ele * y.numel()) return int(flops)
class HeckeModule_free_module(HeckeModule_generic): def __init__(self, base_ring, level, weight, category=None): HeckeModule_generic.__init__(self, base_ring, level, category=category) self.__weight = weight def _repr_(self): return repr(type(self)) def __getitem__(self, n): ...
def query_on_triplane(query, feature, min_, max_, use_ste=False, boundary_check=False, ctx=None): func = LanczosQueryOnTriplane(ctx, min_, max_, use_ste, boundary_check) return func(query, feature)
def delete_Image(i): global remfileNames print(remfileNames) try: os.remove(('Keypoints\\' + remfileNames[(i - 1)])) os.remove((('gui\\captured_images\\' + str(i)) + '.jpg')) except: print('file not found') pass
def LoadData(training_data_path, file_list, split=0.15, workers=4, batch_size=1, transforms=None): if (not os.path.exists(training_data_path)): error_message = (('Folder ' + os.path.abspath(training_data_path)) + ' does not exist.') raise OSError(error_message) (training_samples, validation_samp...
def load_language_model(path: str, device: torch.device): model = torch.load(path, map_location=(lambda storage, loc: storage)).to(device) if isinstance(model, nn.DataParallel): model = model.module model.device = device return model
_toolkit() class EpicFHIR(FunctionToolkit): name_for_human = 'Epic FHIR' description_for_human = 'Toolkit for managing and sharing patient data in healthcare organizations.' name_for_model = 'EpicFHIR' description_for_model = 'The EpicFHIR toolkit provides a comprehensive set of tools for healthcare org...
.parametrize('ti_func,np_func', unary_func_table) def test_python_scope_vector_unary(ti_func, np_func): ti.init() x = ti.Vector(([2, 3] if (ti_func in [ops.invert, ti.lang.ops.logical_not]) else [0.2, 0.3])) result = ti_func(x).to_numpy() if (ti_func in [ti.lang.ops.logical_not]): result = resul...
class TestSingleProcessFileTensorStorage(unittest.TestCase): def test_read_write_1(self): schema = {'tf': SizeData(dtype='float32', shape=(112, 112)), 'ti': SizeData(dtype='int32', shape=(4, 64, 64))} data_elts = [] torch.manual_seed(23) for _i in range(3): data_elt = {'t...
class DistModule(Module): def __init__(self, module): super(DistModule, self).__init__() self.module = module broadcast_params(self.module) def forward(self, *inputs, **kwargs): return self.module(*inputs, **kwargs) def train(self, mode=True): super(DistModule, self)....
def get_cat_id(label_list, cat): for i in range(len(label_list)): if (cat == label_list[i][0]): return i
class JamendoJsonifier(DatasetJsonifier): def load_raw_data(self): assert self.split, 'is split implemented for this dataset?' fields_to_use = ('genre', 'instrument', 'mood/theme') data = [] tsv_file = os.path.join(self.input_dir, 'autotagging.tsv') (tracks, tags, extra) = mt...
def postprocess_pose(pose_folder, scene_id): print('postprocessing pose...') for fid in range(999999): path_reloc = '{}/{}'.format(pose_folder, reloc_mask).format(fid) path_reloc_bm = '{}/{}'.format(pose_folder, reloc_bm_mask).format(fid) if (not os.path.exists(path_reloc)): ...
class simulator(): def __init__(self): self.conf = cfg() self.topo = topo() self.top_path = './' self.verbose = True self.save_trace = True self.num_layers = 0 self.single_layer_sim_object_list = [] self.params_set_flag = False self.all_layer_r...
class ELU(Module): __constants__ = ['alpha', 'inplace'] alpha: float inplace: bool def __init__(self, alpha: float=1.0, inplace: bool=False) -> None: super(ELU, self).__init__() self.alpha = alpha self.inplace = inplace def forward(self, input: Tensor) -> Tensor: retu...
def Trainer(model, temporal_contr_model, model_optimizer, temp_cont_optimizer, train_dl, valid_dl, test_dl, device, logger, config, experiment_log_dir, training_mode): logger.debug('Training started ....') criterion = nn.CrossEntropyLoss() scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(model_optimiz...
def _expect_int(value, msg=None): try: return int(value) except ValueError as e: if (msg is None): msg = 'Expected an int, got %s' raise ValueError((msg % value)) from e
def advance_past_unaries(gold_sequence, cur_index): while (((cur_index + 2) < len(gold_sequence)) and isinstance(gold_sequence[cur_index], OpenConstituent) and isinstance(gold_sequence[(cur_index + 1)], CloseConstituent)): cur_index += 2 return cur_index
def recorder(out, pred_list): NEG_WORDS = ['No', 'not', 'no', 'NO'] for line in out: line = line.replace('.', '') line = line.replace(',', '') words = line.split(' ') if (any(((word in NEG_WORDS) for word in words)) or any((word.endswith("n't") for word in words))): p...
def main(): set_seeds(2020) args = vars(parser.parse_args()) alphabet = Protein() cfgs = [] data_cfg = config.DataConfig(args['data_config']) cfgs.append(data_cfg) if (args['lm_model_config'] is None): model_cfg = config.ModelConfig(args['model_config'], input_dim=len(alphabet), num_...
(goos.CylinderFlow) class CylinderFlowImpl(GeometryImpl): def eval(self, grid: gridlock.Grid, params: RenderParams): radius = self.shape.radius.item() num_points = int(np.ceil((((params.pts_per_arclen * 2) * np.pi) * radius))) grid.draw_cylinder(self.shape.pos, radius, self.shape.height.item...
def write_with_generator_and_metadata(datasource, table, gen, metadata): with connect_with_data_source(datasource) as conn: with SQLFSWriter(conn, table) as w: w.write(_encode_metadata(metadata)) for d in gen(): w.write(d)
def main(): if (len(sys.argv) < 3): sys.exit('Needs args: hook_name, control_dir') hook_name = sys.argv[1] control_dir = sys.argv[2] if (hook_name not in HOOK_NAMES): sys.exit(('Unknown hook: %s' % hook_name)) hook = globals()[hook_name] hook_input = read_json(pjoin(control_dir, ...
def _densenet(arch: str, growth_rate: int, block_config: Tuple[(int, int, int, int)], num_init_features: int, pretrained: bool, progress: bool, **kwargs: Any) -> DenseNet: model = DenseNet(growth_rate, block_config, num_init_features, **kwargs) if pretrained: _load_state_dict(model, model_urls[arch], pr...
class ATR(Dataset): CLASSES = ['background', 'hat', 'hair', 'sunglass', 'upper-clothes', 'skirt', 'pants', 'dress', 'belt', 'left-shoe', 'right-shoe', 'face', 'left-leg', 'right-leg', 'left-arm', 'right-arm', 'bag', 'scarf'] PALETTE = torch.tensor([[0, 0, 0], [127, 0, 0], [254, 0, 0], [0, 84, 0], [169, 0, 50], ...
def LF_pseudo_negation_exclusion(span): left_rgx = "(inadequate\\s+to|does\\s+not|cannot|can't)\\s+exclude" right_rgx = "(cannot\\s+be|not\\s+be|doesn't|not|to)\\s+exclude[d]*" left = get_left_span(span) trigger = match_regex(left_rgx, left) if (trigger and (token_distance(trigger, span) <= 3)): ...
def visualize(settings): settings.check_data_exists() np.random.seed() with h5py.File(settings.hdf5_file_name, 'r') as hf: SNID_idxs = np.random.permutation(hf['SNID'].shape[0])[:16] SNIDs = hf['SNID'][:][SNID_idxs] SNIDs = [i for i in np.array([k for k in SNIDs]).astype(str)] plot_r...
class VAEBaselineView(nn.Module): def __init__(self): super(VAEBaseline, self).__init__() self.fc1 = nn.Linear(784, 400) self.fc21 = nn.Linear(400, 20) self.fc22 = nn.Linear(400, 20) self.fc3 = nn.Linear(20, 400) self.fc4 = nn.Linear(400, 784) print('Total mod...
class SummarizationMetric(Metric): def __init__(self, task: str, device: str='cpu'): self.rouge_fns = {'rouge_1': get_rouge_function('rouge1'), 'rouge_2': get_rouge_function('rouge2'), 'rouge_l': get_rouge_function('rougeL')} if (not spacy.util.is_package('en_core_web_sm')): spacy.cli.do...
class GModel(nn.Module): def __init__(self, opt): super(GModel, self).__init__() self.opt = opt self.fc = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 2)) def forward(self, data): return self.fc(data)
def _wrap_result(result, is_complex, shape=None): if is_complex: z = _real2complex(result) else: z = result if (shape is not None): z = z.reshape(shape) return z