Best Python code snippet using slash
net_component.py
Source:net_component.py  
1from lib.config import cfg2from lib.utils import print_tensor_shapes, compute_sequence_length, get_trainable_variables_by_scope3import tensorflow as tf4import tensorflow.contrib.slim as slim5class NetComponent(object):6    """A network component.7    Simply an architecture without a loss or placeholders. Heavily modeled after the Network class.8    """9    def __init__(self, is_training, reuse=False, name='network_component', no_scope=False):10        self._name = name11        self._is_training = is_training12        self._reuse = reuse13        self._no_scope = no_scope14        self._outputs = None15        self._vars_to_restore = None16    def get_trainable_variables(self):17        """Return the trainable variables in the specified scope.18        Args:19            scope_name: Name of the scope as a string.20        Returns:21            trainable_vars: TensorFlow variables that are trainable and in the22                specified scope.23        """24        if self._no_scope is True:25            trainable_vars = self._trainable_vars26        else:27            trainable_vars = get_trainable_variables_by_scope(self.name)28        return trainable_vars29    def build_architecture(self, inputs_dict):30        """Build the architecture, not including placeholders and preprocessing.31        """32        raise NotImplementedError('Must be implemented by a subclass.')33    def build_model(self, inputs_dict):34        """Build the network component, without placeholders and loss.35        """36        print('building network:', self.name)37        def _build_model():38            self._outputs = self.build_architecture(inputs_dict)39            # Create summaries for network outputs40            if isinstance(self._outputs, dict):41                for k, v in self._outputs.items():42                    if isinstance(v, tf.Tensor):43                        tf.summary.histogram(k + '_hist_summary', v)44        if self._no_scope is True:45            _build_model()46            cur_variable_scope = tf.get_variable_scope()47            self._vars_to_restore = slim.get_variables_to_restore(include=[cur_variable_scope])48            self._trainable_vars = get_trainable_variables_by_scope(cur_variable_scope.name)49        else:50            with tf.variable_scope(self.name, reuse=self.reuse) as sc:51                _build_model()52                self._vars_to_restore = slim.get_variables_to_restore(include=[sc.name])53        print('--> done building {}'.format(self.name))54    @property55    def name(self):56        return self._name57    @property58    def outputs(self):59        return self._outputs60    @property61    def is_training(self):62        return self._is_training63    @property64    def vars_to_restore(self):65        return self._vars_to_restore66    @property67    def reuse(self):68        return self._reuse69class TextEncoderNetComponent(NetComponent):70    def __init__(self, is_training, reuse=False, name='text_encoder_net_component'):71        super(TextEncoderNetComponent, self).__init__(is_training, reuse=reuse, name=name)72    def preprocess_inputs(self, inputs_dict):73        caption_batch, vocab_size = (inputs_dict['caption_batch'], inputs_dict['vocab_size'])74        input_batch = caption_batch75        print('--> building embedding layer')76        with tf.variable_scope('embedding_layer', reuse=self.reuse):77            embeddings = tf.Variable(78                tf.random_uniform([vocab_size, self.embedding_size], -1.0, 1.0),79                name='embedding_matrix')80            embedding_batch = tf.nn.embedding_lookup(embeddings,81                                                     input_batch,82                                                     name='input_embedding_batch')83            # print shapes84            print_tensor_shapes([embedding_batch], prefix='----> ')85        seq_length = compute_sequence_length(input_batch)86        return {'embedding_batch': embedding_batch,87                'seq_length': seq_length}88    def build_model(self, inputs_dict):89        """Build the network component, without placeholders and loss.90        """91        print('building network:', self.name)92        with tf.variable_scope(self.name, reuse=self.reuse) as sc:93            processed_inputs = self.preprocess_inputs(inputs_dict)94            arch_inputs_dict = {**inputs_dict, **processed_inputs}  # Combine dicts95            self._outputs = self.build_architecture(arch_inputs_dict)96            # Create summaries for network outputs97            if isinstance(self._outputs, dict):98                for k, v in self._outputs.items():99                    if isinstance(v, tf.Tensor):100                        tf.summary.histogram(k + '_hist_summary', v)101            self._vars_to_restore = slim.get_variables_to_restore(include=[sc.name])102        print('--> done building {}'.format(self.name))103    @property104    def embedding_size(self):105        raise NotImplementedError('Must be implemented by a subclass.')106class LBANetComponent(NetComponent):107    def __init__(self, is_training, reuse=False, name='lba_net_component', no_scope=False):108        super(LBANetComponent, self).__init__(is_training, reuse=reuse, name=name,109                                              no_scope=no_scope)110    def build_architecture(self, inputs_dict):111        """Build the architecture, not including placeholders and preprocessing.112        Literally copy and pasted from lib.LBA (sorry!).113        """114        text_inputs_dict = {115            'caption_batch': inputs_dict['raw_embedding_batch'],116            'vocab_size': inputs_dict['vocab_size'],117        }118        self.text_encoder = self.text_encoder_class(self.is_training, self.reuse)119        self.text_encoder.build_model(text_inputs_dict)120        shape_inputs_dict = {'shape_batch': inputs_dict['shape_batch']}121        self.shape_encoder = self.shape_encoder_class(self.is_training, self.reuse)122        self.shape_encoder.build_model(shape_inputs_dict)123        # Change 'encoder_output' to be normalized124        if cfg.LBA.NORMALIZE is True:125            assert 'encoder_output' in self.text_encoder.outputs126            orig_text_encoder_output = self.text_encoder.outputs['encoder_output']127            self.text_encoder.outputs['encoder_output'] = tf.nn.l2_normalize(128                orig_text_encoder_output,129                dim=1,130                name='normalize_text_encoding',131            )132            assert 'encoder_output' in self.shape_encoder.outputs133            orig_shape_encoder_output = self.shape_encoder.outputs['encoder_output']134            self.shape_encoder.outputs['encoder_output'] = tf.nn.l2_normalize(135                orig_shape_encoder_output,136                dim=1,137                name='normalize_shape_encoding',138            )139        return {140            'text_encoder': self.text_encoder.outputs,141            'shape_encoder': self.shape_encoder.outputs,142        }143    @property144    def text_encoder_class(self):145        raise NotImplementedError('Must be implemented by a subclass.')146    @property147    def shape_encoder_class(self):148        raise NotImplementedError('Must be implemented by a subclass.')149class CriticNetComponent(NetComponent):150    def __init__(self, is_training, reuse=False, name='critic_net_component'):...test_scope_manager.py
Source:test_scope_manager.py  
...54        def session_validation():55            assert slash.get_current_scope() == 'session'56        @gossip.register('slash.configure', token=TOKEN)57        @gossip.register('slash.app_quit', token=TOKEN)58        def _no_scope():59            assert slash.get_current_scope() is None60        def test_something():61            assert slash.get_current_scope() == 'test'62        gossip.unregister_token(TOKEN)63    suite_builder.build().run().assert_success(1)64    assert get_current_scope() is None65@pytest.fixture66def scope_manager(dummy_fixture_store, forge):67    session = slash.Session()68    forge.replace_with(session, 'fixture_store', dummy_fixture_store)69    return ScopeManager(session)70@pytest.fixture71def dummy_fixture_store():72    return DummyFixtureStore()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
