我尝试制作最近邻算法,将图像分为2类。我正在使用https://github.com/aymericdamien/TensorFlow-Examples
中的示例和代码以下是Xtr和Ytr中的代码片段结果为2个数组,我可以使用for i in range(len(Xte)):
之类的语句循环,并将它们编入索引,如Xte[i, :]
。
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training
Xte, Yte = mnist.test.next_batch(200) #200 for testing
我现在尝试做的是对我自己的图像数据集做同样的事情,我按照https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/5_DataManagement/build_an_image_dataset.ipynb中的示例来构建我自己的数据集
在对图像进行解码和调整大小之后使用以下语句并生成一批用标签表示图像的张量,但是我不能像上面那样使用它们并循环它们:
X, Y = tf.train.batch([image, label], batch_size=batch_size, capacity=batch_size*8, num_threads=4)
我的问题是如何使用这些张量以及如何迭代它们或将它们解析为数组以便以与上面相同的方式使用它们?
以下是我用于生成批处理的函数read_images的完整定义:
N_CLASSES = 2
IMG_HEIGHT = 28
IMG_WIDTH = 28
CHANNELS = 1
def read_images(dataset_path, batch_size):
imagepaths, labels = list(), list()
label = 0
try:
classes = sorted(os.walk(dataset_path).next()[1])
except:
classes = sorted(os.walk(dataset_path).__next__()[1])
for c in classes:
c_dir = os.path.join(dataset_path, c)
try:
walk = os.walk(c_dir).next()
except:
walk = os.walk(c_dir).__next__()
for sample in walk[2]:
if(sample.endswith('.jpg') or sample.endswith('.jpeg')):
imagepaths.append(os.path.join(c_dir, sample))
labels.append(label)
imagepaths = tf.convert_to_tensor(imagepaths, dtype=tf.string)
labels = tf.convert_to_tensor(labels, dtype=tf.int32)
image, label = tf.train.slice_input_producer([imagepaths, labels], shuffle=True)
image = tf.read_file(image)
image = tf.image.decode_jpeg(image, channels=CHANNELS)
image = tf.image.resize_images(image, [IMG_HEIGHT, IMG_WIDTH])
image = image * 1.0/127.5 - 1.0
X, Y = tf.train.batch([image, label], batch_size=batch_size, capacity=batch_size*8, num_threads=4)
return X, Y