如何在 Tensorflow String Tensor 上执行字符串查找和替换?

How to perform string find and replace on Tensorflow String Tensor?

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

我得到的错误是:

AttributeError: 'Tensor' object has no attribute 'find'

我无法使用 dtype 字符串条目对张量执行 "find" 因为 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", "")