我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用tensorflow.python.framework.ops.reset_default_graph()。
def begin_session(self): """ Begins the session :return: None """ # start the tensorflow session ops.reset_default_graph() # initialize interactive session self.sess = tf.Session()
def fit(self, X, y): y = np.array(y) unique_y = np.unique(y) for yi in unique_y: # Neural network models for user T192 originally did not converge due to parameter initialization # Use a different seed to choose different initial parameters. The models seem to converge with seed 2016. if yi == 'T192': np.random.seed(2016) Xi = X[y == yi] target_input = events2keynames(min(Xi, key=len)[:, 0]) if self.align == 'drop': target_input, _ = character_keys_only(target_input) self.target_inputs[yi] = target_input Xi = np.array([fixedtext_features(x, self.target_inputs[yi], align=self.align) for x in Xi]) self.models[yi] = self.model_factory() if self.feature_normalization == 'stddev': self.duration_mins[yi] = Xi[:, 0::2].mean() - Xi[:, 0::2].std() self.duration_maxs[yi] = Xi[:, 0::2].mean() + Xi[:, 0::2].std() self.latency_mins[yi] = Xi[:, 1::2].mean() - Xi[:, 1::2].std() self.latency_maxs[yi] = Xi[:, 1::2].mean() + Xi[:, 1::2].std() elif self.feature_normalization == 'minmax': self.duration_mins[yi] = Xi[:, 0::2].min() self.duration_maxs[yi] = Xi[:, 0::2].max() self.latency_mins[yi] = Xi[:, 1::2].min() self.latency_maxs[yi] = Xi[:, 1::2].max() Xi = self.normalize(Xi, yi) from tensorflow.python.framework import ops ops.reset_default_graph() self.models[yi].fit(Xi) return
def clear_session(): """Destroys the current TF graph and creates a new one. Useful to avoid clutter from old models / layers. """ global _SESSION global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned ops.reset_default_graph() reset_uids() _SESSION = None phase = array_ops.placeholder(dtype='bool', name='keras_learning_phase') _GRAPH_LEARNING_PHASES = {} _GRAPH_LEARNING_PHASES[ops.get_default_graph()] = phase
def __setstate__(self, state): from tensorflow.python.framework import ops ops.reset_default_graph() # we need to destroy the default graph before re_init or checkpoint won't restore. self.__init__(state['hyperparams'], state['dO'], state['dU']) self.policy.scale = state['scale'] self.policy.bias = state['bias'] self.policy.x_idx = state['x_idx'] self.policy.chol_pol_covar = state['chol_pol_covar'] self.tf_iter = state['tf_iter'] with tempfile.NamedTemporaryFile('w+b', delete=True) as f: f.write(state['wts']) f.seek(0) self.restore_model(f.name)
def load_policy(cls, policy_dict_path, tf_generator, network_config=None): """ For when we only need to load a policy for the forward pass. For instance, to run on the robot from a checkpointed policy. """ from tensorflow.python.framework import ops ops.reset_default_graph() # we need to destroy the default graph before re_init or checkpoint won't restore. pol_dict = pickle.load(open(policy_dict_path, "rb")) tf_map = tf_generator(dim_input=pol_dict['deg_obs'], dim_output=pol_dict['deg_action'], batch_size=1, network_config=network_config) sess = tf.Session() init_op = tf.initialize_all_variables() sess.run(init_op) saver = tf.train.Saver() check_file = pol_dict['checkpoint_path_tf'] saver.restore(sess, check_file) device_string = pol_dict['device_string'] cls_init = cls(pol_dict['deg_action'], tf_map.get_input_tensor(), tf_map.get_output_op(), np.zeros((1,)), sess, device_string) cls_init.chol_pol_covar = pol_dict['chol_pol_covar'] cls_init.scale = pol_dict['scale'] cls_init.bias = pol_dict['bias'] cls_init.x_idx = pol_dict['x_idx'] return cls_init
def reset_state(): # Reset all random seeds, as well as TensorFlow default graph random.seed(0) np.random.seed(0) import tensorflow as tf from tensorflow.python.framework import ops tf.set_random_seed(0) ops.reset_default_graph()
def __setstate__(self, state): from tensorflow.python.framework import ops ops.reset_default_graph() # we need to destroy the default graph before re_init or checkpoint won't restore. self.__init__(state['hyperparams'], state['dO'], state['dU']) self.policy.scale = state['scale'] self.policy.bias = state['bias'] self.tf_iter = state['tf_iter'] saver = tf.train.Saver() check_file = self.checkpoint_file saver.restore(self.sess, check_file)
def test_copy_assert(self): ops.reset_default_graph() a = constant_op.constant(1) b = constant_op.constant(1) eq = math_ops.equal(a, b) assert_op = control_flow_ops.Assert(eq, [a, b]) with ops.control_dependencies([assert_op]): _ = math_ops.add(a, b) sgv = ge.make_view([assert_op, eq.op, a.op, b.op]) copier = ge.Transformer() _, info = copier(sgv, sgv.graph, "", "") new_assert_op = info.transformed(assert_op) self.assertIsNotNone(new_assert_op)
def test_graph_replace(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace(c, {a: a_new}) with session.Session() as sess: sess.run(variables.global_variables_initializer()) c_val, c_new_val = sess.run([c, c_new]) self.assertNear(c_val, 2.001, ERROR_TOLERANCE) self.assertNear(c_new_val, 3.001, ERROR_TOLERANCE)
def test_graph_replace_dict(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace({"c": c}, {a: a_new}) self.assertTrue(isinstance(c_new, dict)) with session.Session() as sess: sess.run(variables.global_variables_initializer()) c_val, c_new_val = sess.run([c, c_new]) self.assertTrue(isinstance(c_new_val, dict)) self.assertNear(c_val, 2.001, ERROR_TOLERANCE) self.assertNear(c_new_val["c"], 3.001, ERROR_TOLERANCE)
def test_graph_replace_ordered_dict(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") c_new = ge.graph_replace(collections.OrderedDict({"c": c}), {a: a_new}) self.assertTrue(isinstance(c_new, collections.OrderedDict))
def test_graph_replace_named_tuple(self): ops.reset_default_graph() a = constant_op.constant(1.0, name="a") b = variables.Variable(1.0, name="b") eps = constant_op.constant(0.001, name="eps") c = array_ops.identity(a + b + eps, name="c") a_new = constant_op.constant(2.0, name="a_new") one_tensor = collections.namedtuple("OneTensor", ["t"]) c_new = ge.graph_replace(one_tensor(c), {a: a_new}) self.assertTrue(isinstance(c_new, one_tensor))
def testOutputSizeRandomSizesAndStridesValidPadding(self): np.random.seed(0) max_image_size = 10 for _ in range(10): num_filters = 1 input_size = [ 1, np.random.randint(1, max_image_size), np.random.randint(1, max_image_size), 1 ] filter_size = [ np.random.randint(1, input_size[1] + 1), np.random.randint(1, input_size[2] + 1) ] stride = [np.random.randint(1, 3), np.random.randint(1, 3)] ops.reset_default_graph() graph = ops.Graph() with graph.as_default(): images = random_ops.random_uniform(input_size, seed=1) transpose = layers_lib.conv2d_transpose( images, num_filters, filter_size, stride=stride, padding='VALID') conv = layers_lib.conv2d( transpose, num_filters, filter_size, stride=stride, padding='VALID') with self.test_session(graph=graph) as sess: sess.run(variables_lib.global_variables_initializer()) self.assertListEqual(list(conv.eval().shape), input_size)
def setUp(self): ops.reset_default_graph()
def setUp(self): np.random.seed(1) ops.reset_default_graph()
def setUp(self): np.random.seed(1) ops.reset_default_graph() self._batch_size = 4 self._num_classes = 3 self._np_predictions = np.matrix(('0.1 0.2 0.7;' '0.6 0.2 0.2;' '0.0 0.9 0.1;' '0.2 0.0 0.8')) self._np_labels = [0, 0, 0, 0]
def close(self): # If training, save the RAM memory to file if self._is_training: self._saver.save(self._session, self._PARAMETERS_FILE_PATH) temp_copy = [] while self._previous_observations: temp_copy.append(self._previous_observations.pop()) while len(temp_copy) > MAX_OBSERVATIONS_IN_FILE: file_copy = [] for _ in range(0, MAX_OBSERVATIONS_IN_FILE): file_copy.append(temp_copy.pop()) np.save('obs_' + str(self._number_files) + '.npy', file_copy) self._number_files += 1 del file_copy np.save('obs_' + str(self._number_files) + '.npy', temp_copy) print('\nTotal number of saved file containing transitions:', self._number_files + 1) del temp_copy # Close the session and clear TensorFlow's graphs ops.reset_default_graph() self._session.close() # Plot the graph of the average Implied/Realized reward ratio MA = 50 # moving average parameter if len(self._implied_realized_reward_ratio) > MA: plt.figure() plt.subplot(111) title = plt.title(('History of implied/realized reward ratio'), fontsize="x-large") line = self._implied_realized_reward_ratio.copy() average = [np.mean(line[i:i+MA]) for i in range(len(line)-MA)] dt = [i for i in range(len(line))] plt.plot(dt, line, 'r', label='Individual observations') plt.plot(dt[MA:], average, 'b', label='50-observation moving average') plt.axis([0, len(line), np.min(average)*0.5, np.max(average)*2.]) title.set_y(1.0) plt.legend() plt.show()