1.建立文件列表,使用cifar-10数据集path='./data/cifar/'file_names=os.listdir(path)file_list=[os.join(path,file_name)forfile_nameinfile_namesiffile_name.endswith('.bin')]2.打开队列读取文件列表queue_list=tf.train.string_input_producer(file_list)3.构建读取器读取数据reader=tf.FixedLengthRecordReader(self.bytes)key,value=reader.read(queue_list)4.解析数据label_iamge=tf.decode_row(value,tf.uint8)5.将数据切割成特征值和目标值label=tf.slice(label_image,[0],[self.label_bytes])image=tf.slice(label_image,[self.label_bytes],[self.image_bytes])6.形状变化的特征值image_reshape=tf.reshape(image,[self.height,self.width,self.channel])7.BatchProcessimage_batch,label_batch=tf.train.batch([image,label]batch_size=10,num_threads=3,capacity=20)8.打开会话以使用tf.Session()作为sess进行训练:coord=tf.train。Coordinator()threads=tf.train.start_queue_runners(sess,coord=coord)print(sess.run([image_batch,label_batch]))coord.request_stop()coord.join(threads)完整代码importtensorflowastfiimportosclassCirarReader():def__init__(self,filelsit):self.file_list=filelsitself.height=32self.width=32self.channel=3self.label_bytes=1self.image_bytes=self.width*self.height*self.channelself.bytes=self.label_bytes+self.image_bytesdefread_decode_cifar(self):queue_list=tf.train.string_input_producer(self.file_list)reader=tf.FixedLengthRecordReader(self.bytes)key,readvalue=reader.(queue_list)#解析label_image=tf.decode_raw(value,tf.uint8)#将数据拆分为标签数据和图像数据,特征值和目标值label=tf.slice(label_image,[0],[self.label_bytes])image=tf.slice(label_image,[self.label_bytes],[self.image_bytes])#特征数据形状的变化image_reshape=tf.reshape(image,[self.height,self.width,self.channel])#批量image_batch,label_batch=tf.train.batch([image_reshape,label],batch_size=10,num_threads=3,capacity=20)returnimage_batch,label_batchif__name__=='__main__':path='./data/cifar/'file_names=os.listdir(path)文件列表=[os.path.join(path,file_name)forfile_nameinfile_namesiffile_name.endswith('.bin')]reader=CirarReader(file_list)image_batch,label_batch=reader.read_decode_cifar()withtf.Session()assess:coord=tf.train.Coordinator()threads=tf.train.start_queue_runners(sess,coord=coord)打印(sess.run([image_batch,label_batch]))coord.request_stop()coord.join(threads)
