Python 在使用tf.data时,如何对数据进行定制预处理?

Python 在使用tf.data时,如何对数据进行定制预处理?,python,tensorflow,tf.data.dataset,Python,Tensorflow,Tf.data.dataset,我需要一些关于tf.data的帮助 我正在做一些关于团队数据集的实验。给定的数据集结构如下所示: row-1] { conext: "some big string", question:"q string", "answer": "some ans" } 我想使用tf.data进行加载和预处理。加载后,以foll格式加载。格式: { context: Tensor("some big string

我需要一些关于tf.data的帮助

我正在做一些关于团队数据集的实验。给定的数据集结构如下所示:

row-1]  { conext: "some big string", question:"q string", "answer": "some ans" }
我想使用tf.data进行加载和预处理。加载后,以foll格式加载。格式:

{
  context: Tensor("some big string"), 
  question:Tensor(q string),
  answer": Tensor(some ans) 
}
现在我们要对数据进行预处理。这里的预处理并不简单,因为值是张量对象。

Tensorflow为此类预处理提供了一些API,但是如果我想进行自定义预处理,或者我想使用spacy,它只对原始数据类型(如字符串而不是张量)进行操作,该怎么办

基本上,我需要以下代码片段的帮助:

def format_data(row):
  # Now I can access individual data row here. But value of row is in Tensor form.

  # Hence I can't use my custom function. How to use custom function or spacy function which operates on string and not on tensor?

  # I can use only below tf functions
  return tf.strings.regex_replace(row['context'],'some-regex',' ',True)


train = dataset.map(format_data).batch(2)
ist(train.take(1))
以下代码有效:

def parse_str(str_tensor):
    raw_string = str_tensor.numpy().decode("utf-8") 

    # play with raw string
    raw_string = 'AAA'+raw_string     
    return raw_string
调用解析函数:

def tf_pre_processing(row):
  return tf.py_function(parse_str, [row['context']], [tf.string])


train = t.map(tf_pre_processing).batch(1).take(1)

list(train)
以下代码有效:

def parse_str(str_tensor):
    raw_string = str_tensor.numpy().decode("utf-8") 

    # play with raw string
    raw_string = 'AAA'+raw_string     
    return raw_string
调用解析函数:

def tf_pre_processing(row):
  return tf.py_function(parse_str, [row['context']], [tf.string])


train = t.map(tf_pre_processing).batch(1).take(1)

list(train)

#我也试过使用tf.py_函数,它不起作用。#我也试过使用tf.py_函数,它不起作用。