how can i convert bytes to string in tensorflow

  • Last Update :
  • Techknowledgy :

You can use tf.compat.as_str_any().

for i in x:
   print(tf.compat.as_str_any(i))

Suggestion : 2

Last updated 2022-06-28 UTC.

Convert raw bytes from input tensor into numeric tensors.

tf.io.decode_raw(
   input_bytes, out_type, little_endian = True, fixed_length = None, name = None
)

Every component of the input tensor is interpreted as a sequence of bytes. These bytes are then decoded as numbers in the format specified by out_type.

tf.io.decode_raw(tf.constant("1"), tf.uint8)
<tf.Tensor: shape=(1,), dtype=uint8, numpy=array([49], dtype=uint8)>
   tf.io.decode_raw(tf.constant("1,2"), tf.uint8)
   <tf.Tensor: shape=(3,), dtype=uint8, numpy=array([49, 44, 50], dtype=uint8)>

Note that the rank of the output tensor is always one more than the input one:

tf.io.decode_raw(tf.constant(["1", "2"]), tf.uint8).shape
TensorShape([2, 1])
tf.io.decode_raw(tf.constant([
   ["1"],
   ["2"]
]), tf.uint8).shape
TensorShape([2, 1, 1])

The operation allows specifying endianness via the little_endian parameter.

tf.io.decode_raw(tf.constant("\x0a\x0b"), tf.int16)
<tf.Tensor: shape=(1,), dtype=int16, numpy=array([2826], dtype=int16)>
   hex(2826)
   '0xb0a'
   tf.io.decode_raw(tf.constant("\x0a\x0b"), tf.int16, little_endian=False)
   <tf.Tensor: shape=(1,), dtype=int16, numpy=array([2571], dtype=int16)>
      hex(2571)
      '0xa0b'

If the elements of input_bytes are of different length, you must specify fixed_length:

tf.io.decode_raw(tf.constant([["1"],["23"]]), tf.uint8, fixed_length=4)
<tf.Tensor: shape=(2, 1, 4), dtype=uint8, numpy=array([[[49, 0, 0, 0]], [[50, 51, 0, 0]]], dtype=uint8)>

Suggestion : 3

will print list items as python strings. anycodings_tensorflow-datasets No need to use session. ,I have a list of bytes and I want to convert anycodings_tensorflow it to a list of strings, in python I use anycodings_tensorflow this decode function:,You can use tf.compat.as_str_any(). ,How to get soft delete enabled/disabled status for all keyvault present in one resouce using powershell script

I have a list of bytes and I want to convert anycodings_tensorflow it to a list of strings, in python I use anycodings_tensorflow this decode function:

x = [b '\xd8\xa8\xd9\x85\xd8\xb3\xd8\xa3\xd9\x84\xd8\xa9',
   b '\xd8\xa5\xd9\x86\xd8\xb4\xd8\xa7\xd8\xa1',
   b '\xd9\x82\xd8\xb6\xd8\xa7\xd8\xa1',
   b '\xd8\xac\xd9\x86\xd8\xa7\xd8\xa6\xd9\x8a',
   b '\xd8\xaf\xd9\x88\xd9\x84\xd9\x8a'
]
y = [a.decode("utf-8") for a in x]

You can use tf.compat.as_str_any().

for i in x:
   print(tf.compat.as_str_any(i))

Suggestion : 4

Last Updated : 23 Jun, 2022,GATE Live Course 2023

Output:

Input:
b'GeeksForGeeks'
<class 'bytes'>

   Output:
   GeeksForGeeks
   <class 'str'>