简体   繁体   中英

How to compare two strings in Tensorflow?

Suppose I want to compare to element of a tensor of type string: text

str = tf.constant(['0001', '0013', '0021', '0001'], dtype=tf.string)
str_1 = str[0]
str_2 = str[1]
if str_1==str_2:
    flag=True
else:
    flag=False

You can use tf.math.equal() to compare two string tensor.

code:

tf.enable_eager_execution()

str_var = tf.constant(['0001', '0010', '0020', '0001'], dtype=tf.string)
str_1 = str_var[0]
str_2 = str_var[1]
str_3 = str_var[3]

print(tf.math.equal(str_1, str_2).numpy())
print(tf.math.equal(str_1, str_3).numpy())

output:

False
True

Read more about tf.math.equal() from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM