tf.data.Dataset(variant_tensor)
tf.data.Dataset.from_tensor_slice
a = (1,2,3,4,5,6)
aa = tf.constant(a, shape=(2,3))
dataset = tf.data.Dataset.from_tensor_slices(aa)
for element in dataset:
print('element', element)
输出:
element tf.Tensor([1 2 3], shape=(3,), dtype=int32)
element tf.Tensor([4 5 6], shape=(3,), dtype=int32)
from_tensors( tensors)
a = (1,2,3,4,5,6)
aa = tf.constant(a, shape=(2,3), name='data')
dataset = tf.data.Dataset.from_tensors(aa)
for element in dataset:
print('element:', element)
输出:
element: tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)
1.element_spec:数据集元素的类型说明。
a = (1,2,3,4,5,6)
aa = tf.constant(a, shape=(2,3), name='data')
dataset = tf.data.Dataset.from_tensor_slices(aa)
print('element_spec:',dataset.element_spec)
输出:
element_spec: TensorSpec(shape=(3,), dtype=tf.int32, name=None)
2.as_numpy_iterator:使用as_numpy_iterator检查数据集的内容
a = (1,2,3,4,5,6)
aa = tf.constant(a, shape=(2,3), name=‘data’)
dataset = tf.data.Dataset.from_tensor_slices(aa)
for element in dataset.as_numpy_iterator():
print(‘element:’, element)
输出结果:
element: [1 2 3]
element: [4 5 6]
a = (1,2,3,4,5,6)
aa = tf.constant(a, shape=(2,3), name='data')
dataset = tf.data.Dataset.from_tensor_slices(aa)
print('list: ', list(dataset.as_numpy_iterator()))
输出结果:
list: [array([1, 2, 3]), array([4, 5, 6])]
3.apply(transformation_func):为数据集提供转换函数
a = (1,2,3,4,5,6)
aa = tf.constant(a, shape=(6,), name='data')
dataset = tf.data.Dataset.from_tensor_slices(aa)
dataset = dataset.apply(dataset_fn)
for element in dataset:
print('element:', element)
输出:
element: tf.Tensor(1, shape=(), dtype=int32)
element: tf.Tensor(2, shape=(), dtype=int32)
element: tf.Tensor(3, shape=(), dtype=int32)
element: tf.Tensor(4, shape=(), dtype=int32)
4.batch( batch_size, drop_remainder=False):数据集元素分批
dataset = tf.data.Dataset.range(8)
dataset = dataset.batch(3)
print(list(dataset.as_numpy_iterator()))
输出结果:
[array([0, 1, 2], dtype=int64), array([3, 4, 5], dtype=int64), array([6, 7], dtype=int64)]
dataset = tf.data.Dataset.range(8)
dataset = dataset.batch(3, True)
print(list(dataset.as_numpy_iterator()))
输出结果:
[array([0, 1, 2], dtype=int64), array([3, 4, 5], dtype=int64)]
5.cache( filename=’’):缓存数据集元素,缓存到文件或内层
dataset = tf.data.Dataset.range(5)
dataset = dataset.map(lambda x: x**2)
dataset = dataset.cache()
#第一次读取数据将使用“ range”和“ map”生成数据。
print(list(dataset.as_numpy_iterator()))
#第2次从缓存中读取
print(list(dataset.as_numpy_iterator()))
输出结果:
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
dataset = tf.data.Dataset.range(5)
dataset = dataset.cache("C:/Users/byroot/Desktop/test/dede")
print(list(dataset.as_numpy_iterator()))
dataset = tf.data.Dataset.range(10)
dataset = dataset.cache("C:/Users/byroot/Desktop/test/dede")
print(list(dataset.as_numpy_iterator()))
输出结果:
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
6.cardinality():返回数据集的元素总数。
dataset = tf.data.Dataset.range(66)
print(dataset.cardinality().numpy())
输出结果:
66
7.concatenate( dataset):连接数据集 组成新的数据集
a = tf.data.Dataset.range(1, 4) # ==> [ 1, 2, 3 ]
b = tf.data.Dataset.range(4, 8) # ==> [ 4, 5, 6, 7 ]
ds = a.concatenate(b)
list(ds.as_numpy_iterator())
输出结果:
[1, 2, 3, 4, 5, 6, 7]
8.enumerate( start=0):列举数据集元素,从start序号开始
a = (1,2,3,4,5,6)
aa = tf.constant(a, shape=(2,3), name='data')
dataset = tf.data.Dataset.from_tensor_slices(aa)
dataset = dataset.enumerate(2)
for element in dataset.as_numpy_iterator():
print('element:', element)
输出结果:
element: (2, array([1, 2, 3]))
element: (3, array([4, 5, 6]))
a = (1,2,3,4,5,6)
aa = tf.constant(a, shape=(2,3), name='data')
dataset = tf.data.Dataset.from_tensor_slices(aa)
dataset = dataset.enumerate()
for element in dataset.as_numpy_iterator():
print('element:', element)
输出结果:
element: (0, array([1, 2, 3]))
element: (1, array([4, 5, 6]))
9.filter(predicate):根据条件过滤元素
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
dataset = dataset.filter(lambda x: x < 3)
print(list(dataset.as_numpy_iterator()))
输出结果:
[1, 2]
def filter_fn(x):
return tf.math.equal(x, 1)
dataset = dataset.filter(filter_fn)
print(list(dataset.as_numpy_iterator()))
输出结果:
[1]
10.flat_map(map_func):将批次的数据集展平为其元素的数据集
dataset = tf.data.Dataset.from_tensor_slices(
[[1, 2, 3], [4, 5, 6], [7, 8, 9]])
dataset = dataset.flat_map(lambda x: dataset.from_tensor_slices(x))
print(list(dataset.as_numpy_iterator()))
输出结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
11.from_generator( generator, output_types, output_shapes=None, args=None)创建一个数据集,其元素由generator生成。
def gen():
for i in itertools.count(1):
yield (i, [1] * i)
dataset = tf.data.Dataset.from_generator(
gen,
(tf.int64, tf.int64),
(tf.TensorShape([]), tf.TensorShape([None])))
print(list(dataset.take(3).as_numpy_iterator()))
输出结果:
[(1, array([1], dtype=int64)), (2, array([1, 1], dtype=int64)), (3, array([1, 1, 1], dtype=int64))]
12.interleave( map_func, cycle_length=None, block_length=None, num_parallel_calls=None, deterministic=None)
map_func:对数据进行处理的函数
cycle_length:并行程度,即并行的去同时处理dataset中的多少个元素
block_length:从上面变换的结果中,每次取多少个结果出来
dataset = tf.data.Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ]
dataset = dataset.interleave(
lambda x: tf.data.Dataset.from_tensors(x).repeat(6),
cycle_length=3, block_length=4)
print(list(dataset.as_numpy_iterator()))
输出结果:
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 4, 4, 5, 5]
dataset = tf.data.Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ]
dataset = dataset.interleave(
lambda x: tf.data.Dataset.from_tensors(x).repeat(6),
cycle_length=2, block_length=4)
print(list(dataset.as_numpy_iterator()))
输出结果:
[1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5]
13.list_files( file_pattern, shuffle=None, seed=None):列出所有文件
files = tf.data.Dataset.list_files("C:/Users/byroot/Desktop/test/dede*.txt")
print(list(files.as_numpy_iterator()))
输出结果:
[b'C:\\Users\\byroot\\Desktop\\test\\dede3.txt', b'C:\\Users\\byroot\\Desktop\\test\\dede2.txt', b'C:\\Users\\byroot\\Desktop\\test\\dede1.txt']
14.map( map_func, num_parallel_calls=None, deterministic=None):
dataset = tf.data.Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ]
dataset = dataset.map(lambda x: x + 1)
print(list(dataset.as_numpy_iterator()))
输出:
[2, 3, 4, 5, 6]
elements = [(1, "foo"), (2, "bar"), (3, "baz")]
dataset = tf.data.Dataset.from_generator(
lambda: elements, (tf.int32, tf.string))
result = dataset.map(lambda x_int, y_str: x_int)
print(list(result.as_numpy_iterator()))
输出结果:
[1, 2, 3]
elements = ([{"a": 1, "b": "foo"},
{"a": 2, "b": "bar"},
{"a": 3, "b": "baz"}])
dataset = tf.data.Dataset.from_generator(
lambda: elements, {"a": tf.int32, "b": tf.string})
result = dataset.map(lambda d: str(d["a"]) + d["b"])
print(list(result.as_numpy_iterator()))
输出结果:
[b’Tensor(“args_0:0”, dtype=int32)foo’, b’Tensor(“args_0:0”, dtype=int32)bar’, b’Tensor(“args_0:0”, dtype=int32)baz’]
dataset = tf.data.Dataset.range(3)
# `map_func` returns two `tf.Tensor` objects.
def g(x):
return tf.constant(37.0), tf.constant(["Foo", "Bar", "Baz"])
result = dataset.map(g)
print(list(result.as_numpy_iterator()))
输出结果:
[(37.0, array([b’Foo’, b’Bar’, b’Baz’], dtype=object)), (37.0, array([b’Foo’, b’Bar’, b’Baz’], dtype=object)), (37.0, array([b’Foo’, b’Bar’, b’Baz’], dtype=object))]
15.padded_batch(batch_size, padded_shapes=None, padding_values=None, drop_remainder=False)
A = (tf.data.Dataset.range(1, 5, output_type=tf.int32).map(lambda x: tf.fill([x], x)))
print(list(A.as_numpy_iterator()))#[array([1]), array([2, 2]), array([3, 3, 3]), array([4, 4, 4, 4])]
# Pad to the smallest per-batch size that fits all elements.
B = A.padded_batch(3)
print(list(B.as_numpy_iterator()))
输出:
[array([[1, 0, 0],
[2, 2, 0],
[3, 3, 3]]), array([[4, 4, 4, 4]])]
A = (tf.data.Dataset.range(1, 5, output_type=tf.int32).map(lambda x: tf.fill([x], x)))
# Pad to the smallest per-batch size that fits all elements.
B = A.padded_batch(2)
print(list(B.as_numpy_iterator()))
输出结果:
[array([[1, 0],
[2, 2]]), array([[3, 3, 3, 0],
[4, 4, 4, 4]])]
A = (tf.data.Dataset.range(1, 5, output_type=tf.int32).map(lambda x: tf.fill([x], x)))
C = A.padded_batch(2, padded_shapes=5)
print(list(C.as_numpy_iterator()))
输出结果:
[array([[1, 0, 0, 0, 0],
[2, 2, 0, 0, 0]]), array([[3, 3, 3, 0, 0],
[4, 4, 4, 4, 0]])]
A = (tf.data.Dataset.range(1, 5, output_type=tf.int32).map(lambda x: tf.fill([x], x)))
# Pad with a custom value.
D = A.padded_batch(2, padded_shapes=5, padding_values=6)
print(list(D.as_numpy_iterator()))
输出:
[array([[1, 6, 6, 6, 6],
[2, 2, 6, 6, 6]]), array([[3, 3, 3, 6, 6],
[4, 4, 4, 4, 6]])]
elements = [([1, 2, 3], [10]),
([4, 5], [11, 12])]
dataset = tf.data.Dataset.from_generator(
lambda: iter(elements), (tf.int32, tf.int32))
dataset = dataset.padded_batch(2,padded_shapes=([4], [None]),padding_values=(-1, 100))
print(list(dataset.as_numpy_iterator()))
输出:
[(array([[ 1, 2, 3, -1],
[ 4, 5, -1, -1]]), array([[ 10, 100],
[ 11, 12]]))]
elements = [([1, 2, 3], [10]),
([4, 5], [11, 12])]
dataset = tf.data.Dataset.from_generator(
lambda: iter(elements), (tf.int32, tf.int32))
dataset = dataset.padded_batch(2,padded_shapes=([4], [3]),padding_values=(-1, 100))
print(list(dataset.as_numpy_iterator()))
输出:
[(array([[ 1, 2, 3, -1],
[ 4, 5, -1, -1]]), array([[ 10, 100, 100],
[ 11, 12, 100]]))]
16.prefetch( buffer_size):创建一个数据集,该数据集从另外数据集中预取元素。
dataset = tf.data.Dataset.range(5)#[0, 1, 2, 3, 4]
dataset = dataset.prefetch(1)
print(list(dataset.as_numpy_iterator()))
输出:
[0, 1, 2, 3, 4]
17.reduce(initial_state, reduce_func)
将输入数据集简化为单个元素。
转换会在输入数据集的每个元素上依次调用reduce_func,直到数据集用完为止,以其内部状态汇总信息。 initial_state参数用于初始状态,并返回最终状态作为结果。
deded = tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, _: x + 1).numpy()
print(deded)#5
frfr = tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, y: x + y).numpy()
print(frfr)#10
18.shard(num_shards, index)
A = tf.data.Dataset.range(10)
B = A.shard(num_shards=3, index=0)
print(list(B.as_numpy_iterator()))
C = A.shard(num_shards=3, index=1)
print(list(C.as_numpy_iterator()))
D = A.shard(num_shards=3, index=2)
print(list(D.as_numpy_iterator()))
输出:
[0, 3, 6, 9]
[1, 4, 7]
[2, 5, 8]
19.shuffle(buffer_size, seed=None, reshuffle_each_iteration=None):随机重新排列此数据集的元素。
dataset = tf.data.Dataset.range(5)
dataset = dataset.shuffle(2, reshuffle_each_iteration=True)
print(list(dataset.as_numpy_iterator()))
dataset = dataset.repeat(2) # doctest: +SKIP
print(list(dataset.as_numpy_iterator()))
输出:
[1, 2, 0, 3, 4]
[1, 0, 3, 2, 4, 1, 0, 3, 2, 4]
dataset = tf.data.Dataset.range(5)
dataset = dataset.shuffle(3, reshuffle_each_iteration=True)
print(list(dataset.as_numpy_iterator()))
dataset = dataset.repeat(2) # doctest: +SKIP
print(list(dataset.as_numpy_iterator()))
输出结果:
[2, 3, 0, 4, 1]
[1, 3, 0, 2, 4, 0, 1, 2, 4, 3]
20.skip(count)
dataset = tf.data.Dataset.range(10)
dataset = dataset.skip(7)
print(list(dataset.as_numpy_iterator()))
输出:
[7, 8, 9]
21.take(count)
dataset = tf.data.Dataset.range(10)
dataset = dataset.take(3)
print(list(dataset.as_numpy_iterator()))
输出:
[0, 1, 2]
22.unbatch():将数据集的元素拆分为多个元素。
elements = [ [1, 2, 3], [1, 2], [1, 2, 3, 4] ]
dataset = tf.data.Dataset.from_generator(lambda: elements, tf.int64)
dataset = dataset.unbatch()
for e in dataset.as_numpy_iterator():
print(e)
输出:
1
2
3
1
2
1
2
3
4
23.window( size, shift=None, stride=1, drop_remainder=False)
size:表示要合并到窗口中的输入数据集的元素数。 必须是积极的。
shift:表示窗口在每次迭代中移动的输入元素的数量。 默认为大小。 必须是积极的。
stride:表示滑动窗口中输入元素的跨度。 必须是积极的。 默认值1表示“保留每个输入元素”。
drop_remainder:tf.bool标量tf.Tensor,表示如果最后一个窗口的大小小于size,是否应删除最后一个窗口。
dataset = tf.data.Dataset.range(7).window(2)
for window in dataset:
print(list(window.as_numpy_iterator()))
输出:
[0, 1]
[2, 3]
[4, 5]
[6]
dataset = tf.data.Dataset.range(7).window(2, 2, 1, True)
for window in dataset:
print(list(window.as_numpy_iterator()))
输出:
[0, 1]
[2, 3]
[4, 5]
dataset = tf.data.Dataset.range(7).window(2, 2, 2, True)
for window in dataset:
print(list(window.as_numpy_iterator()))
输出:
[0, 2]
[2, 4]
[4, 6]