code
stringlengths
101
5.91M
def default_convert(data): elem_type = type(data) if isinstance(data, torch.Tensor): return data elif ((elem_type.__module__ == 'numpy') and (elem_type.__name__ != 'str_') and (elem_type.__name__ != 'string_')): if ((elem_type.__name__ == 'ndarray') and (np_str_obj_array_pattern.search(data....
def make_sll_loss_evaluator(cfg): max_disp = cfg.model.losses.l1_loss.get('max_disp', None) weights = cfg.model.losses.l1_loss.weights sparse = cfg.data.sparse return DispSmoothL1Loss(max_disp=max_disp, weights=weights, sparse=sparse)
def add_config(_C): _C.MODEL = CN() _C.MODEL.CONV = CN() _C.MODEL.CONV.TYPE = 'Conv2d' _C.MODEL.CONV.ADD_BLOCKS = None _C.MODEL.NORM = CN() _C.MODEL.NORM.TYPE = 'BatchNorm2d' _C.MODEL.NORM.SYNC_BN = False _C.MODEL.NORM.FIX_BN = False _C.MODEL.NORM.PARTIAL_BN = False _C.MODEL.NORM...
_module() class FastRCNN(TwoStageDetector): 'Implementation of `Fast R-CNN < def __init__(self, backbone, roi_head, train_cfg, test_cfg, neck=None, pretrained=None): super(FastRCNN, self).__init__(backbone=backbone, neck=neck, roi_head=roi_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrai...
_module() class GQAComputeMetrics(BaseComputeMetrics): def extract_target(self, string: str): try: found = ANS_EXTRACT_PAT.findall(string.strip()) if (len(found) != 1): return None return found[0].strip().rstrip('.').strip() except (IndexError, Att...
def inverse_data_transform(config, X): if hasattr(config, 'image_mean'): X = (X + config.image_mean.to(X.device)[(None, ...)]) if config.data.logit_transform: X = torch.sigmoid(X) elif config.data.rescaled: X = ((X + 1.0) / 2.0) return torch.clamp(X, 0.0, 1.0)
def test_pretransform_nobatch(): q = torch.rand(495, 436, 8) output = UNet.unet_pre_transform(data=torch.rand(12, 495, 436, 8), static_data=q, zeropad2d=None, batch_dim=False) assert (output.shape == (((12 * 8) + 8), 495, 436))
def l2_to_ip(l2_score, query, max_norm=None): query_norm = np.linalg.norm(query, axis=1, keepdims=True) if (max_norm is None): return ((- 0.5) * (l2_score - (query_norm ** 2))) return ((- 0.5) * ((l2_score - (query_norm ** 2)) - (max_norm ** 2)))
def isect_segments_include_segments(segments): return isect_segments_impl(segments, include_segments=True)
def download_and_extract_archive(url, download_root, extract_root=None, filename=None, md5=None, remove_finished=False): download_root = os.path.expanduser(download_root) if (extract_root is None): extract_root = download_root if (not filename): filename = os.path.basename(url) download_...
def cobmine_all_coils(image, sensitivity): combined = T.complex_multiply(sensitivity[(..., 0)], (- sensitivity[(..., 1)]), image[(..., 0)], image[(..., 1)]) return combined.sum(dim=0)
def _equal(a, b): if isinstance(a, (torch.Tensor, np.ndarray)): return (a == b).all() else: return (a == b)
class FastRCNNTest(unittest.TestCase): def test_fast_rcnn(self): torch.manual_seed(132) cfg = get_cfg() cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS = (10, 10, 5, 5) box2box_transform = Box2BoxTransform(weights=cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS) box_head_output_size = 8 ...
def _add_categories_metadata(dataset_name: str) -> None: metadict = get_lvis_instances_meta(dataset_name) categories = metadict['thing_classes'] metadata = MetadataCatalog.get(dataset_name) metadata.categories = {(i + 1): categories[i] for i in range(len(categories))} logger = logging.getLogger(__na...
class NDCG_relevance(): def __init__(self, length=20): self.length = length def init(self, train): self.train = train return def reset(self): self.test = 0 self.pos = 0 def skip(self, for_item=0, session=(- 1)): pass def set_buys(self, buys, test_set):...
def _is_float_str(str_number): if (not str_number): return False try: float(str_number) return True except ValueError: return False
class AdaptiveParamNoiseSpec(object): def __init__(self, initial_stddev=0.1, desired_action_stddev=0.1, adoption_coefficient=1.01): self.initial_stddev = initial_stddev self.desired_action_stddev = desired_action_stddev self.adoption_coefficient = adoption_coefficient self.current_st...
class VarData(object): def __init__(self, params=None, lhs=None, ret=None): super().__init__() self.params = params self.lhs = lhs self.ret = ret
class Sorting2TaskDefinition(DefaultTaskDefinition): tray_dir = 'tray' tray_urdf = 'traybox.urdf' spawn_pos_min = np.array([(- 0.4), (- 0.25), 0.1]) spawn_pos_max = np.array([(- 0.65), 0.25, 0.155]) spawn_pos_delta = (spawn_pos_max - spawn_pos_min) tray_poses = [np.array([(- 0.5), 0.0, 0.0]), np...
class ResNet(nn.Module): def __init__(self, block, layers): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3) self.bn1 = nn.InstanceNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool...
def common_tangent_radian(r1, r2, d): alpha = math.acos((abs((r2 - r1)) / d)) alpha = (alpha if (r1 > r2) else (pi - alpha)) return alpha
class LaplacianKernel(Kernel): def __init__(self) -> None: super(LaplacianKernel, self).__init__() def similarity(self, distances: torch.Tensor, bandwidth: Union[(float, torch.Tensor)]) -> torch.Tensor: return ((- torch.sqrt(distances)) / bandwidth)
class Logger(): def __init__(self, config): self.config = config if ('env' in self.config.keys()): self.init_pretrain_logger() else: self.init_downstream_logger() self.init_training_log() def init_pretrain_logger(self): if (self.config.env.experime...
def get_split_template_mesh_dataset(cat_id, edge_length_threshold): return SplitTemplateMeshManager(cat_id, edge_length_threshold).get_saved_dataset()
class TestLoss(unittest.TestCase): def test_run_torsion_angle_loss(self): batch_size = consts.batch_size n_res = consts.n_res a = torch.rand((batch_size, n_res, 7, 2)) a_gt = torch.rand((batch_size, n_res, 7, 2)) a_alt_gt = torch.rand((batch_size, n_res, 7, 2)) loss =...
class Data_Loader_toy(): def __init__(self, path, bsz, L, K, test=False): self.data_path = path self.bsz = bsz self.test = test self.L = L self.K = K self.get_data() def get_data(self): base_path = self.data_path path_train = os.path.join(base_path...
def normalize_probs(m): return tf.math.divide(m, tf.reshape(tf.reduce_sum(m, axis=1), [(- 1), 1]))
def copy_BraTS_segmentation_and_convert_labels(in_file, out_file): img = sitk.ReadImage(in_file) img_npy = sitk.GetArrayFromImage(img) uniques = np.unique(img_npy) for u in uniques: if (u not in [0, 1, 2, 4]): raise RuntimeError('unexpected label') seg_new = np.zeros_like(img_npy...
.parametrize('debugging', [False, True]) .parametrize('ofolder', [str(Path(__tmp_dir__, 'test')), str(Path(__tmp_dir__, 'mixup_test'))]) def test_mixup(debugging, ofolder): inp = [[[[0 for i in range(40)] for i in range(40)]]] targ = [[[[0 for i in range(40)] for i in range(40)]]] for i in range(10): ...
_materialize('tensorflow') class Reverse(UnaryOpBase): in_dtypes = [(i,) for i in DTYPE_GEN_ALL] out_dtypes = [(i,) for i in DTYPE_GEN_ALL] def __init__(self): super().__init__() self.inp_ranks = [rank_from(1)] self.out_ranks = [rank_from(1)] def _init_axis(self, input_shape: Lis...
def predToSegmentation(pred): Max = pred.max(dim=1, keepdim=True)[0] x = (pred / Max) return (x == 1).float()
class ConvBertTokenizerFast(BertTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION slow_tokenizer_class = ConvBertTo...
class TrainTransform(): def __init__(self, aug_mode): self.aug_mode = aug_mode if (self.aug_mode == 1): t = [JitterPoints(sigma=0.1, clip=0.2), RemoveRandomPoints(r=(0.0, 0.1)), RandomTranslation(max_delta=0.3), RemoveRandomBlock(p=0.4)] elif (self.aug_mode == 2): t =...
def build_post_process(args): if PLATFORM_IS_WINDOWS: lapack_paths = glob.glob(os.path.join(args.install_path, 'lib64/lapack_blas_windows/*.dll')) if lapack_paths: for lapack_path in lapack_paths: copy_file_if_not_exists(lapack_path, os.path.join(args.install_path, 'lib',...
def block(inp, nbfilters, dropout, weight_decay, channel_axis, subsample=(1, 1), batchnorm_training=True, use_bias=True): x = inp for i in [1, 2]: x = BatchNormalization(axis=channel_axis, center=batchnorm_training, scale=batchnorm_training)(x) x = Activation('relu')(x) if ((dropout > 0....
def test_remove_last_from_packed_seq(): padded_seq = torch.tensor([[1, 2, 3], [4, 3, 0], [12, 18, 0]]) orig_lengths = torch.tensor([3, 2, 2]) packed_seq = rnn.pack_padded_sequence(padded_seq, orig_lengths, batch_first=True) computed = torch_utils.remove_last_from_packed_seq(packed_seq) (computed_pad...
_start_docstrings('CamemBERT Model with a `language modeling` head on top. ', CAMEMBERT_START_DOCSTRING) class TFCamembertForMaskedLM(TFRobertaForMaskedLM): config_class = CamembertConfig
class TFRoFormerForMaskedLM(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class BatchEnv(object): def __init__(self, envs, blocking): self._envs = envs self._blocking = blocking observ_space = self._envs[0].observation_space if (not all(((env.observation_space == observ_space) for env in self._envs))): raise ValueError('All environments must us...
_sentencepiece class SpeechToTextTokenizerMultilinguialTest(unittest.TestCase): checkpoint_name = 'valhalla/s2t_mustc_multilinguial_medium' french_text = "C'est trop cool" spanish_text = 'Esto es genial' def setUpClass(cls): cls.tokenizer: Speech2TextTokenizer = Speech2TextTokenizer.from_pretrai...
def training_params(is_gcloud=False, output_dir=None): if (not output_dir): output_dir = util.construct_experiment_output_dir(__file__) num_gpus = 1 stop_after = 7 dynamic_batch_size = {2: 128, 3: 128, 4: 64, 5: 32, 6: 16, 7: 6, 8: 3, 9: 2} imgs_per_phase = 384000 dynamic_steps_per_phase...
def missing_explanation(json): for recommendations in json.values(): for rec in recommendations: if ('explanation' not in rec): return ('Recommendations must include explanation.', 400) return False
def find_dense(path, data): nodes = set() graph = defaultdict(list) graph_obj = np.load((path + '.npz'), allow_pickle=True) src_li = graph_obj['src_li'] dst_li = graph_obj['dst_li'] num_nodes = graph_obj['num_nodes'] for (src, dst) in zip(src_li, dst_li): nodes.add(src) nodes...
class GitConfig(PretrainedConfig): model_type = 'git' def __init__(self, vision_config=None, vocab_size=30522, hidden_size=768, num_hidden_layers=6, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=1024, initial...
def _build_expression(inputs, output=None, size_dict=None, optimize='auto', implementation=None, prefer_einsum=False, autojit=False, via=None, sort_contraction_indices=False): if (len(inputs) == 1): term = tuple(inputs[0]) output = tuple(output) if (term == output): def fn(*array...
def debug(msg, *args): if (MIN_LEVEL <= DEBUG): print(('%s: %s' % ('DEBUG', (msg % args))))
_REGISTRY.register() class STL10(DatasetBase): dataset_dir = 'stl10' def __init__(self, cfg): root = osp.abspath(osp.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = osp.join(root, self.dataset_dir) train_dir = osp.join(self.dataset_dir, 'train') test_dir = osp.join(self.dataset_...
class TFMPNetForMaskedLM(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
class TSPDecoder(DecoderBase): def get_context(self, observation: Observation, embeddings: Array) -> Array: return jnp.concatenate([embeddings.mean(0), embeddings[observation.position], embeddings[observation.start_position]], axis=0)[None] def get_transformed_attention_mask(self, attention_mask: Array)...
def test_running_stat(): for shp in ((), (3,), (3, 4)): li = [] rs = RunningStat(shp) for _ in range(5): val = np.random.randn(*shp) rs.push(val) li.append(val) m = np.mean(li, axis=0) assert np.allclose(rs.mean, m) v = ...
_module() class AutoAugment(object): def __init__(self, policies, hparams=_HPARAMS_DEFAULT): assert (isinstance(policies, list) and (len(policies) > 0)), 'Policies must be a non-empty list.' for policy in policies: assert (isinstance(policy, list) and (len(policy) > 0)), 'Each policy in ...
def time_adapter(func): def inner(*args, **kwargs): (h_embedding, r_embedding, t_embedding) = func(*args, **kwargs) model = args[0] start = kwargs['data'][3] end = kwargs['data'][4] if (not model.init_time_adapter): model.start_time_transfer = nn.Embedding(num_emb...
def reshape_hidden_states_to_3d(hidden_states): hs = hidden_states if isinstance(hs, tuple): hs = torch.stack(hs) hs = hs.reshape((hs.shape[0], (- 1), hs.shape[(- 1)])) return hs
class LossScaler(): def __init__(self, init_scale=(2 ** 32), mode='dynamic', scale_factor=2.0, scale_window=1000): self.cur_scale = init_scale self.cur_iter = 0 assert (mode in ('dynamic', 'static')), 'mode can only be dynamic or static' self.mode = mode self.last_overflow_it...
class BaseMaskHead(BaseModule, metaclass=ABCMeta): def __init__(self, init_cfg): super(BaseMaskHead, self).__init__(init_cfg) def loss(self, **kwargs): pass def get_results(self, **kwargs): pass def forward_train(self, x, gt_labels, gt_masks, img_metas, gt_bboxes=None, gt_bboxes_...
def _getlogger(): logger = logging.getLogger('tensorpack') logger.propagate = False logger.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(_MyFormatter(datefmt='%m%d %H:%M:%S')) logger.addHandler(handler) return logger
def create_matrices_for_rliable(data_dictionary: Dict[(str, Dict[(str, Any)])], environment_name: str, metrics_to_normalize: List[str]) -> Tuple[(Dict[(str, Dict[(str, Any)])], Dict[(str, Dict[(str, Any)])])]: (environment_name, metrics_to_normalize) = lower_case_inputs(environment_name, metrics_to_normalize) t...
def validate_keras_model(platform, device_type, model_file, input_file, mace_out_file, input_names, input_shapes, input_data_formats, output_names, output_shapes, output_data_formats, validation_threshold, input_data_types, output_data_types, log_file): from tensorflow import keras import tensorflow_model_optim...
def extract_labelled_aerial_imagery(df_fullmerge2insee): nb_tiles = df_fullmerge2insee.shape[0] n_jbs = min(nb_tiles, MAX_NB_JOBS) prepare_input = [(aerial_fname, gpd.GeoDataFrame(pd.DataFrame([idINSPIRE, insee_geom]).transpose().rename(columns={0: 'idINSPIRE', 1: 'geometry'}), crs={'init': 'epsg:3035'})) f...
class Database(): _database = None _protocol = None _length = None def __init__(self, path: PathLike, readahead: bool=True, pre_open: bool=False): self.path = str(path) self.readahead = readahead self.pre_open = pre_open self._has_fetched_an_item = False def database(...
class SCM(nn.Module): def __int__(self, shape, in_dim, out_dim): super(SCM, self).__int__() self.dim = in_dim self.shape = shape self.conv1 = nn.Conv2d(in_dim, out_dim, 1) self.pool1 = nn.MaxPool2d(kernel_size=2) self.conv2 = nn.Conv2d(in_dim, out_dim, 3) self...
class InfoMixin(object): def _get_doc(cls): return cls.__doc__ def get_info(cls): doc = parse_docstring(cls._get_doc()) return {'name': cls.get_name(), 'platform': cls.get_platform(), 'module': cls.__module__, 'title': doc['short_description'], 'description': doc['long_description'], 'pa...
class DatasetEvaluators(DatasetEvaluator): def __init__(self, evaluators): super().__init__() self._evaluators = evaluators def reset(self): for evaluator in self._evaluators: evaluator.reset() def process(self, inputs, outputs): for evaluator in self._evaluators:...
class Swin2SRForImageSuperResolution(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class wide_basic(nn.Module): def __init__(self, in_planes, planes, dropout_rate, stride=1): super(wide_basic, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, bias=True) self.dropout = nn.Dropout(p=dropout_rate)...
class FlaxElectraModelTester(unittest.TestCase): def __init__(self, parent, batch_size=13, seq_length=7, is_training=True, use_attention_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, embedding_size=24, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37, hidden_act...
def _point_in_triangle(p, a, b, c): whole = abs(calc_area([a, b, c])) parta = abs(calc_area([a, b, p])) partb = abs(calc_area([b, c, p])) partc = abs(calc_area([c, a, p])) thresh = 1e-07 return (((parta + partb) + partc) < (whole + thresh))
def sMAPE(y_true: 'ndarray', y_pred: 'ndarray', multioutput: str='raw_values') -> Union[(float64, 'ndarray')]: (y_true, y_pred, original_shape) = _standardize_input(y_true, y_pred, multioutput) output_errors = np.mean(((100 * np.abs((y_true - y_pred))) / ((np.abs(y_true) + np.abs(y_pred)) + EPSILON)), axis=0) ...
def training_2nd_user_task_fbne(model, sess): best_loss = 0 saver = tf.train.Saver() data_train = fbne_data.Dataset(setting.oracle_training_file_user_task) train_batches = data_train.get_positive_instances_user_task(0, 'train') num_batch_train = ((data_train.oracle_num_users // setting.batch_size_us...
def get_loader(dataset_name, root, batch_size, split='train', num_workers=2, shuffle=True): if (dataset_name not in DATASETS): raise Exception('[!] No data loader found for the dataset: {}.'.format(dataset_name)) transform_list = [] if (split == 'train'): if (dataset_name == 'cifar10'): ...
class TestOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--results_dir', default='', type=str, help='the results dir, default is expr_dir/results ') self.parser.add_argument('--n_samples', type=int, default=5, help='#samples for multimodal...
def _create_wr_from_rx_rm_depth_ahat(filename, rx, user): return wr_rm_depth_ahat(filename, rx.port, rx.mode, rx.divisor, rx.profile_z, rx.profile_ab, rx.level, rx.bitrate, rx.options, user)
class Ui_MAIAN(object): def setupUi(self, MAIAN): MAIAN.setObjectName('MAIAN') MAIAN.resize(950, 821) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizeP...
def plot_shelf_freqs(treble): Rpot = 10000.0 C = 3.9e-09 G1 = (1.0 / 100000.0) G2 = (1.0 / (1800.0 + ((1 - treble) * Rpot))) G3 = (1.0 / (4700.0 + (treble * Rpot))) G4 = (1.0 / 100000.0) b0 = (C * (G1 + G2)) b1 = (G1 * (G2 + G3)) a0 = (C * (G3 - G4)) a1 = ((- G4) * (G2 + G3)) ...
_model def repvgg_b1(pretrained=False, **kwargs): return _create_byobnet('repvgg_b1', pretrained=pretrained, **kwargs)
def visualizeHiddenMain(args): np.random.seed(0) ConfigureGPU(args) (data, dataset) = GetDataset(args) if (('model' in args) and (args['model'] is not None)): model = MakeModel(taskdef=None, **args) model.validate = True model.load(world=None, **data) prev_option = model....
def convert_color_factory(src, dst): code = getattr(cv2, 'COLOR_{}2{}'.format(src.upper(), dst.upper())) def convert_color(img): out_img = cv2.cvtColor(img, code) return out_img convert_color.__doc__ = 'Convert a {0} image to {1} image.\n\n Args:\n img (ndarray or str): The input i...
class ResidualGenerator(nn.Module): def __init__(self, network): super(ResidualGenerator, self).__init__() self.network = network pass def forward(self, epe_batch): return make_residual(epe_batch.img, self.network(epe_batch))
def set_default_general_args(args): args.checkpoint_activations = getattr(args, 'checkpoint_activations', False) args.offload_activations = getattr(args, 'offload_activations', False) args.min_params_to_wrap = getattr(args, 'min_params_to_wrap', int(.0)) args.max_positions = getattr(args, 'max_positions...
class RetriBertTokenizer(BertTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION model_input_names = ['input_ids', 'atten...
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] match = Match('#include\\s*"([^/]+\\.h)"', line) if (match and (not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)))): error(filename, linenum, 'build/in...
class AverageValueListMeter(MultipleAverageValueMeter): def _add(self, list_value: List[float], **kwargs): for (i, v) in enumerate(list_value): self._meter_dicts[str(i)].add(v)
class CaseConfigParser(ConfigParser.ConfigParser): def optionxform(self, optionstr): return optionstr
def visualise_ik(solver, env): for pose in Tep: (q, success, iterations, searches, residual) = solver.solve(ets, pose, q0) print(f'Successful: {success}, iterations: {iterations}, searches: {searches}, residual: {residual}') panda.q = q goal_axes.T = pose ee_axes.T = panda.fk...
class CLIPImageProcessor(BaseImageProcessor): model_input_names = ['pixel_values'] def __init__(self, do_resize: bool=True, size: Dict[(str, int)]=None, resample: PILImageResampling=PILImageResampling.BICUBIC, do_center_crop: bool=True, crop_size: Dict[(str, int)]=None, do_rescale: bool=True, rescale_factor: Un...
def add_choropleth_traces(fig, df, plotting_cols, counties_json=None, visible=False, show_hovertext=False, colorbar_title='Deaths', color_scl=[[0.0, '#FFFFFF'], [0.2, '#B96D67'], [0.4, '#A83C3B'], [0.6, '#8B2222'], [0.8, '#5B0D0D'], [1.0, '#5A2318']], value_labels=['Deaths: ']): if (counties_json is None): ...
def load_histopathologyGray(args, **kwargs): args.input_size = [1, 28, 28] args.input_type = 'gray' args.dynamic_binarization = False with open('datasets/HistopathologyGray/histopathology.pkl', 'rb') as f: data = pickle.load(f) x_train = np.asarray(data['training']).reshape((- 1), (28 * 28))...
class NetworkCIFAR(nn.Module): def __init__(self, C, num_classes, layers, auxiliary, genotype): super(NetworkCIFAR, self).__init__() self._layers = layers self._auxiliary = auxiliary self.drop_path_prob = 0.5 stem_multiplier = 3 C_curr = (stem_multiplier * C) ...
def find_version(): version_file = 'dassl/__init__.py' with open(version_file, 'r') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__']
class ValidActionsMultiAgentEnv(MultiAgentEnv): def __init__(self): super(ValidActionsMultiAgentEnv, self).__init__() self.observation_length = None self.orig_observation_length = None
class Generator(object): def __init__(self): self.z_dim = 100 self.x_dim = [64, 64, 1] self.name = 'face_test/dcgan/g_net' def __call__(self, z): with tf.variable_scope(self.name) as vs: bs = tf.shape(z)[0] fc1 = tc.layers.fully_connected(z, 1024, weights_...
def add_robust_features(df): df['X_95_quantile'] = np.array([np.quantile(df.iloc[i].X, 0.95) for i in range(len(df))]) df['X_mad'] = np.array([robust.mad(df.iloc[i].X) for i in range(len(df))]) return df
def main(): (x, y) = (Var('x'), Var('y')) if True: gradient = Func('gradient') gradient[(x, y)] = (x + y) gradient.trace_stores() print('Evaluating gradient row-major') output = gradient.realize(4, 4) print('Equivalent C:') for yy in range(4): ...
def update_model(old_model): if (not _check_model_old_version(old_model)): return old_model new_model = copy.deepcopy(old_model) for idx in range(0, len(new_model.WN)): wavenet = new_model.WN[idx] wavenet.res_skip_layers = torch.nn.ModuleList() n_channels = wavenet.n_channels...
_elapsed_time(customized_msg='Customized eval_func') def eval_func(infer_graph): dataset = Dataset(FLAGS.input_file, FLAGS.vocab_file) sorted_keys = dataset.sorted_keys dataloader = DataLoader(framework='tensorflow', dataset=dataset, batch_size=FLAGS.batch_size, collate_fn=collate_fn) input_tensors = li...
class AsTypeTransformer(AutotabularPreprocessingAlgorithm): def __init__(self, dtype, random_state: Optional[np.random.RandomState]=None): assert (dtype is not None) self.dtype = dtype super(AsTypeTransformer, self).__init__() def fit(self, X, y=None): return self def transfo...
class MaxPool(PlainNetBasicBlockClass): def __init__(self, out_channels, kernel_size, stride, no_create=False, **kwargs): super(MaxPool, self).__init__(**kwargs) self.in_channels = out_channels self.out_channels = out_channels self.kernel_size = kernel_size self.stride = stri...
class LSGANLoss(nn.Module): def __init__(self): super(LSGANLoss, self).__init__() def forward(self, x, y): if (not isinstance(x, list)): x = [x] loss = 0.0 num = len(x) for out in x: loss += torch.mean(((out - y) ** 2)) loss /= num ...
class State(): nodes: Node windows: TimeWindow coeffs: PenalityCoeff vehicles: StateVehicle order: chex.Array step_count: chex.Array action_mask: chex.Array key: chex.PRNGKey
def update_cache(cache_dir, names: List[str], bytes_io: List[io.BytesIO]): cache_dir = pathlib.Path(os.path.expanduser(cache_dir)) for (i, _) in enumerate(names): filepath = pathlib.Path(cache_dir, names[i]) with open(filepath, 'wb') as f: f.write(bytes_io[i].getvalue())