如何在张量流字符串张量上执行字符串查找和替换?



我目前正在使用 Tensorflow 数据集 api 对指定路径上的图像执行一些增强。文件名本身包含说明是否扩充文件的信息。所以我要做的是从数据集中读取文件,对于每个文件,在文件名中执行查找,如果我找到特定的子字符串,则设置一个布尔标志并将子字符串替换为"。

我得到的错误是:

属性

错误:"张量"对象没有属性"查找">

我无法使用 dtype 字符串条目对张量执行"查找",因为 find 不是张量的一部分,所以我试图弄清楚如何执行上述操作。我在下面分享了一些代码,我认为这些代码演示了我正在尝试做的事情。 性能很重要,所以如果有人看到我错误地通过数据集 API 执行此操作,我宁愿以正确的方式执行此操作。

def preproc_img(filenames):
def parse_fn(filename):
augment_inst = False
if cfg.SPLIT_INTO_INST:
#*****************************************************
#*** THIS IS WHERE THE LOGIC IS CURRENTLY BREAKING ***
#*****************************************************
if filename.find('_data_augmentation') != -1:
augment_inst = True
filename = filename.replace('_data_augmentation', '')
image_string = tf.read_file(filename)
img = tf.image.decode_image(image_string, channels=3)
return dict(zip([filename], [img]))   
dataset = tf.data.Dataset.from_tensor_slices(filenames)
dataset = dataset.map(parse_fn)
iterator = dataset.make_one_shot_iterator()
return iterator.get_next()

def perform_train():
if __name__ == '__main__':
filenames = helper.get_image_paths()
next_batch = preproc_img(filenames)
with tf.Session() as sess:
with sess .graph.as_default():
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())
dat = sess.run(next_batch)
# I would now go about calling any of my tf op code below

您可以使用tf.regex_replace替换tf.string张量中的文本。

filename = tf.regex_replace(filename, "_data_augmentation", "")

对于 TF 2.0

filename = tf.strings.regex_replace(filename, "_data_augmentation", "")

最新更新