code
stringlengths
17
6.64M
class OpTreeSum(OpTreeNodeBase): 'A OpTree node that sums over its children.\n\n Args:\n children_list (list): A list of children of the summation.\n factor_list (list): A list of factors for each child.\n operation_list (list): A list of operations that are applied to each child.\n ' ...
class OpTreeLeafBase(OpTreeElementBase): 'Base class for Leafs of the OpTree.' pass
class OpTreeCircuit(OpTreeLeafBase): 'A leaf of the OpTree that represents a circuit.\n\n Args:\n circuit (QuantumCircuit): The circuit that is represented by the leaf.\n ' def __init__(self, circuit: QuantumCircuit) -> None: self._circuit = circuit self._hashvalue = OpTree.hash_...
class OpTreeOperator(OpTreeLeafBase): 'A leaf of the OpTree that represents an operator.\n\n Args:\n operator (SparsePauliOp): The operator that is represented by the leaf.\n ' def __init__(self, operator: SparsePauliOp) -> None: self._operator = operator self._hashvalue = OpTree...
class OpTreeExpectationValue(OpTreeLeafBase): '\n Leaf of the OpTree that represents an expectation value of a circuit and an operator.\n\n Args:\n circuit (Union[OpTreeLeafCircuit, QuantumCircuit]): The circuit in the expectation value.\n operator (Union[OpTreeLeafOperator, SparsePauliOp]): T...
class OpTreeMeasuredOperator(OpTreeExpectationValue): '\n Leaf of the OpTree that represents an measurement.\n\n The circuit in the class represents the circuit that is measured for the given operator.\n ' def measure_circuit(self, circuit: Union[(QuantumCircuit, OpTreeCircuit)]) -> OpTreeExpectatio...
class OpTreeContainer(OpTreeLeafBase): '\n A container for arbitrary objects that can be used as leafs in the OpTree.\n\n Args:\n item (Any): Any kind of item that is represented by the leaf.\n ' def __init__(self, item: Any) -> None: self.item = item def __str__(self) -> str: ...
class OpTreeValue(OpTreeLeafBase): '\n A leaf that contains an evaluated value.\n\n Args:\n value (float): A float value that is represented by the leaf.\n ' def __init__(self, value: float) -> None: self.value = value def __str__(self) -> str: 'Returns the string represe...
def _simplify_operator(element: Union[(SparsePauliOp, OpTreeOperator)]) -> Union[(SparsePauliOp, OpTreeOperator)]: if isinstance(element, OpTreeOperator): operator = element.operator input_type = 'leaf' else: operator = element input_type = 'operator' pauli_list = [] co...
class OpTree(): 'Static class containing functions for working with OpTrees objects.' from .optree_derivative import OpTreeDerivative derivative = OpTreeDerivative from .optree_evaluate import OpTreeEvaluate evaluate = OpTreeEvaluate @staticmethod def hash_circuit(circuit: QuantumCircuit)...
def _circuit_parameter_shift(element: Union[(OpTreeCircuit, QuantumCircuit, OpTreeValue)], parameter: ParameterExpression) -> Union[(None, OpTreeSum, OpTreeValue)]: '\n Build the parameter shift derivative of a circuit w.r.t. a single parameter.\n\n Args:\n element (Union[OpTreeLeafCircuit, QuantumCi...
def _operator_differentiation(element: Union[(OpTreeOperator, SparsePauliOp, OpTreeValue)], parameter: ParameterExpression) -> Union[(OpTreeOperator, SparsePauliOp, OpTreeValue)]: '\n Obtain the derivative of an operator w.r.t. a single parameter.\n\n Args:\n element (Union[OpTreeLeafOperator, Sparse...
def _differentiate_inplace(tree_node: OpTreeNodeBase, parameter: ParameterExpression) -> None: '\n Create the derivative of a OpTreeNode w.r.t. a single parameter, modifies the tree inplace.\n\n Functions returns nothing, since the OpTree is modified inplace.\n\n Args:\n tree_node (OpTreeNodeBase)...
def _differentiate_copy(element: Union[(OpTreeNodeBase, OpTreeCircuit, QuantumCircuit, OpTreeOperator, SparsePauliOp)], parameter: ParameterExpression) -> OpTreeNodeBase: '\n Create the derivative of a OpTree or circuit w.r.t. a single parameter, the input is untouched.\n\n Args:\n element (Union[OpT...
class OpTreeDerivative(): 'Static class for differentiation of a OpTrees, circuits, or operators.' SUPPORTED_GATES = {'s', 'sdg', 't', 'tdg', 'ecr', 'sx', 'x', 'y', 'z', 'h', 'rx', 'ry', 'rz', 'p', 'cx', 'cy', 'cz'} @staticmethod def transpile_to_supported_instructions(circuit: QuantumCircuit, suppor...
def get_quantum_fisher(encoding_circuit: EncodingCircuitBase, x: np.ndarray, p: np.ndarray, executor: Executor, mode: str='p'): '\n Function for evaluating the Quantum Fisher Information Matrix of a encoding circuit.\n\n The Quantum Fisher Information Matrix (QFIM) is evaluated the supplied numerical\n f...
class TestLayeredEncodingCircuit(): 'Test class for LayeredEncodingCircuit.' def test_layered_encoding_circuit_gates(self): 'Test the non-parameterized gates of the LayeredEncodingCircuit.' lfm = LayeredEncodingCircuit(num_qubits=4, num_features=0) lfm.H() expected_circuit = Q...
class TestQGPC(): 'Test class for QGPC.' @pytest.fixture(scope='module') def data(self) -> tuple[(np.ndarray, np.ndarray)]: 'Test data module.' (X, y) = make_blobs(n_samples=6, n_features=2, centers=2, random_state=42) scl = MinMaxScaler((0.1, 0.9)) X = scl.fit_transform(X...
class TestQGPR(): 'Test class for QGPR' @pytest.fixture(scope='module') def data(self) -> tuple[(np.ndarray, np.ndarray)]: 'Test data module.' (X, y) = make_regression(n_samples=6, n_features=2, random_state=42) scl = MinMaxScaler((0.1, 0.9)) X = scl.fit_transform(X, y) ...
class TestQKRR(): 'Test class for QKRR' @pytest.fixture(scope='module') def data(self) -> tuple[(np.ndarray, np.ndarray)]: 'Test data module.' (X, y) = make_regression(n_samples=6, n_features=2, random_state=42) scl = MinMaxScaler((0.1, 0.9)) X = scl.fit_transform(X, y) ...
class TestQSVC(): 'Test class for QSVC.' @pytest.fixture(scope='module') def data(self) -> tuple[(np.ndarray, np.ndarray)]: 'Test data module.' (X, y) = make_blobs(n_samples=6, n_features=2, centers=2, random_state=42) scl = MinMaxScaler((0.1, 0.9)) X = scl.fit_transform(X...
class TestQSVR(): 'Test class for QSVR.' @pytest.fixture(scope='module') def data(self) -> tuple[(np.ndarray, np.ndarray)]: 'Test data module.' (X, y) = make_regression(n_samples=6, n_features=2, random_state=42) scl = MinMaxScaler((0.1, 0.9)) X = scl.fit_transform(X, y) ...
class MockBaseQNN(BaseQNN): 'Mock class for BaseQNN.' def _fit(self, X: np.ndarray, y: np.ndarray, weights: np.ndarray=None) -> None: pass
class TestBaseQNN(): 'Test class for BaseQNN.' @pytest.fixture(scope='module') def qnn_single_op(self) -> MockBaseQNN: 'BaseQNN module with single operator.' np.random.seed(42) executor = Executor('statevector_simulator') pqc = ChebyshevPQC(num_qubits=4, num_features=1, nu...
class TestQNNClassifier(): 'Test class for QNNClassifier.' @pytest.fixture(scope='module') def data(self) -> tuple[(np.ndarray, np.ndarray)]: 'Test data module.' (X, y) = make_blobs(n_samples=6, n_features=2, centers=2, random_state=42) scl = MinMaxScaler((0.1, 0.9)) X = s...
class TestQNNRegressor(): 'Test class for QNNRegressor.' @pytest.fixture(scope='module') def data(self) -> tuple[(np.ndarray, np.ndarray)]: 'Test data module.' (X, y) = make_regression(n_samples=6, n_features=1, random_state=42) scl = MinMaxScaler((0.1, 0.9)) X = scl.fit_t...
class TestSolvemini_batch(): 'Tests for mini-batch gradient descent.' pqc = ChebyshevPQC(4, 1, 3, False) cost_op = SummedPaulis(4) qnn = QNN(pqc, cost_op, executor) ex_1 = [np.arange(0.1, 0.9, 0.01), np.log(np.arange(0.1, 0.9, 0.01))] def test_wrong_optimizer(self): 'Test for error ca...
class TestShotsFromRSTD(): 'Tests for ShotsFromRSTD.' def test_qnn_training(self): 'Test a optimization with variance reduction and shots from RSTD.' pqc = ChebyshevPQC(2, 1, 3, False) ob = SummedPaulis(2) executor = Executor('qasm_simulator', primitive_seed=0) qnn = Q...
class TestZeroParam(): 'Tests for zero number of parameters in both observable and encoding circuit.' def _build_qnn_setup(self, pqc, ob, test_case: str): 'Helper function to build the qnn setup.\n\n Args:\n pqc (PQC): encoding circuit\n ob (Observable): observable\n ...
class TestOpTreeDerivative(): 'Test class for OpTree derivatives.' def test_derivative(self): 'Function for comparing analytical and numerical derivatives' p = ParameterVector('p', 1) qc = QuantumCircuit(2) qc.rx((2.0 * p[0]), 0) qc.rx((10.0 * np.arccos(p[0])), 1) ...
class TestOpTreeEvaluation(): 'Test class for OpTree evaluation' @pytest.fixture(scope='module') def _create_random_circuits(self) -> OpTreeList: 'Creates the random circuits used in the tests' circuit1 = random_circuit(2, 2, seed=2).decompose(reps=1) circuit2 = random_circuit(2, ...
class TestExecutor(): @pytest.fixture(scope='module') def ExecutorSampler(self) -> Executor: 'Executor with Sampler initialization.' return Executor(Sampler(), primitive_seed=0) @pytest.fixture(scope='module') def ExecutorEstimator(self) -> Executor: 'Executor with Estimator ...
class kernel(): FULL_KERNEL_3 = np.ones((3, 3), np.uint8) FULL_KERNEL_5 = np.ones((5, 5), np.uint8) FULL_KERNEL_7 = np.ones((7, 7), np.uint8) FULL_KERNEL_9 = np.ones((9, 9), np.uint8) FULL_KERNEL_31 = np.ones((31, 31), np.uint8) def cross_kernel_3(self): self.CROSS_KERNEL_3 = np.asarr...
class DepthCompletion(): def __init__(self): self.main_img_path = os.path.expanduser('dataset\\kitti_validation_cropped\\image') self.input_depth_dir = os.path.expanduser('dataset\\kitti_validation_cropped\\velodyne_raw') self.img_size = (450, 130) def save_for_evaluation(self, suffi...
class Metrics(): def calculate_metrics_mm(self, output, gt_item): valid_mask = (gt_item > 0.1) output_mm = (1000.0 * output[valid_mask]) gt_mm = (1000.0 * gt_item[valid_mask]) diff = np.abs((output_mm - gt_mm)) mse = np.mean(np.power(diff, 2)) rmse = np.sqrt(mse) ...
def print_metrics(): print('Calculating Metrics ....') x = Metrics() mae = [] rmse = [] for i in range(len(gt)): (_rmse, _mae) = x.calculate_metrics_mm(results[i], gt[i]) rmse.append(_rmse) mae.append(_mae) print('Evaluation Metrics : \n \nAverage RMSE = {h1} \nAver...
class Config(object): def __init__(self, filename): lines = open(filename).readlines() lines = [(l if (not l.strip().startswith('#')) else '\n') for l in lines] s = ''.join(lines) self._entries = json.loads(s, object_pairs_hook=OrderedDict) def has(self, key): return ...
class Engine(): def __init__(self, config, session=None): self.config = config self.save = config.bool('save', True) self.task = config.string('task', 'train') self.dataset = config.string('dataset').lower() self.num_epochs = config.int('num_epochs', 1000) self.ses...
def accumulate_extractions(extractions_accumulator, *new_extractions): if (len(new_extractions) == 0): return if (len(extractions_accumulator) == 0): extractions_accumulator.update(new_extractions[0]) new_extractions = new_extractions[1:] for (k, v) in extractions_accumulator.items...
class Stream(): def __init__(self, log, lvl): '\n :type log: logging.Logger\n :type lvl: int\n ' self.buf = StringIO.StringIO() self.log = log self.lvl = lvl self.lock = RLock() def write(self, msg): with self.lock: if (msg == '\n'): ...
class Log(object): def initialize(self, logs=[], verbosity=[], formatter=[]): fmt = {'default': logging.Formatter('%(message)s'), 'timed': logging.Formatter('%(asctime)s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S.%MS'), 'raw': logging.Formatter('%(message)s'), 'verbose': logging.Formatter('%(levelname)s - ...
def accumulate_measures(measures_accumulator, *new_measures, exclude=[DET_BOXES, DET_PROBS, DET_LABELS, DET_MASKS, IMAGE_ID]): if (len(new_measures) == 0): return if (len(measures_accumulator) == 0): measures_accumulator.update(new_measures[0]) new_measures = new_measures[1:] for (...
def compute_measures_average(measures, for_final_result, exclude=[DET_BOXES, DET_PROBS, DET_LABELS, DET_MASKS, IMAGE_ID]): measures_avg = {} n_examples = measures[N_EXAMPLES] for (k, v) in measures.items(): if (k not in exclude): measures_avg[k] = (measures[k] / n_examples) del mea...
def measures_string_to_print(measures, exclude=[DET_BOXES, DET_PROBS, DET_LABELS, DET_MASKS, IMAGE_ID]): s = '{' first = True measures_to_print = [m for m in measures.keys() if (m not in exclude)] for k in sorted(measures_to_print): s += '{}{}: {:8.5}'.format(('' if first else ', '), k, measur...
def compute_measures_for_binary_segmentation_tf(predictions, targets): def f(ps, ts): meas = compute_measures_for_binary_segmentation_summed(ps, ts) meas = [np.cast[np.float32](meas[IOU]), np.cast[np.float32](meas[RECALL]), np.cast[np.float32](meas[PRECISION])] return meas res = tf.py...
def compute_measures_for_binary_segmentation_summed(predictions, targets): res = [compute_measures_for_binary_segmentation_single_image(p, t) for (p, t) in zip(predictions, targets)] accum = res[0] for r in res[1:]: for (k, v) in r.items(): accum[k] += v return accum
def compute_measures_for_binary_segmentation_single_image(prediction, target): assert ((target.ndim == 2) or ((target.ndim == 3) and (target.shape[(- 1)] == 1))) valid_mask = (target != VOID_LABEL) T = np.logical_and(target, valid_mask).sum() P = np.logical_and(prediction, valid_mask).sum() I = np...
class Timer(): def __init__(self, message='', stream=None): if (stream is None): from core.Log import log stream = log.v4 self.stream = stream self.start_time = time.time() self.message = message def __enter__(self): self.start_time = time.time...
class Trainer(): def __init__(self, config, train_network, test_network, global_step, session): self.opt_str = config.string('optimizer', 'adam').lower() self.train_network = train_network self.test_network = test_network self.session = session self.global_step = global_st...
class Augmentor(): def apply_before_resize(self, tensors): return tensors def apply_after_resize(self, tensors): return tensors def batch_apply_before_resize(self, tensors_batch): return tensors_batch def batch_apply_after_resize(self, tensors_batch): return tensors...
class GammaAugmentor(Augmentor): def __init__(self, gamma_range=((- 0.1), 0.1)): self.gamma_range = gamma_range def apply_after_resize(self, tensors, factor=None): '\n Augments the images. Expects it to be in the [0, 1] range\n ' with tf.name_scope('gamma_augmentor'): ...
class FlipAugmentor(Augmentor): def __init__(self, p=0.5): '\n :param p: The probability that the image will be flipped.\n ' self.p = p def apply_after_resize(self, tensors, doit=None): with tf.name_scope('flip_augmentor'): aug_tensors = tensors.copy() i...
class BBoxJitterAugmentor(Augmentor): def __init__(self, v=0.15): self.v = v def apply_before_resize(self, tensors, g=None): if (DataKeys.BBOXES_y0x0y1x1 in tensors): (y0, x0, y1, x1) = tf.unstack(tf.cast(tensors[DataKeys.BBOXES_y0x0y1x1], tf.float32)) if (g is None):...
def parse_augmentors(strs, config): augmentors = [] for s in strs: if (s == 'gamma'): augmentor = GammaAugmentor(gamma_range=((- 0.05), 0.05)) elif (s == 'flip'): augmentor = FlipAugmentor() elif (s == 'bbox_jitter'): v = config.float('bbox_jitter_fa...
def read_image_and_annotation_list(fn, data_dir): imgs = [] ans = [] with open(fn) as f: for l in f: sp = l.split() an = (data_dir + sp[1]) im = (data_dir + sp[0]) imgs.append(im) ans.append(an) return (imgs, ans)
def get_input_list_file(subset, trainsplit): if (subset == 'train'): if (trainsplit == 0): return 'ImageSets/480p/train.txt' elif (trainsplit == 1): return 'ImageSets/480p/trainsplit_train.txt' elif (trainsplit == 2): return 'ImageSets/480p/trainsplit2_t...
@register_dataset('davis') class DAVISDataset(FileListDataset): def __init__(self, config, subset, num_classes, name='davis16'): super().__init__(config, name, subset, DAVIS_DEFAULT_PATH, num_classes) self.trainsplit = config.int('trainsplit', 0) def postproc_annotation(self, ann_filename, a...
def postproc_2017_labels(labels): return tf.cast((tf.reduce_max(labels, axis=2, keep_dims=True) > 0), tf.uint8)
def get_input_list_file_2017(subset): if (subset == 'train'): return 'ImageSets/2017/train.txt' elif (subset == 'valid'): return 'ImageSets/2017/val.txt' else: assert False, ('invalid subset', subset)
def read_image_and_annotation_list_2017(fn, data_dir): imgs = [] ans = [] with open(fn) as f: for seq in f: seq = seq.strip() base_seq = seq.split('__')[0] imgs_seq = sorted(glob.glob((((data_dir + 'JPEGImages/480p/') + base_seq) + '/*.jpg'))) ans_se...
@register_dataset('davis17') @register_dataset('davis2017') class DAVIS2017Dataset(FileListDataset): def __init__(self, config, subset, num_classes, name='davis17'): super().__init__(config, name, subset, DAVIS2017_DEFAULT_PATH, num_classes) def read_inputfile_lists(self): assert (self.subse...
class AbstractDataset(ABC): def __init__(self, config, subset, num_classes): self.summaries = [] self.config = config self.subset = subset self.n_classes = num_classes self.use_bbox_guidance = config.bool('use_bbox_guidance', False) self.use_unsigned_distance_trans...
class FileListDataset(AbstractDataset): def __init__(self, config, dataset_name, subset, default_path, num_classes): super().__init__(config, subset, num_classes) self.inputfile_lists = None self.fraction = config.float('data_fraction', 1.0) self.data_dir = config.string((dataset_...
class DetectionFileListDataset(FileListDataset): def __init__(self, config, dataset_name, subset, default_path, num_classes, n_max_detections, class_ids_with_instances, id_divisor): super().__init__(config, dataset_name, subset, default_path, num_classes) self.add_masks = config.bool('add_masks',...
class FeedDataset(AbstractDataset): def __init__(self, config, subset, data_keys_to_use, num_classes=2): super().__init__(config, subset, num_classes) self._data_keys_to_use = data_keys_to_use self._batch_size = (- 1) if (subset == 'val'): self._batch_size = config.int...
@register_dataset(NAME) class GrabcutDataset(FileListDataset): def __init__(self, config, subset, name=NAME): super().__init__(config, dataset_name=name, subset=subset, default_path=DEFAULT_PATH, num_classes=2) def postproc_annotation(self, ann_filename, ann): ann_postproc = tf.where(tf.equa...
@register_dataset(NAME) class KITTIMaskedDiosDataset(KITTIMturkersInstanceDataset): def __init__(self, config, subset, name=NAME): super().__init__(config, subset, name) def get_extraction_keys(self): return self.pascal_masked_dataset.get_extraction_keys() def postproc_example_before_as...
@register_dataset(NAME) class KITTIMturkersInstanceDataset(FileListDataset): def __init__(self, config, subset, name=NAME): super(KITTIMturkersInstanceDataset, self).__init__(config, name, subset, DEFAULT_PATH, 2) def read_inputfile_lists(self): files = glob.glob((self.data_dir + 'object/seg...
def register_dataset(name, **args): name = name.lower() def _register(dataset): _registered_datasets[name] = (dataset, args) return dataset return _register
def load_dataset(config, subset, session, name): if (not hasattr(load_dataset, '_imported')): load_dataset._imported = True import_submodules('datasets') name = name.lower() if (name not in _registered_datasets): raise ValueError((('dataset ' + name) + ' not registered.')) (dat...
@register_dataset(NAME) class PascalVOCDataset(FileListDataset): def __init__(self, config, name, subset, num_classes): data_dir = config.string('data_dir', DEFAULT_PATH) super().__init__(config, name, subset, data_dir, num_classes) def read_inputfile_lists(self): data_list = ('train...
def normalize(img, img_mean=IMAGENET_RGB_MEAN, img_std=IMAGENET_RGB_STD): if hasattr(img, 'get_shape'): l = img.get_shape()[(- 1)] if ((img_mean is not None) and (l != img_mean.size)): img_mean = np.concatenate([img_mean, np.zeros((l - img_mean.size), dtype='float32')], axis=0) ...
def unnormalize(img, img_mean=IMAGENET_RGB_MEAN, img_std=IMAGENET_RGB_STD): if hasattr(img, 'get_shape'): l = img.get_shape()[(- 1)] if ((img_mean is not None) and (l != img_mean.size)): img_mean = np.concatenate([img_mean, np.zeros((l - img_mean.size), dtype='float32')], axis=0) ...
def save_with_pascal_colormap(filename, arr): colmap = (np.array(pascal_colormap) * 255).round().astype('uint8') palimage = Image.new('P', (16, 16)) palimage.putpalette(colmap) im = Image.fromarray(np.squeeze(arr.astype('uint8'))) im2 = im.quantize(palette=palimage) im2.save(filename)
class Forwarder(ABC): def __init__(self, engine): self.engine = engine self.config = engine.config self.session = engine.session self.val_data = self.engine.valid_data self.train_data = self.engine.train_data self.trainer = self.engine.trainer self.saver = ...
def init_log(config): log_dir = config.dir('log_dir', 'logs') model = config.string('model') filename = ((log_dir + model) + '.log') verbosity = config.int('log_verbosity', 3) log.initialize([filename], [verbosity], [])
def main(_): assert (len(sys.argv) == 2), 'usage: main.py <config>' config_path = sys.argv[1] assert os.path.exists(config_path), config_path try: config = Config(config_path) except ValueError as e: print('Malformed config file:', e) return (- 1) init_log(config) p...
class Conv(Layer): output_layer = False def __init__(self, name, inputs, n_features, tower_setup, filter_size=(3, 3), old_order=False, strides=(1, 1), dilation=None, pool_size=(1, 1), pool_strides=None, activation='relu', dropout=0.0, batch_norm=False, bias=False, batch_norm_decay=Layer.BATCH_NORM_DECAY_DEFA...
class ConvTranspose(Layer): output_layer = False def __init__(self, name, inputs, n_features, tower_setup, filter_size=(3, 3), strides=(1, 1), activation='relu', batch_norm=False, bias=False, batch_norm_decay=Layer.BATCH_NORM_DECAY_DEFAULT, l2=Layer.L2_DEFAULT, padding='SAME'): super(ConvTranspose, s...
class ConvForOutput(Layer): output_layer = False def __init__(self, name, inputs, dataset, n_features, tower_setup, filter_size=(1, 1), input_activation=None, dilation=None, l2=Layer.L2_DEFAULT, dropout=0.0): super().__init__() if (n_features == (- 1)): n_features = dataset.num_cl...
class ResidualUnit(Layer): output_layer = False def __init__(self, name, inputs, tower_setup, n_convs=2, n_features=None, dilations=None, strides=None, filter_size=None, activation='relu', dropout=0.0, batch_norm_decay=Layer.BATCH_NORM_DECAY_DEFAULT, l2=Layer.L2_DEFAULT): super().__init__() (...
class Upsampling(Layer): def __init__(self, name, inputs, tower_setup, n_features, concat, activation='relu', filter_size=(3, 3), l2=Layer.L2_DEFAULT): super(Upsampling, self).__init__() filter_size = list(filter_size) assert isinstance(concat, list) assert (len(concat) > 0) ...
class FullyConnected(Layer): def __init__(self, name, inputs, n_features, tower_setup, activation='relu', dropout=0.0, batch_norm=False, batch_norm_decay=Layer.BATCH_NORM_DECAY_DEFAULT, l2=Layer.L2_DEFAULT): super(FullyConnected, self).__init__() (inp, n_features_inp) = prepare_input(inputs) ...
class Layer(): BATCH_NORM_DECAY_DEFAULT = 0.95 BATCH_NORM_EPSILON = 1e-05 L2_DEFAULT = 0.0001 def __init__(self): self.summaries = [] self.regularizers = [] self.losses = [] self.update_ops = [] self.outputs = [] self.measures = {} self.extracti...
class Network(): def __init__(self, config, dataset, is_trainnet, freeze_batchnorm, name, reuse_variables=None): self.name = name self.batch_size = (- 1) if (not is_trainnet): self.batch_size = config.int('batch_size_eval', (- 1)) if (self.batch_size == (- 1)): ...
def get_layer_class(layer_class): if (not hasattr(get_layer_class, '_imported')): get_layer_class._imported = True import_submodules('network') constructors = [l for l in Layer.__subclasses__() if (l.__name__ == layer_class)] assert (len(constructors) == 1), constructors class_ = const...
class TowerSetup(): def __init__(self, gpu_idx, reuse_variables, dataset, variable_device, is_main_train_tower, is_training, freeze_batchnorm, network_name, use_weight_summaries=False): self.gpu_idx = gpu_idx self.reuse_variables = reuse_variables self.dataset = dataset self.varia...
class NetworkTower(): def __init__(self, config, tower_setup, input_tensors_dict, dataset): network_def = config.dict('network') self.setup = tower_setup self.layers = {} self.summaries = [] self.losses = [] self.regularizers = [] self.update_ops = [] ...
class SegmentationSoftmax(Layer): output_layer = True def __init__(self, name, inputs, dataset, network_input_dict, tower_setup, resize_targets=False, resize_logits=False, loss='ce', fraction=None): super().__init__() self.n_classes = dataset.num_classes() targets = network_input_dict...
def conv2d(x, W, strides=(1, 1), padding='SAME'): strides = list(strides) return tf.nn.conv2d(x, W, strides=(([1] + strides) + [1]), padding=padding)
def conv2d_transpose(x, W, strides=(1, 1), padding='SAME'): strides = list(strides) W_shape = tf.shape(W) inputs_shape = tf.shape(x) out_height = deconv_output_length(inputs_shape[1], W_shape[0], padding, strides[0]) out_width = deconv_output_length(inputs_shape[2], W_shape[1], padding, strides[1]...
def conv2d_dilated(x, W, dilation, padding='SAME'): res = tf.nn.atrous_conv2d(x, W, dilation, padding=padding) shape = x.get_shape().as_list() shape[(- 1)] = W.get_shape().as_list()[(- 1)] res.set_shape(shape) return res
def create_batch_norm_vars(n_out, tower_setup, scope_name='bn'): with tf.device(tower_setup.variable_device), tf.variable_scope(scope_name): initializer_zero = tf.constant_initializer(0.0, dtype=tf.float32) beta = tf.get_variable('beta', [n_out], tf.float32, initializer_zero) initializer_g...
def get_activation(act_str): assert (act_str.lower() in _activations), ('Unknown activation function ' + act_str) return _activations[act_str.lower()]
def prepare_input(inputs): if (len(inputs) == 1): inp = inputs[0] dim = int(inp.get_shape()[(- 1)]) else: dims = [int(inp.get_shape()[3]) for inp in inputs] dim = sum(dims) inp = tf.concat(inputs, axis=3) return (inp, dim)
def apply_dropout(inp, dropout): if (dropout == 0.0): return inp else: keep_prob = (1.0 - dropout) return tf.nn.dropout(inp, keep_prob)
def max_pool(x, shape, strides=None, padding='SAME'): if (strides is None): strides = shape return tf.nn.max_pool(x, ksize=(([1] + shape) + [1]), strides=(([1] + strides) + [1]), padding=padding)
def bootstrapped_ce_loss(raw_ce, fraction, n_valid_pixels_per_im): ks = tf.maximum(tf.cast(tf.round((tf.cast(n_valid_pixels_per_im, tf.float32) * fraction)), tf.int32), 1) def bootstrapped_ce_for_one_img(args): (one_ce, k) = args hardest = tf.nn.top_k(tf.reshape(one_ce, [(- 1)]), k, sorted=Fa...
def class_balanced_ce_loss(raw_ce, targets, n_classes): def class_balanced_ce_for_one_img(args): (ce, target) = args cls_losses = [] for cls in range(n_classes): cls_mask = tf.equal(target, cls) n_cls = tf.reduce_sum(tf.cast(cls_mask, tf.int32)) cls_los...
def _mobilenet_v2(net, depth_multiplier, output_stride, reuse=None, scope=None, final_endpoint=None): "Auxiliary function to add support for 'reuse' to mobilenet_v2.\n\n Args:\n net: Input tensor of shape [batch_size, height, width, channels].\n depth_multiplier: Float multiplier for the depth (number of c...