Python tensorflow.python.framework.ops.reset_default_graph() Examples

The following are 30 code examples of tensorflow.python.framework.ops.reset_default_graph(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tensorflow.python.framework.ops , or try the search function .
Example #1
Source File: inception_v2_test.py    From tf-slim with Apache License 2.0 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 224, 224
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.cached_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v2.inception_v2(inputs, num_classes)
      self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_5c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) 
Example #2
Source File: inception_v1_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 224, 224
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.test_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v1.inception_v1(inputs, num_classes)
      self.assertTrue(logits.op.name.startswith('InceptionV1/Logits'))
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_5c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) 
Example #3
Source File: inception_v3_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 299, 299
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.test_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v3.inception_v3(inputs, num_classes)
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_7c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 8, 2048]) 
Example #4
Source File: inception_v2_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 224, 224
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.test_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v2.inception_v2(inputs, num_classes)
      self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_5c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) 
Example #5
Source File: saved_model_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testClearDevices(self):
    export_dir = os.path.join(test.get_temp_dir(), "test_clear_devices")
    builder = saved_model_builder.SavedModelBuilder(export_dir)

    # Specify a device and save a variable.
    ops.reset_default_graph()
    with session.Session(
        target="",
        config=config_pb2.ConfigProto(device_count={"CPU": 2})) as sess:
      with sess.graph.device("/cpu:0"):
        self._init_and_validate_variable(sess, "v", 42)
        builder.add_meta_graph_and_variables(
            sess, [tag_constants.TRAINING], clear_devices=True)

    # Save the SavedModel to disk.
    builder.save()

    # Restore the graph with a single predefined tag whose variables were saved
    # without any device information.
    with self.test_session(graph=ops.Graph()) as sess:
      loader.load(sess, [tag_constants.TRAINING], export_dir)
      self.assertEqual(
          42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval()) 
Example #6
Source File: inception_v1_test.py    From tf-slim with Apache License 2.0 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 224, 224
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.cached_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v1.inception_v1(inputs, num_classes)
      self.assertTrue(logits.op.name.startswith('InceptionV1/Logits'))
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_5c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) 
Example #7
Source File: saved_model_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testClearDevices(self):
    export_dir = os.path.join(test.get_temp_dir(), "test_clear_devices")
    builder = saved_model_builder.SavedModelBuilder(export_dir)

    # Specify a device and save a variable.
    ops.reset_default_graph()
    with session.Session(
        target="",
        config=config_pb2.ConfigProto(device_count={"CPU": 2})) as sess:
      with sess.graph.device("/cpu:0"):
        self._init_and_validate_variable(sess, "v", 42)
        builder.add_meta_graph_and_variables(
            sess, [tag_constants.TRAINING], clear_devices=True)

    # Save the SavedModel to disk.
    builder.save()

    # Restore the graph with a single predefined tag whose variables were saved
    # without any device information.
    with self.test_session(graph=ops.Graph()) as sess:
      loader.load(sess, [tag_constants.TRAINING], export_dir)
      self.assertEqual(
          42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval()) 
Example #8
Source File: inception_v2_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 224, 224
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.test_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v2.inception_v2(inputs, num_classes)
      self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_5c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) 
Example #9
Source File: inception_v3_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 299, 299
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.test_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v3.inception_v3(inputs, num_classes)
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_7c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 8, 2048]) 
Example #10
Source File: inception_v1_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 224, 224
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.test_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v1.inception_v1(inputs, num_classes)
      self.assertTrue(logits.op.name.startswith('InceptionV1/Logits'))
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_5c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) 
Example #11
Source File: layers_test.py    From tf-slim with Apache License 2.0 6 votes vote down vote up
def testCreateDropoutWithPlaceholder(self):
    height, width = 3, 3
    tf.reset_default_graph()
    with self.cached_session():
      is_training = array_ops.placeholder(dtype=dtypes.bool, shape=[])
      images = random_ops.random_uniform((5, height, width, 3), seed=1)
      # this verifies that that we've inserted cond properly.
      output = _layers.dropout(images, is_training=is_training)
      # In control_flow_v2 the op is called "If" and it is behind
      # identity op. In legacy mode cond we just go by name.
      # Might need to do something more robust here eventually.
      is_cond_op = (output.op.inputs[0].op.type == 'If' or
                    output.op.name == 'Dropout/cond/Merge')
      self.assertTrue(is_cond_op,
                      'Expected cond_op got ' + repr(output))
      output.get_shape().assert_is_compatible_with(images.get_shape()) 
Example #12
Source File: bundle_shim_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testLegacyBasic(self):
    base_path = test.test_src_dir_path(SESSION_BUNDLE_PATH)
    ops.reset_default_graph()
    sess, meta_graph_def = (
        bundle_shim.load_session_bundle_or_saved_model_bundle_from_path(
            base_path,
            tags=[""],
            target="",
            config=config_pb2.ConfigProto(device_count={"CPU": 2})))

    self.assertTrue(sess)
    asset_path = os.path.join(base_path, constants.ASSETS_DIRECTORY)
    with sess.as_default():
      path1, path2 = sess.run(["filename1:0", "filename2:0"])
      self.assertEqual(
          compat.as_bytes(os.path.join(asset_path, "hello1.txt")), path1)
      self.assertEqual(
          compat.as_bytes(os.path.join(asset_path, "hello2.txt")), path2)

      collection_def = meta_graph_def.collection_def

      signatures_any = collection_def[constants.SIGNATURES_KEY].any_list.value
      self.assertEqual(len(signatures_any), 1) 
Example #13
Source File: bundle_shim_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testSavedModelBasic(self):
    base_path = test.test_src_dir_path(SAVED_MODEL_PATH)
    ops.reset_default_graph()
    sess, meta_graph_def = (
        bundle_shim.load_session_bundle_or_saved_model_bundle_from_path(
            base_path,
            tags=[tag_constants.SERVING],
            target="",
            config=config_pb2.ConfigProto(device_count={"CPU": 2})))

    self.assertTrue(sess)

    # Check basic signature def property.
    signature_def = meta_graph_def.signature_def
    self.assertEqual(len(signature_def), 2)
    self.assertEqual(
        signature_def[signature_constants.REGRESS_METHOD_NAME].method_name,
        signature_constants.REGRESS_METHOD_NAME)
    signature = signature_def["tensorflow/serving/regress"]
    asset_path = os.path.join(base_path, saved_model_constants.ASSETS_DIRECTORY)
    with sess.as_default():
      output1 = sess.run(["filename_tensor:0"])
      self.assertEqual(["foo.txt"], output1) 
Example #14
Source File: bundle_shim_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testLegacyBasic(self):
    base_path = test.test_src_dir_path(SESSION_BUNDLE_PATH)
    ops.reset_default_graph()
    sess, meta_graph_def = (
        bundle_shim.load_session_bundle_or_saved_model_bundle_from_path(
            base_path,
            tags=[""],
            target="",
            config=config_pb2.ConfigProto(device_count={"CPU": 2})))

    self.assertTrue(sess)
    asset_path = os.path.join(base_path, constants.ASSETS_DIRECTORY)
    with sess.as_default():
      path1, path2 = sess.run(["filename1:0", "filename2:0"])
      self.assertEqual(
          compat.as_bytes(os.path.join(asset_path, "hello1.txt")), path1)
      self.assertEqual(
          compat.as_bytes(os.path.join(asset_path, "hello2.txt")), path2)

      collection_def = meta_graph_def.collection_def

      signatures_any = collection_def[constants.SIGNATURES_KEY].any_list.value
      self.assertEqual(len(signatures_any), 1) 
Example #15
Source File: bundle_shim_test.py    From keras-lambda with MIT License 6 votes vote down vote up
def testSavedModelBasic(self):
    base_path = test.test_src_dir_path(SAVED_MODEL_PATH)
    ops.reset_default_graph()
    sess, meta_graph_def = (
        bundle_shim.load_session_bundle_or_saved_model_bundle_from_path(
            base_path,
            tags=[tag_constants.SERVING],
            target="",
            config=config_pb2.ConfigProto(device_count={"CPU": 2})))

    self.assertTrue(sess)

    # Check basic signature def property.
    signature_def = meta_graph_def.signature_def
    self.assertEqual(len(signature_def), 2)
    self.assertEqual(
        signature_def[signature_constants.REGRESS_METHOD_NAME].method_name,
        signature_constants.REGRESS_METHOD_NAME)
    signature = signature_def["tensorflow/serving/regress"]
    asset_path = os.path.join(base_path, saved_model_constants.ASSETS_DIRECTORY)
    with sess.as_default():
      output1 = sess.run(["filename_tensor:0"])
      self.assertEqual(["foo.txt"], output1) 
Example #16
Source File: inception_v3_test.py    From tf-slim with Apache License 2.0 6 votes vote down vote up
def testUnknownImageShape(self):
    ops.reset_default_graph()
    batch_size = 2
    height, width = 299, 299
    num_classes = 1000
    input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
    with self.cached_session() as sess:
      inputs = array_ops.placeholder(
          dtypes.float32, shape=(batch_size, None, None, 3))
      logits, end_points = inception_v3.inception_v3(inputs, num_classes)
      self.assertListEqual(logits.get_shape().as_list(),
                           [batch_size, num_classes])
      pre_pool = end_points['Mixed_7c']
      feed_dict = {inputs: input_np}
      variables.global_variables_initializer().run()
      pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
      self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 8, 2048]) 
Example #17
Source File: test_util.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def setUp(self):
    self._ClearCachedSession()
    random.seed(random_seed.DEFAULT_GRAPH_SEED)
    np.random.seed(random_seed.DEFAULT_GRAPH_SEED)
    # Note: The following line is necessary because some test methods may error
    # out from within nested graph contexts (e.g., via assertRaises and
    # assertRaisesRegexp), which may leave ops._default_graph_stack non-empty
    # under certain versions of Python. That would cause
    # ops.reset_default_graph() to throw an exception if the stack were not
    # cleared first.
    ops._default_graph_stack.reset()  # pylint: disable=protected-access
    ops.reset_default_graph()
    ops.get_default_graph().seed = random_seed.DEFAULT_GRAPH_SEED 
Example #18
Source File: framework_test.py    From keras-lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    # Tear down temporary dump directory.
    shutil.rmtree(self._dump_root)

    ops.reset_default_graph() 
Example #19
Source File: session_debug_testlib.py    From keras-lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    ops.reset_default_graph()

    # Tear down temporary dump directory.
    if os.path.isdir(self._dump_root):
      shutil.rmtree(self._dump_root) 
Example #20
Source File: stepper_test.py    From keras-lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    ops.reset_default_graph() 
Example #21
Source File: backend.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
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 
Example #22
Source File: session_debug_testlib.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    ops.reset_default_graph()

    # Tear down temporary dump directory.
    if os.path.isdir(self._dump_root):
      shutil.rmtree(self._dump_root) 
Example #23
Source File: io.py    From lang2program with Apache License 2.0 5 votes vote down vote up
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() 
Example #24
Source File: io.py    From lang2program with Apache License 2.0 5 votes vote down vote up
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() 
Example #25
Source File: dumping_wrapper_test.py    From keras-lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    ops.reset_default_graph()
    if os.path.isdir(self.session_root):
      shutil.rmtree(self.session_root) 
Example #26
Source File: local_cli_wrapper_test.py    From keras-lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    ops.reset_default_graph()
    if os.path.isdir(self._tmp_dir):
      shutil.rmtree(self._tmp_dir) 
Example #27
Source File: stepper_cli_test.py    From keras-lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    ops.reset_default_graph() 
Example #28
Source File: cli_shared_test.py    From keras-lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    ops.reset_default_graph() 
Example #29
Source File: layers_test.py    From tf-slim with Apache License 2.0 5 votes vote down vote up
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.session(graph=graph) as sess:
          sess.run(variables_lib.global_variables_initializer())
          self.assertListEqual(list(conv.eval().shape), input_size) 
Example #30
Source File: stepper_test.py    From keras-lambda with MIT License 5 votes vote down vote up
def tearDown(self):
    ops.reset_default_graph()