在整个机器学习过程当中,除了训练模型外,应该就属数据预处理过程消耗的精力最多,数据预处理过程须要完成的任务包括数据读取、过滤、转换等等。为了将用户从繁杂的预处理操做中解放处理,更多地将精力放在算法建模上,TensorFlow中提供了data模块,这一模块以多种方式提供了数据读取、数据处理、数据保存等功能。本文重点是data模块中的Dataset对象。css
对于建立Dataset对象,官方文档中总结为两种方式,我将这两种方式细化后总结为4中方式:html
(1)经过Dataset中的range()方法建立包含必定序列的Dataset对象。html5
range()方法是Dataset内部定义的一个的静态方法,能够直接经过类名调用。另外,Dataset中的range()方法与Python自己内置的range()方法接受参数形式是一致的,能够接受range(begin)、range(begin, end)、range(begin, end, step)等多种方式传参。java
import tensorflow as tf
import numpy as np
dataset1 = tf.data.Dataset.range(5)
type(dataset1)
tensorflow.python.data.ops.dataset_ops.RangeDataset
注:RangeDataset是Dataset的一个子类。 Dataset对象属于可迭代对象, 可经过循环进行遍历:node
for i in dataset1:
print(i)
print(i.numpy())
tf.Tensor(0, shape=(), dtype=int64) 0 tf.Tensor(1, shape=(), dtype=int64) 1 tf.Tensor(2, shape=(), dtype=int64) 2 tf.Tensor(3, shape=(), dtype=int64) 3 tf.Tensor(4, shape=(), dtype=int64) 4
能够看到,range()方法建立的Dataset对象内部每个元素都以Tensor对象的形式存在,能够经过numpy()方法访问真实值。python
若是你以为range()方法不够灵活,功能不够强大,那么你能够尝试使用from_generator()方法。from_generator()方法接收一个可调用的生成器函数最为参数,在遍历from_generator()方法返回的Dataset对象过程当中不断生成新的数据,减小内存占用,这在大数据集中颇有用。jquery
def count(stop):
i = 0
while i<stop:
print('第%s次调用……'%i)
yield i
i += 1
dataset2 = tf.data.Dataset.from_generator(count, args=[3], output_types=tf.int32, output_shapes = (), )
a = iter(dataset2)
next(a)
第0次调用……
<tf.Tensor: id=46, shape=(), dtype=int32, numpy=0>
next(a)
第1次调用……
<tf.Tensor: id=47, shape=(), dtype=int32, numpy=1>
for i in dataset2:
print(i)
print(i.numpy())
第0次调用…… tf.Tensor(0, shape=(), dtype=int32) 0 第1次调用…… tf.Tensor(1, shape=(), dtype=int32) 1 第2次调用…… tf.Tensor(2, shape=(), dtype=int32) 2
(2)经过接收其余类型的集合类对象建立Dataset对象。这里所说的集合类型对象包含Python内置的list、tuple,numpy中的ndarray等等。这种建立Dataset对象的方法大多经过from_tensors()和from_tensor_slices()两个方法实现。这两个方法很经常使用,重点说一说。linux
当接收参数为list或Tensor对象时,返回的状况是同样的,由于TensorFlow内部会将list先转为Tensor对象,而后实例化一个Dataset对象:android
a = [0,1,2,3,4]
dataset1 = tf.data.Dataset.from_tensors(a)
dataset1_n = tf.data.Dataset.from_tensors(np.array(a))
dataset1_t = tf.data.Dataset.from_tensors(tf.constant(a))
dataset1,next(iter(dataset1))
(<TensorDataset shapes: (5,), types: tf.int32>, <tf.Tensor: id=67, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>)
dataset1_n,next(iter(dataset1_n))
(<TensorDataset shapes: (5,), types: tf.int64>, <tf.Tensor: id=73, shape=(5,), dtype=int64, numpy=array([0, 1, 2, 3, 4])>)
dataset1_t,next(iter(dataset1_t))
(<TensorDataset shapes: (5,), types: tf.int32>, <tf.Tensor: id=79, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>)
多维结构也是同样的:
a = [0,1,2,3,4]
b = [5,6,7,8,9]
dataset2 = tf.data.Dataset.from_tensors([a,b])
dataset2_n = tf.data.Dataset.from_tensors(np.array([a,b]))
dataset2_t = tf.data.Dataset.from_tensors(tf.constant([a,b]))
dataset2,next(iter(dataset2))
(<TensorDataset shapes: (2, 5), types: tf.int32>, <tf.Tensor: id=91, shape=(2, 5), dtype=int32, numpy= array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=int32)>)
dataset2_n,next(iter(dataset2_n))
(<TensorDataset shapes: (2, 5), types: tf.int64>, <tf.Tensor: id=97, shape=(2, 5), dtype=int64, numpy= array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])>)
dataset2_t,next(iter(dataset2_t))
(<TensorDataset shapes: (2, 5), types: tf.int32>, <tf.Tensor: id=103, shape=(2, 5), dtype=int32, numpy= array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=int32)>)
当接收参数为数组就不同了,此时Dataset内部内容为一个tuple,tuple的元素是原来tuple元素转换为的Tensor对象:
a = [0,1,2,3,4]
b = [5,6,7,8,9]
dataset3 = tf.data.Dataset.from_tensors((a,b))
for i in dataset3:
print(type(i))
print(i)
for j in i:
print(j)
<class 'tuple'> (<tf.Tensor: id=112, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>, <tf.Tensor: id=113, shape=(5,), dtype=int32, numpy=array([5, 6, 7, 8, 9], dtype=int32)>) tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int32) tf.Tensor([5 6 7 8 9], shape=(5,), dtype=int32)
当传入一个list时,时将list中元素逐个转换为Tensor对象而后依次放入Dataset中,因此Dataset中有多个Tensor对象:
a = [0,1,2,3,4]
dataset1 = tf.data.Dataset.from_tensor_slices(a)
dataset1
<TensorSliceDataset shapes: (), types: tf.int32>
for i,elem in enumerate(dataset1):
print(i, '-->', elem)
0 --> tf.Tensor(0, shape=(), dtype=int32) 1 --> tf.Tensor(1, shape=(), dtype=int32) 2 --> tf.Tensor(2, shape=(), dtype=int32) 3 --> tf.Tensor(3, shape=(), dtype=int32) 4 --> tf.Tensor(4, shape=(), dtype=int32)
a = [0,1,2,3,4]
b = [5,6,7,8,9]
dataset2 = tf.data.Dataset.from_tensor_slices([a,b])
dataset2
<TensorSliceDataset shapes: (5,), types: tf.int32>
for i,elem in enumerate(dataset2):
print(i, '-->', elem)
0 --> tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int32) 1 --> tf.Tensor([5 6 7 8 9], shape=(5,), dtype=int32)
当传入参数为tuple时,会将tuple中各元素转换为Tensor对象,而后将第一维度对应位置的切片进行从新组合成一个tuple依次放入到Dataset中,因此在返回的Dataset中有多个tuple。这种形式在对训练集和测试集进行从新组合是很是实用。
a = [0,1,2,3,4]
b = [5,6,7,8,9]
dataset1 = tf.data.Dataset.from_tensor_slices((a,b))
dataset1
<TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.int32)>
for i in dataset1:
print(i)
(<tf.Tensor: id=143, shape=(), dtype=int32, numpy=0>, <tf.Tensor: id=144, shape=(), dtype=int32, numpy=5>) (<tf.Tensor: id=145, shape=(), dtype=int32, numpy=1>, <tf.Tensor: id=146, shape=(), dtype=int32, numpy=6>) (<tf.Tensor: id=147, shape=(), dtype=int32, numpy=2>, <tf.Tensor: id=148, shape=(), dtype=int32, numpy=7>) (<tf.Tensor: id=149, shape=(), dtype=int32, numpy=3>, <tf.Tensor: id=150, shape=(), dtype=int32, numpy=8>) (<tf.Tensor: id=151, shape=(), dtype=int32, numpy=4>, <tf.Tensor: id=152, shape=(), dtype=int32, numpy=9>)
c = ['a','b','c','d','e']
dataset3 = tf.data.Dataset.from_tensor_slices((a,b,c))
dataset3
<TensorSliceDataset shapes: ((), (), ()), types: (tf.int32, tf.int32, tf.string)>
for i in dataset3:
print(i)
(<tf.Tensor: id=162, shape=(), dtype=int32, numpy=0>, <tf.Tensor: id=163, shape=(), dtype=int32, numpy=5>, <tf.Tensor: id=164, shape=(), dtype=string, numpy=b'a'>) (<tf.Tensor: id=165, shape=(), dtype=int32, numpy=1>, <tf.Tensor: id=166, shape=(), dtype=int32, numpy=6>, <tf.Tensor: id=167, shape=(), dtype=string, numpy=b'b'>) (<tf.Tensor: id=168, shape=(), dtype=int32, numpy=2>, <tf.Tensor: id=169, shape=(), dtype=int32, numpy=7>, <tf.Tensor: id=170, shape=(), dtype=string, numpy=b'c'>) (<tf.Tensor: id=171, shape=(), dtype=int32, numpy=3>, <tf.Tensor: id=172, shape=(), dtype=int32, numpy=8>, <tf.Tensor: id=173, shape=(), dtype=string, numpy=b'd'>) (<tf.Tensor: id=174, shape=(), dtype=int32, numpy=4>, <tf.Tensor: id=175, shape=(), dtype=int32, numpy=9>, <tf.Tensor: id=176, shape=(), dtype=string, numpy=b'e'>)
对比总结一下from_generator()、from_tensor()、from_tensor_slices()这三个方法:
(3)经过读取磁盘中的文件(文本、图片等等)来建立Dataset。tf.data中提供了TextLineDataset、TFRecordDataset等对象来实现此功能。这部份内容比较多,也比较重要,我打算后续用专门一篇博客来总结这部份内容。
(1)take()
功能:用于返回一个新的Dataset对象,新的Dataset对象包含的数据是原Dataset对象的子集。
参数:
dataset = tf.data.Dataset.range(10)
dataset_take = dataset.take(5)
for i in dataset_take:
print(i)
tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) tf.Tensor(2, shape=(), dtype=int64) tf.Tensor(3, shape=(), dtype=int64) tf.Tensor(4, shape=(), dtype=int64)
(2)batch()
功能:将Dataset中连续的数据分割成批。
参数:
dataset = tf.data.Dataset.range(11)
dataset_batch = dataset.batch(3)
for i in dataset_batch:
print(i)
tf.Tensor([0 1 2], shape=(3,), dtype=int64) tf.Tensor([3 4 5], shape=(3,), dtype=int64) tf.Tensor([6 7 8], shape=(3,), dtype=int64) tf.Tensor([ 9 10], shape=(2,), dtype=int64)
dataset_batch = dataset.batch(3,drop_remainder=True)
for i in dataset_batch:
print(i)
tf.Tensor([0 1 2], shape=(3,), dtype=int64) tf.Tensor([3 4 5], shape=(3,), dtype=int64) tf.Tensor([6 7 8], shape=(3,), dtype=int64)
train_x = tf.random.uniform((10,3),maxval=100, dtype=tf.int32)
train_y = tf.range(10)
dataset = tf.data.Dataset.from_tensor_slices((train_x, train_y))
for i in dataset.take(3):
print(i)
(<tf.Tensor: id=236, shape=(3,), dtype=int32, numpy=array([81, 53, 85], dtype=int32)>, <tf.Tensor: id=237, shape=(), dtype=int32, numpy=0>) (<tf.Tensor: id=238, shape=(3,), dtype=int32, numpy=array([13, 7, 25], dtype=int32)>, <tf.Tensor: id=239, shape=(), dtype=int32, numpy=1>) (<tf.Tensor: id=240, shape=(3,), dtype=int32, numpy=array([83, 25, 55], dtype=int32)>, <tf.Tensor: id=241, shape=(), dtype=int32, numpy=2>)
dataset_batch = dataset.batch(4)
for i in dataset_batch:
print(i)
(<tf.Tensor: id=250, shape=(4, 3), dtype=int32, numpy= array([[81, 53, 85], [13, 7, 25], [83, 25, 55], [53, 41, 11]], dtype=int32)>, <tf.Tensor: id=251, shape=(4,), dtype=int32, numpy=array([0, 1, 2, 3], dtype=int32)>) (<tf.Tensor: id=252, shape=(4, 3), dtype=int32, numpy= array([[41, 58, 39], [44, 68, 55], [52, 34, 22], [66, 39, 5]], dtype=int32)>, <tf.Tensor: id=253, shape=(4,), dtype=int32, numpy=array([4, 5, 6, 7], dtype=int32)>) (<tf.Tensor: id=254, shape=(2, 3), dtype=int32, numpy= array([[73, 8, 20], [67, 71, 98]], dtype=int32)>, <tf.Tensor: id=255, shape=(2,), dtype=int32, numpy=array([8, 9], dtype=int32)>)
为何在训练模型时要将Dataset分割成一个个batch呢?
(3)padded_batch()
功能: batch()的进阶版,能够对shape不一致的连续元素进行分批。
参数:
dataset = tf.data.Dataset.range(10)
dataset = dataset.map(lambda x: tf.fill([tf.cast(x, tf.int32)], x))
dataset_padded = dataset.padded_batch(4, padded_shapes=(None,))
for batch in dataset_padded:
print(batch.numpy())
print('---------------------')
[[0 0 0] [1 0 0] [2 2 0] [3 3 3]] --------------------- [[4 4 4 4 0 0 0] [5 5 5 5 5 0 0] [6 6 6 6 6 6 0] [7 7 7 7 7 7 7]] --------------------- [[8 8 8 8 8 8 8 8 0] [9 9 9 9 9 9 9 9 9]] ---------------------
dataset_padded = dataset.padded_batch(4, padded_shapes=(10,),padding_values=tf.constant(9,dtype=tf.int64)) # 修改填充形状和填充元素
for batch in dataset_padded:
print(batch.numpy())
print('---------------------')
[[9 9 9 9 9 9 9 9 9 9] [1 9 9 9 9 9 9 9 9 9] [2 2 9 9 9 9 9 9 9 9] [3 3 3 9 9 9 9 9 9 9]] --------------------- [[4 4 4 4 9 9 9 9 9 9] [5 5 5 5 5 9 9 9 9 9] [6 6 6 6 6 6 9 9 9 9] [7 7 7 7 7 7 7 9 9 9]] --------------------- [[8 8 8 8 8 8 8 8 9 9] [9 9 9 9 9 9 9 9 9 9]] ---------------------
(4)map()
功能: 以dataset中每一位元素为参数执行pap_func()方法,这一功能在数据预处理中修改dataset中元素是很实用。
参数:
def change_dtype(t): # 将类型修改成int32
return tf.cast(t,dtype=tf.int32)
dataset = tf.data.Dataset.range(3)
for i in dataset:
print(i)
tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) tf.Tensor(2, shape=(), dtype=int64)
dataset_map = dataset.map(change_dtype)
for i in dataset_map:
print(i)
tf.Tensor(0, shape=(), dtype=int32) tf.Tensor(1, shape=(), dtype=int32) tf.Tensor(2, shape=(), dtype=int32)
map_func的参数必须对应dataset中的元素类型,例如,若是dataset中元素是tuple,map_func能够这么定义:
def change_dtype_2(t1,t2):
return t1/10,tf.cast(t2,dtype=tf.int32)*(-1) # 第一位元素除以10,第二为元素乘以-1
dataset = tf.data.Dataset.from_tensor_slices((tf.range(3),tf.range(3)))
dataset_map = dataset.map(change_dtype_2)
for i in dataset_map:
print(i)
(<tf.Tensor: id=347, shape=(), dtype=float64, numpy=0.0>, <tf.Tensor: id=348, shape=(), dtype=int32, numpy=0>) (<tf.Tensor: id=349, shape=(), dtype=float64, numpy=0.1>, <tf.Tensor: id=350, shape=(), dtype=int32, numpy=-1>) (<tf.Tensor: id=351, shape=(), dtype=float64, numpy=0.2>, <tf.Tensor: id=352, shape=(), dtype=int32, numpy=-2>)
(5)filter()
功能:对Dataset中每个执行指定过滤方法进行过滤,返回过滤后的Dataset对象
参数:
dataset = tf.data.Dataset.range(5)
def filter_func(t): # 过滤出值为偶数的元素
if t % 2 == 0:
return True
else:
return False
dataset_filter = dataset.filter(filter_func)
for i in dataset_filter:
print(i)
tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(2, shape=(), dtype=int64) tf.Tensor(4, shape=(), dtype=int64)
(6)shuffle()
功能:随机打乱数据
参数:
dataset = tf.data.Dataset.range(5)
dataset_s = dataset.shuffle(1)
for i in dataset_s:
print(i)
tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) tf.Tensor(2, shape=(), dtype=int64) tf.Tensor(3, shape=(), dtype=int64) tf.Tensor(4, shape=(), dtype=int64)
dataset_s = dataset.shuffle(5)
for i in dataset_s:
print(i)
tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(4, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) tf.Tensor(2, shape=(), dtype=int64) tf.Tensor(3, shape=(), dtype=int64)
(7)repeat()
功能:对Dataset中的数据进行重复,以建立新的Dataset
参数:
dataset = tf.data.Dataset.range(3)
dataset_repeat = dataset.repeat(3)
for i in dataset_repeat:
print(i)
tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) tf.Tensor(2, shape=(), dtype=int64) tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) tf.Tensor(2, shape=(), dtype=int64) tf.Tensor(0, shape=(), dtype=int64) tf.Tensor(1, shape=(), dtype=int64) tf.Tensor(2, shape=(), dtype=int64)