regex - 使用正则表达式从 Tensorflow 2 中的 tf.Tensor 中提取字符串?

标签 regex tensorflow tensorflow-serving

我正在用 TF2 中的签名保存我的 tf.keras 模型,以便通过 TFServing 为其提供服务。在签名函数中,我想使用正则表达式提取一些实体。

我的输入是数据类型为 tf.string 的张量。我无法在其中使用 numpy(),导致“张量对象没有属性 numpy”。 tf.py_function() 在 TFServing 中也不可用。

所以我只剩下 tensorflow 运算了。如何提取带有模式的子字符串?

@tf.function
def serve_fn(input):
    # Returns Today's date is  . Tomorrow is another day. But I need 11/2020
    output = tf.strings.regex_replace("Today's date is 11/2020. Tomorrow is another day.", pattern=r'[\d]{2}/[\d]{4}', rewrite=" ")
    
    # model inference ...

    return {'output': output}

这将返回一个张量,内容为“今天的日期。明天又是新的一天。”

仅返回日期的模式会是什么样子?如果我没记错的话,tf.strings.regex_replace 使用不支持前瞻的 re2。还有其他解决方案吗?

提前致谢

最佳答案

你可以使用

 tf.strings.regex_replace("Today's date is 11/2020. Tomorrow is another day.", pattern=r'.*?(\d{2}/\d{4}).*', rewrite=r'\1')

请参阅RE2 regex demo 。详情:

  • .*?(\d{2}/\d{4}).* 匹配0个或多个除换行符之外的字符,尽可能少,(\d {2}/\d{4}) 将任意两位数字捕获到第 1 组中,/ 然后是任意四位数字,然后仅匹配其余的数字与 .* 一致(贪婪地,尽可能多)
  • \1 是对组 1 值的括号引用。请参阅regex_replace reference : regex_rewrite "支持反斜杠转义数字(\1\9),可以插入与相应括号组匹配的文本。”。

关于regex - 使用正则表达式从 Tensorflow 2 中的 tf.Tensor 中提取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64789833/

相关文章:

tensorflow - 如何使用 Tensorflow Serving 提供重新训练的 Inception 模型?

python-3.x - TensorFlow 服务 : get input shape and labels

Java split() 方法不会再次起作用

python - 安装 tflearn 但未找到 contrib

python - 如何使用 export_savedmodel 函数导出 Estimator 模型

python - 为什么结果打印 b'hello,Python!' ,当我使用tensorflow?

python - 如何从 Keras 的 model.predict 函数获取预测标签?

java - 在Java中使用Matcher时出现无限循环

php - 使用 .htaccess 更改 URL .php 扩展名

python - 使用Python正则表达式可随时从某个字符之后的字符串中提取数字。