How to use _get_session method in Molotov

Best Python code snippet using molotov_python

cli.py

Source:cli.py Github

copy

Full Screen

...125 'profile': _train_keys,126 'test': _test_keys,127 'validate': _validate_keys,128 }129 def _get_session(self, action=None):130 if not action:131 if self.session:132 return self.session133 keys = self._train_keys134 if self._validate_config(keys, 'train', test=True):135 self.session = self._get_session('train')136 else:137 self.session = self._get_session('validate')138 return self.session139 keys = self._model_keys + self._dataset_keys140 try:141 cls = self._session_map[action]142 keys += self._keys_map[action]143 except KeyError:144 raise TypeError('Action {!r} not recognized.'.format(action))145 self._validate_config(keys, action)146 if not isinstance(self.session, cls):147 log.info('Starting a {} session...'.format(action))148 self.session = cls(self.config)149 return self.session150 def cli_profile_timeline(self):151 """Performs training profiling to produce timeline.json. """152 # TODO integrate this into Profile.153 from tensorflow.python.client import timeline154 options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)155 run_metadata = tf.RunMetadata()156 session = self._get_session('train')157 # run 100 iterations to warm up158 max_iterations = 100159 for i in range(max_iterations):160 log.info(161 'Running {}/{} iterations to warm up...'162 .format(i, max_iterations), update=True)163 session.run(session._train_op)164 log.info('Running the final iteration to generate timeline...')165 session.run(166 session._train_op, options=options, run_metadata=run_metadata)167 fetched_timeline = timeline.Timeline(run_metadata.step_stats)168 chrome_trace = fetched_timeline.generate_chrome_trace_format()169 with open('timeline.json', 'w') as f:170 f.write(chrome_trace)171 def cli_plot(self):172 """Plots activation maps as images and parameters as histograms."""173 return self._get_session('validate').plot()174 def cli_train(self):175 """Performs training. """176 return self._get_session('train').train()177 def cli_search(self):178 """Performs automated hyperparameter search. """179 return self._get_session('search').search()180 def cli_profile(self):181 """Performs profiling. """182 return self._get_session('profile').profile()183 def cli_eval(self):184 """Evaluates the accuracy of a saved model. """185 return self._get_session('validate').eval()186 def cli_eval_all(self):187 """Evaluates all checkpoints for accuracy. """188 result = self._get_session('validate').eval_all()189 file_name = 'eval_all.csv'190 with open(file_name, 'w') as f:191 f.write(result.csv())192 log.info(193 'Evaluation results saved in {!r}.'.format(file_name))194 def cli_test(self):195 """Perform inference for custom test data. """196 return self._get_session('test').test()197 def cli_overriders_update(self):198 """Updates variable overriders in the training session. """199 self._get_session('train').overriders_update()200 def cli_overriders_assign(self):201 """Assign overridden values to original parameters. """202 self._get_session('train').overriders_assign()203 self._get_session('train').save_checkpoint('assigned')204 def cli_overriders_reset(self):205 """Reset the internal state of overriders. """206 self._get_session('train').overriders_reset()207 def cli_overriders_dump(self):208 """Export the internal parameters of overriders. """209 self._get_session().overriders_dump()210 def cli_reset_num_epochs(self):211 """Resets the number of training epochs. """212 self._get_session('train').reset_num_epochs()213 def cli_export(self):214 """Exports the current config. """215 name = 'export.yaml'216 with open(name, 'w') as f:217 f.write(self.config.to_yaml())218 log.info('Config successfully exported to {!r}.'.format(name))219 def cli_info(self):220 """Prints parameter and layer info of the model. """221 plumbing = self.config.system.info.get('plumbing')222 info = self._get_session().info(plumbing)223 if plumbing:224 with open('info.yaml', 'w') as f:225 yaml.dump(info, f)226 else:227 for key in ('trainables', 'nontrainables', 'layers'):228 print(info[key].format())229 for table in info.get('overriders', {}).values():230 print(table.format())231 def cli_interact(self):232 """Interacts with the train/eval session using iPython. """233 self._get_session().interact()234 def cli_save(self):235 """Saves the latest checkpoint. """236 self.session.checkpoint.save('latest')237 def _purge_session(self):238 if not self.session:239 return240 log.info('Purging current session because config is updated...')241 del self.session242 self.session = None243 def main(self, args=None):244 if args is None:245 args = docopt(self.usage(), version=meta()['__version__'])246 anything = args['<anything>']247 commands = self.commands()...

Full Screen

Full Screen

test_pyxis.py

Source:test_pyxis.py Github

copy

Full Screen

...9 monkeypatch.setenv("PYXIS_KEY_PATH", "/path/to/key.key")10 assert pyxis.is_internal()11def test_get_session_api_key(monkeypatch: Any) -> None:12 monkeypatch.setenv("PYXIS_API_KEY", "123")13 session = pyxis._get_session()14 assert session.headers["X-API-KEY"] == "123"15def test_get_session_cert(monkeypatch: Any) -> None:16 monkeypatch.setenv("PYXIS_CERT_PATH", "/path/to/cert.pem")17 monkeypatch.setenv("PYXIS_KEY_PATH", "/path/to/key.key")18 session = pyxis._get_session()19 assert session.cert == ("/path/to/cert.pem", "/path/to/key.key")20def test_get_session_no_auth(monkeypatch: Any) -> None:21 with pytest.raises(Exception):22 pyxis._get_session()23@patch("operatorcert.pyxis._get_session")24def test_post(mock_session: MagicMock) -> None:25 mock_session.return_value.post.return_value.json.return_value = {"key": "val"}26 resp = pyxis.post("https://foo.com/v1/bar", {})27 assert resp == {"key": "val"}28@patch("operatorcert.pyxis._get_session")29def test_patch(mock_session: MagicMock) -> None:30 mock_session.return_value.patch.return_value.json.return_value = {"key": "val"}31 resp = pyxis.patch("https://foo.com/v1/bar", {})32 assert resp == {"key": "val"}33@patch("operatorcert.pyxis._get_session")34def test_patch_error(mock_session: MagicMock) -> None:35 response = Response()36 response.status_code = 400...

Full Screen

Full Screen

m.py

Source:m.py Github

copy

Full Screen

...55 def set_lr(self, lr):56 '''set_lr to update learning rate. call this at least once.'''57 self.lr = lr58 print("learning rate to: ", lr)59 def _get_session(self):60 if self.session is None:61 global_step = tf.contrib.framework.get_or_create_global_step()62 self.lrt = tf.placeholder(tf.float32, shape=[])63 self.train_op = self.optimizer_cls(learning_rate=self.lrt).minimize(self.loss,64 global_step=global_step)65 self.session = tf.Session()66 self.session.run(tf.global_variables_initializer())67 return self.session68 def fit(self, x, y, epochs=1, verbose=True, log_every=1):69 '''fit to fix predictions to labels.'''70 losses = []71 with self.graph.as_default():72 sess = self._get_session()73 for _ in range(epochs):74 ops = [self.loss, self.train_op]75 if self.tensorboard_dir:76 ops.append(self.merged)77 r = sess.run(ops, feed_dict={78 self.input: x, self.labels: y, self.lrt: self.lr})79 self.fit_iterations += 180 if verbose:81 if self.fit_iterations % log_every == 0:82 print("Loss: ", r[0])83 losses.append(r[0])84 if self.tensorboard_dir:85 self.tb_writer.add_summary(r[2], self.fit_iterations)86 return losses87 def predict(self, x):88 '''predict to make prediction from observation.'''89 with self.graph.as_default():90 sess = self._get_session()91 res = sess.run(self.prediction, feed_dict={self.input: x})92 return res93 def evaluate(self, x, y):94 with self.graph.as_default():95 sess = self._get_session()96 loss = sess.run(self.loss, feed_dict={97 self.input: x, self.labels: y, self.lrt: self.lr})98 return loss99 def add(self, l):100 '''101 Add this later to the model. We will take care of the unique naming102 '''103 if len(self._layers) == 0:104 self.input = l105 self.output = l106 self._layers.append(l)107 def __repr__(self):108 return '\n\n'.join([str(x) + ': ' + str(l) for x, l in enumerate(self._layers)])109 def save(self, filename):110 '''save graph'''111 with self.graph.as_default():112 saver = tf.train.Saver()113 saver.save(self._get_session(), filename)114 def load(self, filename):115 '''load graph'''116 with self.graph.as_default():117 saver = tf.train.Saver()118 saver.restore(self._get_session(), filename)119 def close(self):120 if self.session:121 self.session.close()...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Molotov automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful