关于 tf.data.TextLineDataset() 和常见dataset函数

  1. 官方原话:
  2. class TextLineDataset(dataset_ops.Dataset):
  3. """A `Dataset` comprising lines from one or more text files."""
  4. def __init__(self, filenames, compression_type=None, buffer_size=None):
  5. Creates a `TextLineDataset`.
  6. Args:
  7. filenames: A `tf.string` tensor containing one or more filenames.
  8. compression_type: (Optional.) A `tf.string` scalar evaluating to one of
  9. `""` (no compression), `"ZLIB"`, or `"GZIP"`.
  10. buffer_size: (Optional.) A `tf.int64` scalar denoting the number of bytes
  11. to buffer. A value of 0 results in the default buffering values chosen
  12. based on the compression type.


中文含义:
创造一个TextLineDataset()类
参数:
----filenames:                         单个或者多个string格式的文件名或者目录
----compression_type:   可选!!!格式是ZLIB或者GZIP
----buffer_size:                      可选!!!决定缓冲字节数多少

  1. 举例:
  2. # 文件路径可以用list包括起来,多个路径
  3. input_files = ['./input_file11', './input_file22']
  4. dataset = tf.data.TextLineDataset(input_files)

tf.data.TextLineDataset 接口提供了一种方法从数据文件中读取。我们提供只需要提供文件名(1个或者多个)。这个接口会自动构造一个dataset,类中保存的元素:文中一行,就是一个元素,是string类型的tensor

小知识:支持data包下多个函数的操作,目前深度学习中最常用的有4个方法如下

1.map():对元素进行操作

关于代码里面的tf.string_split可以看另外一篇文档:https://blog.csdn.net/xinjieyuan/article/details/90698352

  1. 格式:
  2. map(函数)
  3. # map里面的函数决定了dataset中的数据的处理方式。列如:
  4. dataset.map(Lambda string:tf.string_split([string]).values)
  5. # dataset中元素命名为string,对string进行切割操作
  6. '''
  7. 注:
  8. tf.string_split(
  9. source,
  10. delimiter=' ',
  11. skip_empty=True
  12. )
  13. source:需要操作的对象,一般是字符串或者多个字符串构成的列表;
  14. delimiter:分割符,默认空字符串
  15. skip_empty:m默认True,暂时没用到过
  16. '''
  1. # 官方代码
  2. map
  3. View source
  4. map(
  5. map_func,
  6. num_parallel_calls=None
  7. )
  8. Maps map_func across the elements of this dataset.
  9. This transformation applies map_func to each element of this dataset, and returns a new dataset containing the transformed elements, in the same order as they appeared in the input.
  10. For example:
  11. a = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ]
  12. a.map(lambda x: x + 1) # ==> [ 2, 3, 4, 5, 6 ]
  13. The input signature of map_func is determined by the structure of each element in this dataset. For example:
  14. # NOTE: The following examples use `{ ... }` to represent the
  15. # contents of a dataset.
  16. # Each element is a `tf.Tensor` object.
  17. a = { 1, 2, 3, 4, 5 }
  18. # `map_func` takes a single argument of type `tf.Tensor` with the same
  19. # shape and dtype.
  20. result = a.map(lambda x: ...)
  21. # Each element is a tuple containing two `tf.Tensor` objects.
  22. b = { (1, "foo"), (2, "bar"), (3, "baz") }
  23. # `map_func` takes two arguments of type `tf.Tensor`.
  24. result = b.map(lambda x_int, y_str: ...)
  25. # Each element is a dictionary mapping strings to `tf.Tensor` objects.
  26. c = { {"a": 1, "b": "foo"}, {"a": 2, "b": "bar"}, {"a": 3, "b": "baz"} }
  27. # `map_func` takes a single argument of type `dict` with the same keys as
  28. # the elements.
  29. result = c.map(lambda d: ...)
  30. The value or values returned by map_func determine the structure of each element in the returned dataset.
  31. # `map_func` returns a scalar `tf.Tensor` of type `tf.float32`.
  32. def f(...):
  33. return tf.constant(37.0)
  34. result = dataset.map(f)
  35. result.output_classes == tf.Tensor
  36. result.output_types == tf.float32
  37. result.output_shapes == [] # scalar
  38. # `map_func` returns two `tf.Tensor` objects.
  39. def g(...):
  40. return tf.constant(37.0), tf.constant(["Foo", "Bar", "Baz"])
  41. result = dataset.map(g)
  42. result.output_classes == (tf.Tensor, tf.Tensor)
  43. result.output_types == (tf.float32, tf.string)
  44. result.output_shapes == ([], [3])
  45. # Python primitives, lists, and NumPy arrays are implicitly converted to
  46. # `tf.Tensor`.
  47. def h(...):
  48. return 37.0, ["Foo", "Bar", "Baz"], np.array([1.0, 2.0] dtype=np.float64)
  49. result = dataset.map(h)
  50. result.output_classes == (tf.Tensor, tf.Tensor, tf.Tensor)
  51. result.output_types == (tf.float32, tf.string, tf.float64)
  52. result.output_shapes == ([], [3], [2])
  53. # `map_func` can return nested structures.
  54. def i(...):
  55. return {"a": 37.0, "b": [42, 16]}, "foo"
  56. result.output_classes == ({"a": tf.Tensor, "b": tf.Tensor}, tf.Tensor)
  57. result.output_types == ({"a": tf.float32, "b": tf.int32}, tf.string)
  58. result.output_shapes == ({"a": [], "b": [2]}, [])
  59. map_func can accept as arguments and return any type of dataset element.
  60. Note that irrespective of the context in which map_func is defined (eager vs. graph), tf.data traces the function and executes it as a graph. To use Python code inside of the function you have two options:
  61. 1) Rely on AutoGraph to convert Python code into an equivalent graph computation. The downside of this approach is that AutoGraph can convert some but not all Python code.
  62. 2) Use tf.py_function, which allows you to write arbitrary Python code but will generally result in worse performance than 1). For example:
  63. d = tf.data.Dataset.from_tensor_slices(['hello', 'world'])
  64. # transform a string tensor to upper case string using a Python function
  65. def upper_case_fn(t: tf.Tensor) -> str:
  66. return t.numpy().decode('utf-8').upper()
  67. d.map(lambda x: tf.py_function(func=upper_case_fn,
  68. inp=[x], Tout=tf.string)) # ==> [ "HELLO", "WORLD" ]
  69. Args:
  70. map_func: A function mapping a dataset element to another dataset element.
  71. num_parallel_calls: (Optional.) A tf.int32 scalar tf.Tensor, representing the number elements to process asynchronously in parallel. If not specified, elements will be processed sequentially. If the value tf.data.experimental.AUTOTUNE is used, then the number of parallel calls is set dynamically based on available CPU.
  72. Returns:
  73. Dataset: A Dataset.

 

2.shuttle():

  1. 打乱元素的序列
  2. 其实就是随机组合

3.zip()

可以把不同的dataset组合起来

  1. # 生成两个不同的dataset
  2. dataset1 = tf.data.Dataset.from_tensor_slices(tf.random_uniform([4, 10]))
  3. dataset2 = tf.data.Dataset.from_tensor_slices(
  4. (tf.random_uniform([4]),
  5. tf.random_uniform([4, 100], maxval=100, dtype=tf.int32)))
  6. # 进行组合
  7. dataset3 = tf.data.Dataset.zip((dataset1, dataset2))
  8. '''
  9. 注:
  10. 使用zip()函数时候,注意要把多个dataset用括号包起来
  11. 不然会报:
  12. TypeError: zip() takes 1 positional argument but 2 were given
  13. '''
  1. # 官方原文
  2. zip
  3. View source
  4. @staticmethod
  5. zip(datasets)
  6. Creates a Dataset by zipping together the given datasets.
  7. This method has similar semantics to the built-in zip() function in Python, with the main difference being that the datasets argument can be an arbitrary nested structure of Dataset objects. For example:
  8. a = Dataset.range(1, 4) # ==> [ 1, 2, 3 ]
  9. b = Dataset.range(4, 7) # ==> [ 4, 5, 6 ]
  10. c = Dataset.range(7, 13).batch(2) # ==> [ [7, 8], [9, 10], [11, 12] ]
  11. d = Dataset.range(13, 15) # ==> [ 13, 14 ]
  12. # The nested structure of the `datasets` argument determines the
  13. # structure of elements in the resulting dataset.
  14. Dataset.zip((a, b)) # ==> [ (1, 4), (2, 5), (3, 6) ]
  15. Dataset.zip((b, a)) # ==> [ (4, 1), (5, 2), (6, 3) ]
  16. # The `datasets` argument may contain an arbitrary number of
  17. # datasets.
  18. Dataset.zip((a, b, c)) # ==> [ (1, 4, [7, 8]),
  19. # (2, 5, [9, 10]),
  20. # (3, 6, [11, 12]) ]
  21. # The number of elements in the resulting dataset is the same as
  22. # the size of the smallest dataset in `datasets`.
  23. Dataset.zip((a, d)) # ==> [ (1, 13), (2, 14) ]
  24. Args:
  25. datasets: A nested structure of datasets.
  26. Returns:
  27. Dataset: A Dataset.

4.filter()

过滤符合要求的元素

  1. # 设置过滤器
  2. def FilterLength(src_len,trg_len):
  3. len_ok = tf.logical_andgic(
  4. tf.greater(src_len,1), # src_len大于1,返回True
  5. tf.less_equal(trg_len,MAX_LEN) # trg_len小于MAX_LEN,返回True
  6. )
  7. return len_ok
  8. # 调用过滤器,过滤不符合条件的元素
  9. dataset = dataset.filter(FilterLength)

官方原文:

  1. filter
  2. View source
  3. filter(predicate)
  4. Filters this dataset according to predicate.
  5. d = tf.data.Dataset.from_tensor_slices([1, 2, 3])
  6. d = d.filter(lambda x: x < 3) # ==> [1, 2]
  7. # `tf.math.equal(x, y)` is required for equality comparison
  8. def filter_fn(x):
  9. return tf.math.equal(x, 1)
  10. d = d.filter(filter_fn) # ==> [1]
  11. Args:
  12. predicate: A function mapping a dataset element to a boolean.
  13. Returns:
  14. Dataset: The Dataset containing the elements of this dataset for which predicate is True.

 

(0)

相关推荐