以MNIST数据训练集为例,
本人在将数据集切片后,发现batch(实现数据的分批),map(对一个序列的每一个元素用一个function处理,形成一个新序列)对一个对象的作用位置不能随意摆放,还与map中的function有关系。
例子:
def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32)/255.
x = tf.reshape(x, [-1, 28 * 28])
y = tf.cast(y, dtype=tf.int64)
y = tf.one_hot(y, depth=10)
return x, y
batchsize = 128
train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.shuffle(60000).batch(batchsize).map(preprocess)
上述例子先进行数据打包,再对数据用map方法的函数处理,所以使用map处理时对象已经打包完(x的shape 为[128,28,28]),因此在运行preprocess时要注意此时的x在运行reshape时不能直接使用[2828]完成降维,**而应该使用[-1,2828]实现降维**。
另一个是先对数据用map方法的函数处理,再打包数据,代码如下:
def preprocess(x, y):
"""
x is a simple image, not a batch
"""
x = tf.cast(x, dtype=tf.float32) / 255.
x = tf.reshape(x, [28*28])
y = tf.cast(y, dtype=tf.int32)
y = tf.one_hot(y, depth=10)
return x,y
batchsize = 128
train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.map(preprocess).shuffle(60000).batch(batchsize)
此时map的对象直接是切片完的数据集,即60000个[28,28]的图片,因为还未打包,因此此时的(x,y)只是一张图片和一个标签。所以function中对x进行reshape应该是使用[28*28]实现降维。