我在尝试增强MNIST数据集。这是我的尝试方法,但一直没有成功。
from tensorflow.examples.tutorials.mnist import input_dataimport tensorflow as tfX = mnist.train.imagesy = mnist.train.labelsdef flip_images(X_imgs): X_flip = [] tf.reset_default_graph() X = tf.placeholder(tf.float32, shape = (28, 28, 1)) input_d = tf.reshape(X_imgs, [-1, 28, 28, 1]) tf_img1 = tf.image.flip_left_right(X) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for img in input_d: flipped_imgs = sess.run([tf_img1], feed_dict = {X: img}) X_flip.extend(flipped_imgs) X_flip = np.array(X_flip, dtype = np.float32) return X_flipflip = flip_images(X)
我做错了什么?我实在是搞不明白。
错误:
Line: for img in input_d:raise TypeError("'Tensor' object is not iterable.")TypeError: 'Tensor' object is not iterable
回答:
首先要注意,你的tf.reshape操作将数据类型从ndarray变为了tensor。需要调用.eval()来将其转换回来。在那个for循环中,你试图遍历一个tensor(而不是列表或真正的可迭代对象),可以考虑使用数值索引,如下所示:
X = mnist.train.imagesy = mnist.train.labelsdef flip_images(X_imgs): X_flip = [] tf.reset_default_graph() X = tf.placeholder(tf.float32, shape = (28, 28, 1)) input_d = tf.reshape(X_imgs, [-1, 28, 28, 1]) tf_img1 = tf.image.flip_left_right(X) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for img_ind in range(input_d.shape[0]): img = input_d[img_ind].eval() flipped_imgs = sess.run([tf_img1], feed_dict={X: img}) X_flip.extend(flipped_imgs) X_flip = np.array(X_flip, dtype = np.float32) return X_flipflip = flip_images(X)
如果这解决了你的问题,请告诉我!为了测试,你可能需要将范围设置为一个较小的常数,如果没有GPU,这可能会花费一些时间。