在我需要知道文件名中的前缀的情况下,示例是从火车时间中提取的。
在dataset生成器中,我有当前文件名'sourceA_stuff.tfrecords'或'sourceB_stuff.tfrecords'等的张量。我希望确定张量sources = ['sourceA', 'sourceB']中的哪个元素与文件名的前缀匹配,并将该元素的索引作为源标签传递。我在没有急切执行的情况下做这个有问题,如果可以避免的话,我真的不想使用急切的执行。下面是最小的例子(见下面的注释):
filename = tf.cast('sourceA_stuff.tfrecords', tf.string)
sources = ['sourceA', 'sourceB']
for i in range(len(sources)):
if sources[i] in filename:
source = tf.cast(i, tf.int32)
breakTypeError:只有在启用急切执行时,张量对象才是可迭代的。要迭代此张量,请使用
tf.map_fn。
问题是,我无法弄清楚如何使用tf.map_fn来模拟带有子字符串匹配的where查询,而且我也找不出一种好的方法来绕过我在没有迭代的情况下所做的工作。
也曾尝试过:
source = [i for i in range(len(sources)) if source[i] in filename]同样的交易。
注意:现在在我的电脑上测试这个有问题。如有必要,将使用补丁进行更新。
发布于 2019-11-23 01:12:18
下列各点应能发挥作用。
import tensorflow as tf
filename = tf.cast('sourceB_stuff.tfrecords', tf.string)
sources = tf.constant(['sourceA.+', 'sourceB.+'])
tf_label = tf.argmax(tf.cast(tf.map_fn(lambda x: tf.strings.regex_full_match(filename, x), sources, dtype=tf.bool), tf.int32))
with tf.Session() as sess:
print(sess.run(tf_label))值得注意的事情:
startswith()类型的字符串操作。因此,我能找到的最接近的是regex_full_match,这意味着您需要有一个正则表达式,该正则表达式与您所比较的完整字符串相匹配。https://stackoverflow.com/questions/59003050
复制相似问题