目錄
- 前言
- 示例
- 示例1
- 示例2
- 示例3
- 示例4
前言
TensorFlow 的 tf.data.Dataset API 提供了一種靈活且高效的方式來加載和預處理數據。它可以輕松處理大規模數據集,并支持多種數據源格式。 所有數據集相關的內容都在tf.data中,from_tensor_slices:可以從元組, 列表, 字典, ndarray中創建dataset。
示例
示例1
import tensorflow as tf
import numpy as npdataset = tf.data.Dataset.from_tensor_slices(np.arange(10))
print (dataset)# 數據集最基礎的用法就是取數據
for item in dataset:print(item)
結果如下:
<TensorSliceDataset shapes: (), types: tf.int32>
tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(4, shape=(), dtype=int32)
tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor(8, shape=(), dtype=int32)
tf.Tensor(9, shape=(), dtype=int32)
示例2
import tensorflow as tf
import numpy as np# 從元組創建dataset, (x,y)
x = np.array([[1, 2], [3, 4], [5, 6]])
y = np.array(['cat', 'dog', 'fox'])
dataset = tf.data.Dataset.from_tensor_slices((x, y))
for item_x, item_y in dataset:print(item_x.numpy(), item_y.numpy().decode())
結果如下
[1 2] b'cat'
[3 4] b'dog'
[5 6] b'fox'
示例3
import tensorflow as tf
import numpy as np# 從元組創建dataset, (x,y)
x = np.array([[1, 2], [3, 4], [5, 6]])
y = np.array(['cat', 'dog', 'fox'])
dataset = tf.data.Dataset.from_tensor_slices({'feature': x,'label': y
})
for item in dataset:print(item['feature'].numpy(), item['label'].numpy())
結果如下
[1 2] b'cat'
[3 4] b'dog'
[5 6] b'fox'
示例4
import tensorflow as tf
import numpy as np# interleave
# 最常見用法 : 文件名dataset --> 具體數據集
dataset = tf.data.Dataset.from_tensor_slices(np.arange(10))
dataset = dataset.repeat(3).batch(7)
# map_fn, cycle_length 并行長度, block_length
dataset = dataset.interleave(lambda v: tf.data.Dataset.from_tensor_slices(v),cycle_length = 5,block_length = 5
)
for item in dataset:print(item)
結果如下
tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(4, shape=(), dtype=int32)
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor(8, shape=(), dtype=int32)
tf.Tensor(9, shape=(), dtype=int32)
tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(4, shape=(), dtype=int32)
tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor(8, shape=(), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(4, shape=(), dtype=int32)
tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(8, shape=(), dtype=int32)
tf.Tensor(9, shape=(), dtype=int32)
tf.Tensor(5, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor(9, shape=(), dtype=int32)
tf.Tensor(0, shape=(), dtype=int32)
tf.Tensor(6, shape=(), dtype=int32)
tf.Tensor(7, shape=(), dtype=int32)