制作tfrecord并读取

import os
import tensorflow as tf
import numpy as np
import pandas as pd
import skimage.io as io
import matplotlib.pyplot as plt



def get_data (filename):
    class_train = []
    label_train = []
    label_data = pd.read_csv('./breastpathq/datasets/train_labels.csv')

    label_data.sort_values(by=['rid', 'slide'], ascending=True)

    for item in label_data['y']:
        if item == 0.0:
            label_train.append(0)
        elif item > 0.0 and item <= 0.1:
            label_train.append(1)
        elif item > 0.1 and item <= 0.2:
            label_train.append(2)
        elif item > 0.2 and item <= 0.3:
            label_train.append(3)
        elif item > 0.3 and item <= 0.4:
            label_train.append(4)
        elif item > 0.4 and item <= 0.6:
            label_train.append(5)
        elif item > 0.6 and item <= 0.8:
            label_train.append(6)
        elif item > 0.8 and item <= 0.9:
            label_train.append(7)
        elif item > 0.9 and item < 1:
            label_train.append(8)
        else:
            label_train.append(9)

    for i in range(label_data.shape[0]):
        class_train.append(
            filename + str(int(label_data.ix[i]['slide'])) + '_' + str(int(label_data.ix[i]['rid'])) + '.tif')
    print(label_train)
    print(class_train)
    # label_train = tf.one_hot(label_train, depth=10, on_value=0, off_value=1, axis=-1)


    temp = np.array([class_train, label_train])
    temp = temp.transpose()
    print(temp)
    np.random.shuffle(temp)
    # temp = {class_train: label_train}

    image_list = list(temp[:,0])
    label_list = list(temp[:,1])
    # image_list = list(temp.keys())
    # label_list = list(temp.values())

    label_list = [int(float(i)) for i in label_list]
    return image_list,label_list
# 转化成字符串


def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))


def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))


def convert_tfrecord(images,labels,save_filename):
    writer = tf.python_io.TFRecordWriter(save_filename)
    print("Transform start....")
    num_examples= len(labels)
    if np.shape(images)[0]!=num_examples:
        raise ValueError('Images size %d does not match label size %d.' % (images.shape[0], num_examples))
    for index in np.arange(0,num_examples):
        try:
            image = io.imread(images[index],as_grey=False)
            #image = tf.image.decode_jpeg(images[index])
            #print(image.shape)
            image_raw = image.tostring()
            #print(len(image_raw))
            example = tf.train.Example(features = tf.train.Features(feature={
                'label' :_int64_feature(int(labels[index])),
                'image_raw':_bytes_feature(image_raw)
            }))
            writer.write(example.SerializeToString())
        except IOError as e:
            print('Could not read:',images[index])
            print('error :%s Skip it !\n'%e)
    writer.close()
    print("success!")


def read_and_decodes(tfrecords_file,batch_size):
    reader = tf.TFRecordReader()
    filename_queue = tf.train.string_input_producer([tfrecords_file])
    _,serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
            'label': tf.FixedLenFeature([],tf.int64),
            'image_raw': tf.FixedLenFeature([], tf.string)
        }
    )
    #print(features['image_raw'])
    capacity = 1000+3*batch_size
    image = tf.decode_raw(features['image_raw'],tf.uint8)
    #wuhong
    label = tf.one_hot(features['label'], depth=10, on_value=1, off_value=0, axis=-1)
    label = tf.cast(label, tf.int32)
    #原始的
    # label = tf.cast(features['label'],tf.int32)

    #image = tf.image.resize_images(image,[300, 200, 1])

    image = tf.reshape(image,[512,512,3])
    image_batch,label_batch = tf.train.batch([image,label],
                                             batch_size=batch_size,
                                             capacity=capacity)
    # image_batch = tf.image.resize_image_with_crop_or_pad(image_batch,512,512)
    image_batch = tf.cast(image_batch, tf.float32) * (1. / 255)
    return image_batch,label_batch



def plot_images(images, labels):
    '''plot one batch size
    '''
    for i in np.arange(0, 2):
        plt.subplot(3, 3, i + 1)
        plt.axis('off')
        # plt.title((labels[i] - 1), fontsize = 14)
        plt.subplots_adjust(top=1)
        print(labels[i])
        print(images.shape)
        # print(images[i].shape)
        plt.imshow(images[i][:,:,:])
    plt.show()


def train():
    # image,label = get_data('./breastpathq/datasets/train/')
    # convert_tfrecord(image,label,'2.tfrecords')
    x_batch, y_batch = read_and_decodes('2.tfrecords', batch_size=128)
    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        try:
            i=0
            while not coord.should_stop() and i<3:
                     # just plot one batch size
                image, label = sess.run([x_batch, y_batch])
                plot_images(image, label)
                i+=1
        except tf.errors.OutOfRangeError:
            print('done!')
        finally:
            coord.request_stop()
        coord.join(threads)

if __name__ == "__main__":
    train()

 tensorflow官网上的example:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os.path
import sys
import time

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import mnist

# Basic model parameters as external flags.
FLAGS = None

# Constants used for dealing with the files, matches convert_to_records.
TRAIN_FILE = 'train.tfrecords'
VALIDATION_FILE = 'validation.tfrecords'


def read_and_decode(filename_queue):
  reader = tf.TFRecordReader()
  _, serialized_example = reader.read(filename_queue)
  features = tf.parse_single_example(
      serialized_example,
      # Defaults are not specified since both keys are required.
      features={
          'image_raw': tf.FixedLenFeature([], tf.string),
          'label': tf.FixedLenFeature([], tf.int64),
      })

  # Convert from a scalar string tensor (whose single string has
  # length mnist.IMAGE_PIXELS) to a uint8 tensor with shape
  # [mnist.IMAGE_PIXELS].
  image = tf.decode_raw(features['image_raw'], tf.uint8)
  image.set_shape([mnist.IMAGE_PIXELS])

  # OPTIONAL: Could reshape into a 28x28 image and apply distortions
  # here.  Since we are not applying any distortions in this
  # example, and the next step expects the image to be flattened
  # into a vector, we don't bother.
  # Convert from [0, 255] -> [-0.5, 0.5] floats.
  image = tf.cast(image, tf.float32) * (1. / 255) - 0.5

  # Convert label from a scalar uint8 tensor to an int32 scalar.
  label = tf.cast(features['label'], tf.int32)
  return image, label


def inputs(train, batch_size, num_epochs):
  """Reads input data num_epochs times.

  Args:
    train: Selects between the training (True) and validation (False) data.
    batch_size: Number of examples per returned batch.
    num_epochs: Number of times to read the input data, or 0/None to
       train forever

  Returns:
    A tuple (images, labels), where:
    * images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]
      in the range [-0.5, 0.5].
    * labels is an int32 tensor with shape [batch_size] with the true label,
      a number in the range [0, mnist.NUM_CLASSES).
    Note that an tf.train.QueueRunner is added to the graph, which
    must be run using e.g. tf.train.start_queue_runners().
  """
  if not num_epochs: num_epochs = None
  filename = os.path.join(FLAGS.train_dir,
                          TRAIN_FILE if train else VALIDATION_FILE)

  with tf.name_scope('input'):
    filename_queue = tf.train.string_input_producer(
        [filename], num_epochs=num_epochs)

    # Even when reading in multiple threads, share the filename
    # queue.
    image, label = read_and_decode(filename_queue)

    # Shuffle the examples and collect them into batch_size batches.
    # (Internally uses a RandomShuffleQueue.)
    # We run this in two threads to avoid being a bottleneck.
    images, sparse_labels = tf.train.shuffle_batch(
        [image, label], batch_size=batch_size, num_threads=2,
        capacity=1000 + 3 * batch_size,
        # Ensures a minimum amount of shuffling of examples.
        min_after_dequeue=1000)
    return images, sparse_labels


def run_training():

  """Train MNIST for a number of steps."""
  # Tell TensorFlow that the model will be built into the default Graph.
  with tf.Graph().as_default():
    # Input images and labels.
    images, labels = inputs(train=True, batch_size=FLAGS.batch_size,
                            num_epochs=FLAGS.num_epochs)

    # Build a Graph that computes predictions from the inference model.
    logits = mnist.inference(images,
                             FLAGS.hidden1,
                             FLAGS.hidden2)

    # Add to the Graph the loss calculation.
    loss = mnist.loss(logits, labels)

    # Add to the Graph operations that train the model.
    train_op = mnist.training(loss, FLAGS.learning_rate)

    # The op for initializing the variables.
    init_op = tf.group(tf.global_variables_initializer(),
                       tf.local_variables_initializer())

    # Create a session for running operations in the Graph.
    sess = tf.Session()

    # Initialize the variables (the trained variables and the
    # epoch counter).
    sess.run(init_op)

    # Start input enqueue threads.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    try:
      step = 0
      while not coord.should_stop():
        start_time = time.time()
        # Run one step of the model.  The return values are
        # the activations from the `train_op` (which is
        # discarded) and the `loss` op.  To inspect the values
        # of your ops or variables, you may include them in
        # the list passed to sess.run() and the value tensors
        # will be returned in the tuple from the call.
        _, loss_value = sess.run([train_op, loss])
        duration = time.time() - start_time
        # Print an overview fairly often.
        if step % 100 == 0:
          print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value,
                                                     duration))
        step += 1
    except tf.errors.OutOfRangeError:
      print('Done training for %d epochs, %d steps.' % (FLAGS.num_epochs, step))
    finally:
      # When done, ask the threads to stop.
      coord.request_stop()
    # Wait for threads to finish.
    coord.join(threads)
    sess.close()

def main(_):
  run_training()

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--learning_rate',
      type=float,
      default=0.01,
      help='Initial learning rate.'
  )
  parser.add_argument(
      '--num_epochs',
      type=int,
      default=2,
      help='Number of epochs to run trainer.'
  )

  parser.add_argument(

      '--hidden1',

      type=int,

      default=128,

      help='Number of units in hidden layer 1.'

  )

  parser.add_argument(
      '--hidden2',
      type=int,
      default=32,
      help='Number of units in hidden layer 2.'
  )

  parser.add_argument(
      '--batch_size',
      type=int,
      default=100,
      help='Batch size.'
  )
  parser.add_argument(
      '--train_dir',
      type=str,
      default='/tmp/data',
      help='Directory with the training data.'
  )
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

 在模型中读取tfrecord

def train():
    x_batch, y_batch = read_and_decodes('2.tfrecords', batch_size=32)
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        merged = tf.summary.merge_all()
        train_writer = tf.summary.FileWriter(_SAVE_BOARD_PATH, sess.graph)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        try:
            while not coord.should_stop():
                batch_xs, batch_ys = sess.run([x_batch, y_batch])
                start_time = time()
                i_global, _ = sess.run([global_step, optimizer], feed_dict={x: batch_xs, y: batch_ys})
                duration = time() - start_time
                _loss, batch_acc = sess.run([loss, accuracy], feed_dict={x: batch_xs, y: batch_ys})
                msg = "Glo bal Step: {0:>6}, accuracy: {1:>6.1%}, loss = {2:.2f} ({3:.1f} examples/sec, {4:.2f} sec/batch)"
                print(msg.format(i_global, batch_acc, _loss, _BATCH_SIZE / duration, duration))

                resultmerged = sess.run(merged, feed_dict={x: batch_xs, y: batch_ys})
                train_writer.add_summary(resultmerged, i_global)

                if (i_global % 100 == 0):
                    saver.save(sess, save_path=_SAVE_PATH, global_step=global_step)
                    print("Saved checkpoint")

 

 

你可能感兴趣的:(deeplearning,image_prepare)