Python tensorflow.as_string() Examples

The following are 30 code examples of tensorflow.as_string(). 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 , or try the search function .
Example #1
Source File: mappers_test.py    From transform with Apache License 2.0 6 votes vote down vote up
def testEstimatedProbabilityDensityMissingKey(self):
    input_size = 5

    with tf.compat.v1.Graph().as_default():
      input_data = tf.constant([[str(x + 1)] for x in range(input_size)])

      count = tf.constant([3] * input_size, tf.int64)
      boundaries = tf.as_string(tf.range(input_size))
      with mock.patch.object(
          mappers.analyzers, 'histogram', side_effect=[(count, boundaries)]):

        result = mappers.estimated_probability_density(
            input_data, categorical=True)

      expected = np.array([[0.2], [0.2], [0.2], [0.2], [0.]], np.float32)
      with tf.compat.v1.Session() as sess:
        sess.run(tf.compat.v1.tables_initializer())
        self.assertAllEqual(expected, sess.run(result)) 
Example #2
Source File: graph_tools_test.py    From transform with Apache License 2.0 6 votes vote down vote up
def _create_graph_with_table_initialized_by_table_output():
  filename = tf.compat.v1.placeholder(tf.string, ())
  table1 = _create_lookup_table_from_file(filename)

  # Use output from the first table to initialize the second table.
  keys = ['a', 'b', 'c']
  tensor_keys = tf.as_string(
      table1.lookup(tf.constant(keys, tf.string)))
  initializer2 = tf.lookup.KeyValueTensorInitializer(
      keys=tensor_keys,
      values=tf.range(len(keys), dtype=tf.int64),
      key_dtype=tf.string,
      value_dtype=tf.int64)
  table2 = tf.lookup.StaticHashTable(initializer2, default_value=-1)
  x = tf.compat.v1.placeholder(tf.string, (None,))
  y = table2.lookup(x)
  return {'filename': filename, 'x': x, 'y': y} 
Example #3
Source File: text_demo.py    From tensorboard with Apache License 2.0 6 votes vote down vote up
def markdown_table(step):
    # The text summary can also contain Markdown, including Markdown
    # tables. Markdown tables look like this:
    #
    #     | hello | there |
    #     |-------|-------|
    #     | this  | is    |
    #     | a     | table |
    #
    # The leading and trailing pipes in each row are optional, and the text
    # doesn't actually have to be neatly aligned, so we can create these
    # pretty easily. Let's do so.
    header_row = "Pounds of chocolate | Happiness"
    chocolate = tf.range(step)
    happiness = tf.square(chocolate + 1)
    chocolate_column = tf.as_string(chocolate)
    happiness_column = tf.as_string(happiness)
    table_rows = tf.strings.join([chocolate_column, " | ", happiness_column])
    table_body = tf.strings.reduce_join(inputs=table_rows, separator="\n")
    table = tf.strings.join([header_row, "---|---", table_body], separator="\n")
    preamble = "We conducted an experiment and found the following data:\n\n"
    result = tf.strings.join([preamble, table])
    tf.compat.v1.summary.text("chocolate_study", result) 
Example #4
Source File: fake_multi_examples_per_input_estimator.py    From model-analysis with Apache License 2.0 6 votes vote down vote up
def _parse_csv(rows_string_tensor):
  """Takes the string input tensor and returns a dict of rank-2 tensors."""
  example_count = tf.io.decode_csv(
      records=rows_string_tensor,
      record_defaults=[tf.constant([0], dtype=tf.int32, shape=None)])[0]

  input_index, intra_input_index = _indices_from_example_count(example_count)
  annotation = tf.strings.join([
      'raw_input: ',
      tf.gather(rows_string_tensor, input_index), '; index: ',
      tf.as_string(intra_input_index)
  ])

  return {
      'example_count': tf.gather(example_count, input_index),
      'input_index': input_index,
      'intra_input_index': intra_input_index,
      'annotation': annotation,
  } 
Example #5
Source File: as_string_op_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testLargeInt(self):
    # Cannot use values outside -128..127 for test, because we're also
    # testing int8
    s = lambda strs: [x.decode("ascii") for x in strs]

    with self.test_session():
      input_ = tf.placeholder(tf.int32)
      int_inputs_ = [np.iinfo(np.int32).min, np.iinfo(np.int32).max]
      output = tf.as_string(input_)
      result = output.eval(feed_dict={input_: int_inputs_})
      self.assertAllEqual(s(result), ["%d" % x for x in int_inputs_])

      input_ = tf.placeholder(tf.int64)
      int_inputs_ = [np.iinfo(np.int64).min, np.iinfo(np.int64).max]
      output = tf.as_string(input_)
      result = output.eval(feed_dict={input_: int_inputs_})
      self.assertAllEqual(s(result), ["%d" % x for x in int_inputs_]) 
Example #6
Source File: post_export_metrics.py    From model-analysis with Apache License 2.0 5 votes vote down vote up
def _cast_or_convert(original: tf.Tensor, target_type: tf.DType) -> tf.Tensor:
  if target_type == tf.string and original.dtype != tf.string:
    return tf.as_string(original)
  else:
    return tf.cast(original, target_type) 
Example #7
Source File: text_demo.py    From tensorboard with Apache License 2.0 5 votes vote down vote up
def higher_order_tensors(step):
    # We're not limited to passing scalar tensors to the summary
    # operation. If we pass a rank-1 or rank-2 tensor, it'll be visualized
    # as a table in TensorBoard. (For higher-ranked tensors, you'll see
    # just a 2D slice of the data.)
    #
    # To demonstrate this, let's create a multiplication table.

    # First, we'll create the table body, a `step`-by-`step` array of
    # strings.
    numbers = tf.range(step)
    numbers_row = tf.expand_dims(numbers, 0)  # shape: [1, step]
    numbers_column = tf.expand_dims(numbers, 1)  # shape: [step, 1]
    products = tf.matmul(numbers_column, numbers_row)  # shape: [step, step]
    table_body = tf.as_string(products)

    # Next, we'll create a header row and column, and a little
    # multiplication sign to put in the corner.
    bold_numbers = tf.strings.join(["**", tf.as_string(numbers), "**"])
    bold_row = tf.expand_dims(bold_numbers, 0)
    bold_column = tf.expand_dims(bold_numbers, 1)
    corner_cell = tf.constant(u"\u00d7".encode("utf-8"))  # MULTIPLICATION SIGN

    # Now, we have to put the pieces together. Using `axis=0` stacks
    # vertically; using `axis=1` juxtaposes horizontally.
    table_body_and_top_row = tf.concat([bold_row, table_body], axis=0)
    table_left_column = tf.concat([[[corner_cell]], bold_column], axis=0)
    table_full = tf.concat([table_left_column, table_body_and_top_row], axis=1)

    # The result, `table_full`, is a rank-2 string tensor of shape
    # `[step + 1, step + 1]`. We can pass it directly to the summary, and
    # we'll get a nicely formatted table in TensorBoard.
    tf.compat.v1.summary.text("multiplication_table", table_full) 
Example #8
Source File: Reader.py    From PReMVOS with MIT License 5 votes vote down vote up
def add_distance_transform(tensors, labels, distance_transform_fn):
  args_list = [tensors["unnormalized_img"], tensors["label"],
               tensors["raw_label"], labels[Constants.STRATEGY], labels[Constants.IGNORE_CLASSES]]

  if "old_label" in tensors:
    args_list.append(tensors["old_label"])

  u0, u1, num_clicks = tf.py_func(distance_transform_fn,
                                  args_list,
                                  [tf.float32, tf.float32, tf.int64],
                                  name="create_distance_transform")

  u0 = tf.expand_dims(u0, axis=2)
  u0.set_shape(tensors["unnormalized_img"].get_shape().as_list()[:-1] + [1])

  u1 = tf.expand_dims(u1, axis=2)
  u1.set_shape(tensors["unnormalized_img"].get_shape().as_list()[:-1] + [1])

  shape = tensors["tag"].get_shape()
  im_path = tf.string_join([tensors["tag"], tf.as_string(num_clicks)], separator=":", name="JoinPath")
  im_path.set_shape(shape)

  tensors[Constants.DT_NEG] = u0
  tensors[Constants.DT_POS] = u1
  tensors["tag"] = im_path

  return tensors 
Example #9
Source File: utils.py    From DeepCTR with Apache License 2.0 5 votes vote down vote up
def call(self, x, mask=None, **kwargs):
        if x.dtype != tf.string:
            x = tf.as_string(x, )
        try:
            hash_x = tf.string_to_hash_bucket_fast(x, self.num_buckets if not self.mask_zero else self.num_buckets - 1,
                                                    name=None)  # weak hash
        except:
            hash_x = tf.strings.to_hash_bucket_fast(x, self.num_buckets if not self.mask_zero else self.num_buckets - 1,
                                               name=None)  # weak hash
        if self.mask_zero:
            mask_1 = tf.cast(tf.not_equal(x, "0"), 'int64')
            mask_2 = tf.cast(tf.not_equal(x, "0.0"), 'int64')
            mask = mask_1 * mask_2
            hash_x = (hash_x + 1) * mask
        return hash_x 
Example #10
Source File: winequality.py    From tf-yarn with Apache License 2.0 5 votes vote down vote up
def get_dataset(
    path: str,
    train_fraction: float = 0.7,
    split: str = "train"
) -> tf.data.Dataset:
    def split_label(*row):
        return dict(zip(FEATURES, row)), row[-1]

    def in_training_set(*row):
        num_buckets = 1000
        key = tf.strings.join(list(map(tf.as_string, row)))
        bucket_id = tf.strings.to_hash_bucket_fast(key, num_buckets)
        return bucket_id < int(train_fraction * num_buckets)

    def in_test_set(*row):
        return ~in_training_set(*row)

    data = tf.data.experimental.CsvDataset(
        path,
        [tf.float32] * len(FEATURES) + [tf.int32],
        header=True,
        field_delim=";")

    if split == "train":
        return data.filter(in_training_set).map(split_label)
    elif split == "test":
        return data.filter(in_test_set).map(split_label)
    else:
        raise ValueError("Unknown option split, must be 'train' or 'test'") 
Example #11
Source File: inputs.py    From MAX-Object-Detector with Apache License 2.0 5 votes vote down vote up
def _replace_empty_string_with_random_number(string_tensor):
  """Returns string unchanged if non-empty, and random string tensor otherwise.

  The random string is an integer 0 and 2**63 - 1, casted as string.


  Args:
    string_tensor: A tf.tensor of dtype string.

  Returns:
    out_string: A tf.tensor of dtype string. If string_tensor contains the empty
      string, out_string will contain a random integer casted to a string.
      Otherwise string_tensor is returned unchanged.

  """

  empty_string = tf.constant('', dtype=tf.string, name='EmptyString')

  random_source_id = tf.as_string(
      tf.random_uniform(shape=[], maxval=2**63 - 1, dtype=tf.int64))

  out_string = tf.cond(
      tf.equal(string_tensor, empty_string),
      true_fn=lambda: random_source_id,
      false_fn=lambda: string_tensor)

  return out_string 
Example #12
Source File: inputs.py    From g-tensorflow-models with Apache License 2.0 5 votes vote down vote up
def _replace_empty_string_with_random_number(string_tensor):
  """Returns string unchanged if non-empty, and random string tensor otherwise.

  The random string is an integer 0 and 2**63 - 1, casted as string.


  Args:
    string_tensor: A tf.tensor of dtype string.

  Returns:
    out_string: A tf.tensor of dtype string. If string_tensor contains the empty
      string, out_string will contain a random integer casted to a string.
      Otherwise string_tensor is returned unchanged.

  """

  empty_string = tf.constant('', dtype=tf.string, name='EmptyString')

  random_source_id = tf.as_string(
      tf.random_uniform(shape=[], maxval=2**63 - 1, dtype=tf.int64))

  out_string = tf.cond(
      tf.equal(string_tensor, empty_string),
      true_fn=lambda: random_source_id,
      false_fn=lambda: string_tensor)

  return out_string 
Example #13
Source File: train.py    From g-tensorflow-models with Apache License 2.0 5 votes vote down vote up
def make_status_message(model):
  """Makes a string `Tensor` of training status."""
  return tf.string_join(
      [
          'Starting train step: current_image_id: ',
          tf.as_string(model.current_image_id), ', progress: ',
          tf.as_string(model.progress), ', num_blocks: {}'.format(
              model.num_blocks), ', batch_size: {}'.format(model.batch_size)
      ],
      name='status_message') 
Example #14
Source File: bottles_of_bear.py    From EsotericTensorFlow with MIT License 5 votes vote down vote up
def body(self, i, text):
        before, after, before_uppercase = tf.cond(tf.equal(i, 0),
                lambda: ('no more bottles', '99 bottles', 'No more bottles'),
                lambda: tf.cond(tf.equal(i, 1),
                            lambda: ('1 bottle', 'no more bottles', '1 bottle'),
                            lambda: tf.cond(tf.equal(i, 2),
                                        lambda: ('2 bottles', '1 bottle', '2 bottles'),
                                        lambda: (tf.string_join([tf.as_string(i), ' bottles'], ''),
                                                 tf.string_join([tf.as_string(tf.subtract(i, 1)), ' bottles']),
                                                 tf.string_join([tf.as_string(i), ' bottles'], '')))))
        action = tf.cond(tf.equal(i, 0),
                        lambda: tf.constant('Go to the store and buy some more'),
                        lambda: tf.constant('Take one down and pass it around'))
        return tf.subtract(i, 1), tf.string_join([text, tf.string_join([before_uppercase, ' of beer on the wall, ', before, ' of beer.\n', action, ', ', after, ' of beer on the wall.\n'])]) 
Example #15
Source File: tfrecords_to_bigtable.py    From class-balanced-loss with MIT License 5 votes vote down vote up
def build_row_key_dataset(num_records, row_prefix):
  if num_records is not None:
    ds = tf.data.Dataset.range(num_records)
  else:
    ds = tf.contrib.data.Counter()
  if num_records is None:
    width = 10
  else:
    width = pad_width(num_records)
  ds = ds.map(lambda idx: tf.as_string(idx, width=width, fill='0'))
  if row_prefix is not None:
    ds = ds.map(lambda idx: tf.string_join([row_prefix, idx]))
  return ds 
Example #16
Source File: inputs.py    From multilabel-image-classification-tensorflow with MIT License 5 votes vote down vote up
def _replace_empty_string_with_random_number(string_tensor):
  """Returns string unchanged if non-empty, and random string tensor otherwise.

  The random string is an integer 0 and 2**63 - 1, casted as string.


  Args:
    string_tensor: A tf.tensor of dtype string.

  Returns:
    out_string: A tf.tensor of dtype string. If string_tensor contains the empty
      string, out_string will contain a random integer casted to a string.
      Otherwise string_tensor is returned unchanged.

  """

  empty_string = tf.constant('', dtype=tf.string, name='EmptyString')

  random_source_id = tf.as_string(
      tf.random_uniform(shape=[], maxval=2**63 - 1, dtype=tf.int64))

  out_string = tf.cond(
      tf.equal(string_tensor, empty_string),
      true_fn=lambda: random_source_id,
      false_fn=lambda: string_tensor)

  return out_string 
Example #17
Source File: train.py    From multilabel-image-classification-tensorflow with MIT License 5 votes vote down vote up
def make_status_message(model):
  """Makes a string `Tensor` of training status."""
  return tf.string_join(
      [
          'Starting train step: current_image_id: ',
          tf.as_string(model.current_image_id), ', progress: ',
          tf.as_string(model.progress), ', num_blocks: {}'.format(
              model.num_blocks), ', batch_size: {}'.format(model.batch_size)
      ],
      name='status_message') 
Example #18
Source File: preprocessing.py    From kale with Apache License 2.0 5 votes vote down vote up
def preprocess(inputs):
    """tf.transform's callback function for preprocessing inputs.
    Args:
      inputs: map from feature keys to raw not-yet-transformed features.
    Returns:
      Map from string feature key to transformed feature operations.
    """
    outputs = {}
    for key in DENSE_FLOAT_FEATURE_KEYS:
        # Preserve this feature as a dense float, setting nan's to the mean.
        outputs[key] = transform.scale_to_z_score(inputs[key])

    for key in VOCAB_FEATURE_KEYS:
        # Build a vocabulary for this feature.
        if inputs[key].dtype == tf.string:
            vocab_tensor = inputs[key]
        else:
            vocab_tensor = tf.as_string(inputs[key])
        outputs[key] = transform.string_to_int(
            vocab_tensor, vocab_filename='vocab_' + key,
            top_k=VOCAB_SIZE, num_oov_buckets=OOV_SIZE)

    for key in BUCKET_FEATURE_KEYS:
        outputs[key] = transform.bucketize(inputs[key], FEATURE_BUCKET_COUNT)

    for key in CATEGORICAL_FEATURE_KEYS:
        outputs[key] = tf.to_int64(inputs[key])

    taxi_fare = inputs[FARE_KEY]
    taxi_tip = inputs[LABEL_KEY]
    # Test if the tip was > 20% of the fare.
    tip_threshold = tf.multiply(taxi_fare, tf.constant(0.2))
    outputs[LABEL_KEY] = tf.logical_and(
        tf.logical_not(tf.is_nan(taxi_fare)),
        tf.greater(taxi_tip, tip_threshold))

    return outputs 
Example #19
Source File: inputs.py    From vehicle_counting_tensorflow with MIT License 5 votes vote down vote up
def _replace_empty_string_with_random_number(string_tensor):
  """Returns string unchanged if non-empty, and random string tensor otherwise.

  The random string is an integer 0 and 2**63 - 1, casted as string.


  Args:
    string_tensor: A tf.tensor of dtype string.

  Returns:
    out_string: A tf.tensor of dtype string. If string_tensor contains the empty
      string, out_string will contain a random integer casted to a string.
      Otherwise string_tensor is returned unchanged.

  """

  empty_string = tf.constant('', dtype=tf.string, name='EmptyString')

  random_source_id = tf.as_string(
      tf.random_uniform(shape=[], maxval=2**63 - 1, dtype=tf.int64))

  out_string = tf.cond(
      tf.equal(string_tensor, empty_string),
      true_fn=lambda: random_source_id,
      false_fn=lambda: string_tensor)

  return out_string 
Example #20
Source File: meta_parameter_recorder.py    From rec-rl with Apache License 2.0 5 votes vote down vote up
def build_metagraph_list(self):
        """
        Convert MetaParams into TF Summary Format and create summary_op

        Args:
            None

        Returns:
            Merged TF Op for TEXT summary elements, should only be executed once to reduce data duplication

        """
        ops = []

        self.ignore_unknown_dtypes = True
        for key in sorted(self.meta_params):
            value = self.convert_data_to_string(self.meta_params[key])

            if len(value) == 0:
                continue
            if isinstance(value,str):
                ops.append(tf.summary.text(key, tf.convert_to_tensor(str(value))))
            else:
                ops.append(tf.summary.text(key, tf.as_string(tf.convert_to_tensor(value))))

        with tf.control_dependencies(tf.tuple(ops)):
            self.summary_merged = tf.summary.merge_all()

        return self.summary_merged 
Example #21
Source File: cast.py    From onnx-tensorflow with Apache License 2.0 5 votes vote down vote up
def version_9(cls, node, **kwargs):
    inp = kwargs["tensor_dict"][node.inputs[0]]
    to_type = node.attrs.get("to")

    if to_type == tf.string:
      return [tf.as_string(inp)]

    if inp.dtype == tf.string:
      if to_type not in [tf.float32, tf.float64, tf.int32, tf.int64]:
        raise RuntimeError(
            "Cast string to type {} is not supported in Tensorflow.".format(
                to_type))
      return [tf.strings.to_number(inp, to_type)]

    return [cls.make_tensor_from_onnx_node(node, **kwargs)] 
Example #22
Source File: tfrecords_to_bigtable.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
def build_row_key_dataset(num_records, row_prefix):
  if num_records is not None:
    ds = tf.data.Dataset.range(num_records)
  else:
    ds = tf.contrib.data.Counter()
  if num_records is None:
    width = 10
  else:
    width = pad_width(num_records)
  ds = ds.map(lambda idx: tf.as_string(idx, width=width, fill='0'))
  if row_prefix is not None:
    ds = ds.map(lambda idx: tf.string_join([row_prefix, idx]))
  return ds 
Example #23
Source File: tfrecords_to_bigtable.py    From tpu_models with Apache License 2.0 5 votes vote down vote up
def build_row_key_dataset(num_records, row_prefix):
  if num_records is not None:
    ds = tf.data.Dataset.range(num_records)
  else:
    ds = tf.contrib.data.Counter()
  if num_records is None:
    width = 10
  else:
    width = pad_width(num_records)
  ds = ds.map(lambda idx: tf.as_string(idx, width=width, fill='0'))
  if row_prefix is not None:
    ds = ds.map(lambda idx: tf.string_join([row_prefix, idx]))
  return ds 
Example #24
Source File: as_string_op_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testInt(self):
    # Cannot use values outside -128..127 for test, because we're also
    # testing int8
    int_inputs_ = [0, -1, 1, -128, 127, -101, 101, -0]
    s = lambda strs: [x.decode("ascii") for x in strs]

    with self.test_session():
      for dtype in (tf.int32, tf.int64, tf.int8):
        input_ = tf.placeholder(dtype)

        output = tf.as_string(input_)
        result = output.eval(feed_dict={input_: int_inputs_})
        self.assertAllEqual(s(result), ["%d" % x for x in int_inputs_])

        output = tf.as_string(input_, width=3)
        result = output.eval(feed_dict={input_: int_inputs_})
        self.assertAllEqual(s(result), ["%3d" % x for x in int_inputs_])

        output = tf.as_string(input_, width=3, fill="0")
        result = output.eval(feed_dict={input_: int_inputs_})
        self.assertAllEqual(s(result), ["%03d" % x for x in int_inputs_])

      with self.assertRaisesOpError("scientific and shortest"):
        output = tf.as_string(input_, scientific=True)
        output.eval(feed_dict={input_: int_inputs_})

      with self.assertRaisesOpError("scientific and shortest"):
        output = tf.as_string(input_, shortest=True)
        output.eval(feed_dict={input_: int_inputs_})

      with self.assertRaisesOpError("precision not supported"):
        output = tf.as_string(input_, precision=0)
        output.eval(feed_dict={input_: int_inputs_}) 
Example #25
Source File: as_string_op_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testBool(self):
    bool_inputs_ = [False, True]
    s = lambda strs: [x.decode("ascii") for x in strs]

    with self.test_session():
      for dtype in (tf.bool,):
        input_ = tf.placeholder(dtype)

        output = tf.as_string(input_)
        result = output.eval(feed_dict={input_: bool_inputs_})
        self.assertAllEqual(s(result), ["false", "true"]) 
Example #26
Source File: batch_sequences_with_states_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(BatchSequencesWithStatesTest, self).setUp()
    self.value_length = 4
    self.batch_size = 2
    self.key = tf.string_join(["key_", tf.as_string(tf.cast(
        10000 * tf.random_uniform(()), tf.int32))])
    self.sequences = {"seq1": np.random.rand(self.value_length, 5),
                      "seq2": np.random.rand(self.value_length, 4, 2)}
    self.context = {"context1": [3, 4]}
    self.initial_states = {"state1": np.random.rand(6, 7),
                           "state2": np.random.rand(8)} 
Example #27
Source File: model.py    From document-ocr with Apache License 2.0 5 votes vote down vote up
def _build_pred(self):
    decoded, log_prob = tf.nn.ctc_greedy_decoder(self.logits, self.sequence_length)
    self.decoded = tf.identity(decoded[0], name='decoded')
    self.log_prob = tf.identity(log_prob, name='log_prob')
    if self.is_training:
      pred_str_labels = tf.as_string(self.decoded.values)
      pred_tensor = tf.SparseTensor(indices=self.decoded.indices, values=pred_str_labels, dense_shape=self.decoded.dense_shape)
      true_str_labels = tf.as_string(self.labels.values)
      true_tensor = tf.SparseTensor(indices=self.labels.indices, values=true_str_labels, dense_shape=self.labels.dense_shape)
      self.edit_distance = tf.reduce_mean(tf.edit_distance(pred_tensor, true_tensor, normalize=True), name='distance') 
Example #28
Source File: text_demo.py    From tensorboard with Apache License 2.0 5 votes vote down vote up
def simple_example(step):
    # Text summaries log arbitrary text. This can be encoded with ASCII or
    # UTF-8. Here's a simple example, wherein we greet the user on each
    # step:
    step_string = tf.as_string(step)
    greeting = tf.strings.join(["Hello from step ", step_string, "!"])
    tf.compat.v1.summary.text("greeting", greeting) 
Example #29
Source File: as_string_op_test.py    From deep_image_model with Apache License 2.0 4 votes vote down vote up
def testComplex(self):
    float_inputs_ = [0, 1, -1, 0.5, 0.25, 0.125, complex("INF"), complex("NAN"),
                     complex("-INF")]
    complex_inputs_ = [(x + (x + 1) * 1j) for x in float_inputs_]

    with self.test_session():
      for dtype in (tf.complex64,):
        input_ = tf.placeholder(dtype)

        def clean_nans(s_l):
          return [s.decode("ascii").replace("-nan", "nan") for s in s_l]

        output = tf.as_string(input_, shortest=True)
        result = output.eval(feed_dict={input_: complex_inputs_})
        self.assertAllEqual(clean_nans(result),
                            ["(%g,%g)" % (x.real, x.imag)
                             for x in complex_inputs_])

        output = tf.as_string(input_, scientific=True)
        result = output.eval(feed_dict={input_: complex_inputs_})
        self.assertAllEqual(clean_nans(result),
                            ["(%e,%e)" % (x.real, x.imag)
                             for x in complex_inputs_])

        output = tf.as_string(input_)
        result = output.eval(feed_dict={input_: complex_inputs_})
        self.assertAllEqual(clean_nans(result),
                            ["(%f,%f)" % (x.real, x.imag)
                             for x in complex_inputs_])

        output = tf.as_string(input_, width=3)
        result = output.eval(feed_dict={input_: complex_inputs_})
        self.assertAllEqual(clean_nans(result),
                            ["(%03f,%03f)" % (x.real, x.imag)
                             for x in complex_inputs_])

        output = tf.as_string(input_, width=3, fill="0", shortest=True)
        result = output.eval(feed_dict={input_: complex_inputs_})
        self.assertAllEqual(clean_nans(result),
                            ["(%03g,%03g)" % (x.real, x.imag)
                             for x in complex_inputs_])

        output = tf.as_string(input_, precision=10, width=3)
        result = output.eval(feed_dict={input_: complex_inputs_})
        self.assertAllEqual(clean_nans(result),
                            ["(%03.10f,%03.10f)" % (x.real, x.imag)
                             for x in complex_inputs_])

        output = tf.as_string(input_,
                              precision=10,
                              width=3,
                              fill="0",
                              shortest=True)
        result = output.eval(feed_dict={input_: complex_inputs_})
        self.assertAllEqual(clean_nans(result),
                            ["(%03.10g,%03.10g)" % (x.real, x.imag)
                             for x in complex_inputs_])

      with self.assertRaisesOpError("Cannot select both"):
        output = tf.as_string(input_, scientific=True, shortest=True)
        output.eval(feed_dict={input_: complex_inputs_}) 
Example #30
Source File: test_load_pairs.py    From PReMVOS with MIT License 4 votes vote down vote up
def main():
  n_pers = 1454

  image_list = np.genfromtxt('/fastwork/luiten/mywork/data/CUHK03/number_of_images.csv', delimiter=',')
  image_list = image_list.astype(np.int32)
  num_images = tf.constant(image_list)

  rand = tf.random_uniform([7], maxval=tf.int32.max, dtype=tf.int32)
  sample_same_person = rand[0] % 2
  pers_id_1 = ((rand[1]-1) % n_pers) + 1
  cam_id_1 = ((rand[2]-1) % 2) + 1
  pers_1_n_imgs = num_images[n_pers * (cam_id_1 - 1) + pers_id_1][2]
  img_id_1 = ((rand[3] - 1) % pers_1_n_imgs) + 1

  def if_same_person():
    pers_id_2 = pers_id_1
    cam_id_2 = cam_id_1
    img_id_2 = ((rand[4] - 1) % (pers_1_n_imgs - 1)) + 1
    img_id_2 = tf.cond(img_id_2 >= img_id_1, lambda: img_id_2 + 1, lambda: img_id_2)
    return pers_id_2, cam_id_2, img_id_2

  def if_not_same_person():
    pers_id_2 = ((rand[4]-1) % (n_pers-1)) + 1
    pers_id_2 = tf.cond(pers_id_2 >= pers_id_1, lambda: pers_id_2 + 1, lambda: pers_id_2)
    cam_id_2 = ((rand[5]-1) % 2) + 1
    pers_2_n_imgs = num_images[n_pers * (cam_id_2 - 1) + pers_id_2][2]
    img_id_2 = ((rand[6] - 1) % (pers_2_n_imgs -1)) + 1
    return pers_id_2, cam_id_2, img_id_2

  pers_id_2, cam_id_2, img_id_2 = tf.cond(tf.cast(sample_same_person,tf.bool),if_same_person,if_not_same_person)

  # pair = tf.stack([sample_same_person, pers_id_1,cam_id_1,img_id_1,pers_id_2,cam_id_2,img_id_2])

  img1 = tf.as_string(pers_id_1) + "_" + tf.as_string(cam_id_1) + "_" + tf.as_string(img_id_1) + ".png"
  img2 = tf.as_string(pers_id_2) + "_" + tf.as_string(cam_id_2) + "_" + tf.as_string(img_id_2) + ".png"

  pair = tf.stack([img1, img2, tf.as_string(sample_same_person)])


  # image_reader = tf.WholeFileReader()
  # _, image_file1 = image_reader.read(img1)
  # _, image_file2 = image_reader.read(img2)

  print(image_list.shape)
  batch = tf.train.batch([pair], batch_size=3)
  sess = tf.Session()
  sess.run(tf.global_variables_initializer())
  tf.train.start_queue_runners(sess)
  for i in range(1):
    x = sess.run([batch])
    print(x)