tensorflow 인증 코드 인식 실현 (2)

tfrecords
5W 장의 그림 이 있 는 훈련 집 이 있 기 때문에 placeholder 방식 으로 데 이 터 를 graph 에 먹 인 다 면 정말 어 리 석 은 일이 다.그래서 tensorflow 가 공식 적 으로 추천 한 tfrecords 로 IO 를 진행 하 는 것 이 좋 습 니 다.이러한 IO 방식 은 주로 두 단계 입 니 다. 1. 먼저 데이터 dump 를 tfrecords 파일 로 만 듭 니 다. 2. 대기 열 로 데 이 터 를 모델 에 먹 입 니 다.
데 이 터 를 쓰다
tfrecords 파일 은 바 이 너 리 파일 입 니 다. 이 바 이 너 리 파일 을 열 면 전혀 읽 을 수 없 지만 tensor flow 는 이 바 이 너 리 파일 을 읽 고 쓸 때 바 텀 에 google 이 추진 하 는 protocol buffer (프로 토 콜 메모리) 를 사용 합 니 다. 이것 은 비교적 편안 합 니 다. 바 이 너 리 파일 을 블랙박스 로 사용 할 수 있 습 니 다.코드 차원 의 논리 가 정확 하면 문제 가 없다.
방금 tfrecords 가 프로 토 콜 버퍼 라 고 했 으 니 프로 토 콜 을 훑 어보 세 요.먼저 데이터 세트 는 여러 개의 데이터 로 구성 되 어 있 고 모든 데 이 터 는 여러 필드 (특징) 로 구성 되 어 있다 고 상상 할 수 있다.그래서 tfrecords 에 서 는 example 로 데 이 터 를 표시 하고 features 로 데이터 의 특징 을 표시 합 니 다.
그럼 덩굴 을 따라 참 외 를 만 질 수 있 습 니 다. example. proto 와 feature. proto 가 어떻게 생 겼 는 지 보 세 요.
example.proto
// Protocol messages for describing input data Examples for machine learning
// model training or inference.
syntax = "proto3";

import "tensorflow/core/example/feature.proto";
option cc_enable_arenas = true;
option java_outer_classname = "ExampleProtos";
option java_multiple_files = true;
option java_package = "org.tensorflow.example";

package tensorflow;

// An Example is a mostly-normalized data format for storing data for
// training and inference.  It contains a key-value store (features); where
// each key (string) maps to a Feature message (which is oneof packed BytesList,
// FloatList, or Int64List).  This flexible and compact format allows the
// storage of large amounts of typed data, but requires that the data shape
// and use be determined by the configuration files and parsers that are used to
// read and write this format.  That is, the Example is mostly *not* a
// self-describing format.  In TensorFlow, Examples are read in row-major
// format, so any configuration that describes data with rank-2 or above
// should keep this in mind.  For example, to store an M x N matrix of Bytes,
// the BytesList must contain M*N bytes, with M rows of N contiguous values
// each.  That is, the BytesList value must store the matrix as:
//     .... row 0 .... .... row 1 .... // ...........  // ... row M-1 ....
//
// An Example for a movie recommendation application:
//   features {
//     feature {
//       key: "age"
//       value { float_list {
//         value: 29.0
//       }}
//     }
//     feature {
//       key: "movie"
//       value { bytes_list {
//         value: "The Shawshank Redemption"
//         value: "Fight Club"
//       }}
//     }
//     feature {
//       key: "movie_ratings"
//       value { float_list {
//         value: 9.0
//         value: 9.7
//       }}
//     }
//     feature {
//       key: "suggestion"
//       value { bytes_list {
//         value: "Inception"
//       }}
//     }
//     # Note that this feature exists to be used as a label in training.
//     # E.g., if training a logistic regression model to predict purchase
//     # probability in our learning tool we would set the label feature to
//     # "suggestion_purchased".
//     feature {
//       key: "suggestion_purchased"
//       value { float_list {
//         value: 1.0
//       }}
//     }
//     # Similar to "suggestion_purchased" above this feature exists to be used
//     # as a label in training.
//     # E.g., if training a linear regression model to predict purchase
//     # price in our learning tool we would set the label feature to
//     # "purchase_price".
//     feature {
//       key: "purchase_price"
//       value { float_list {
//         value: 9.99
//       }}
//     }
//  }
//
// A conformant Example data set obeys the following conventions:
//   - If a Feature K exists in one example with data type T, it must be of
//       type T in all other examples when present. It may be omitted.
//   - The number of instances of Feature K list data may vary across examples,
//       depending on the requirements of the model.
//   - If a Feature K doesn't exist in an example, a K-specific default will be
//       used, if configured.
//   - If a Feature K exists in an example but contains no items, the intent
//       is considered to be an empty tensor and no default will be used.

message Example {
  Features features = 1;
};

// A SequenceExample is an Example representing one or more sequences, and
// some context.  The context contains features which apply to the entire
// example. The feature_lists contain a key, value map where each key is
// associated with a repeated set of Features (a FeatureList).
// A FeatureList thus represents the values of a feature identified by its key
// over time / frames.
//
// Below is a SequenceExample for a movie recommendation application recording a
// sequence of ratings by a user. The time-independent features ("locale",
// "age", "favorites") describing the user are part of the context. The sequence
// of movies the user rated are part of the feature_lists. For each movie in the
// sequence we have information on its name and actors and the user's rating.
// This information is recorded in three separate feature_list(s).
// In the example below there are only two movies. All three feature_list(s),
// namely "movie_ratings", "movie_names", and "actors" have a feature value for
// both movies. Note, that "actors" is itself a bytes_list with multiple
// strings per movie.
//
// context: {
//   feature: {
//     key  : "locale"
//     value: {
//       bytes_list: {
//         value: [ "pt_BR" ]
//       }
//     }
//   }
//   feature: {
//     key  : "age"
//     value: {
//       float_list: {
//         value: [ 19.0 ]
//       }
//     }
//   }
//   feature: {
//     key  : "favorites"
//     value: {
//       bytes_list: {
//         value: [ "Majesty Rose", "Savannah Outen", "One Direction" ]
//       }
//     }
//   }
// }
// feature_lists: {
//   feature_list: {
//     key  : "movie_ratings"
//     value: {
//       feature: {
//         float_list: {
//           value: [ 4.5 ]
//         }
//       }
//       feature: {
//         float_list: {
//           value: [ 5.0 ]
//         }
//       }
//     }
//   }
//   feature_list: {
//     key  : "movie_names"
//     value: {
//       feature: {
//         bytes_list: {
//           value: [ "The Shawshank Redemption" ]
//         }
//       }
//       feature: {
//         bytes_list: {
//           value: [ "Fight Club" ]
//         }
//       }
//     }
//   }
//   feature_list: {
//     key  : "actors"
//     value: {
//       feature: {
//         bytes_list: {
//           value: [ "Tim Robbins", "Morgan Freeman" ]
//         }
//       }
//       feature: {
//         bytes_list: {
//           value: [ "Brad Pitt", "Edward Norton", "Helena Bonham Carter" ]
//         }
//       }
//     }
//   }
// }
//
// A conformant SequenceExample data set obeys the following conventions:
//
// Context:
//   - All conformant context features K must obey the same conventions as
//     a conformant Example's features (see above).
// Feature lists:
//   - A FeatureList L may be missing in an example; it is up to the
//     parser configuration to determine if this is allowed or considered
//     an empty list (zero length).
//   - If a FeatureList L exists, it may be empty (zero length).
//   - If a FeatureList L is non-empty, all features within the FeatureList
//     must have the same data type T. Even across SequenceExamples, the type T
//     of the FeatureList identified by the same key must be the same. An entry
//     without any values may serve as an empty feature.
//   - If a FeatureList L is non-empty, it is up to the parser configuration
//     to determine if all features within the FeatureList must
//     have the same size.  The same holds for this FeatureList across multiple
//     examples.
//
// Examples of conformant and non-conformant examples' FeatureLists:
//
// Conformant FeatureLists:
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { float_list: { value: [ 5.0 ] } } }
//    } }
//
// Non-conformant FeatureLists (mismatched types):
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { int64_list: { value: [ 5 ] } } }
//    } }
//
// Conditionally conformant FeatureLists, the parser configuration determines
// if the feature sizes must match:
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { float_list: { value: [ 5.0, 6.0 ] } } }
//    } }
//
// Conformant pair of SequenceExample
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { float_list: { value: [ 5.0 ] } } }
//    } }
// and:
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { float_list: { value: [ 5.0 ] } }
//               feature: { float_list: { value: [ 2.0 ] } } }
//    } }
//
// Conformant pair of SequenceExample
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { float_list: { value: [ 5.0 ] } } }
//    } }
// and:
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { }
//    } }
//
// Conditionally conformant pair of SequenceExample, the parser configuration
// determines if the second feature_lists is consistent (zero-length) or
// invalid (missing "movie_ratings"):
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { float_list: { value: [ 5.0 ] } } }
//    } }
// and:
//    feature_lists: { }
//
// Non-conformant pair of SequenceExample (mismatched types)
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { float_list: { value: [ 5.0 ] } } }
//    } }
// and:
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { int64_list: { value: [ 4 ] } }
//               feature: { int64_list: { value: [ 5 ] } }
//               feature: { int64_list: { value: [ 2 ] } } }
//    } }
//
// Conditionally conformant pair of SequenceExample; the parser configuration
// determines if the feature sizes must match:
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.5 ] } }
//               feature: { float_list: { value: [ 5.0 ] } } }
//    } }
// and:
//    feature_lists: { feature_list: {
//      key: "movie_ratings"
//      value: { feature: { float_list: { value: [ 4.0 ] } }
//               feature: { float_list: { value: [ 5.0, 3.0 ] } }
//    } }

message SequenceExample {
  Features context = 1;
  FeatureLists feature_lists = 2;
};



feature.proto
syntax = "proto3";
option cc_enable_arenas = true;
option java_outer_classname = "FeatureProtos";
option java_multiple_files = true;
option java_package = "org.tensorflow.example";

package tensorflow;

// Containers to hold repeated fundamental values.
message BytesList {
  repeated bytes value = 1;
}
message FloatList {
  repeated float value = 1 [packed = true];
}
message Int64List {
  repeated int64 value = 1 [packed = true];
}

// Containers for non-sequential data.
message Feature {
  // Each feature can be exactly one kind.
  oneof kind {
    BytesList bytes_list = 1;
    FloatList float_list = 2;
    Int64List int64_list = 3;
  }
};

message Features {
  // Map from feature name to feature.
  map feature = 1;
};

// Containers for sequential data.
//
// A FeatureList contains lists of Features.  These may hold zero or more
// Feature values.
//
// FeatureLists are organized into categories by name.  The FeatureLists message
// contains the mapping from name to FeatureList.
//
message FeatureList {
  repeated Feature feature = 1;
};

message FeatureLists {
  // Map from feature name to feature list.
  map feature_list = 1;
};

이 두 개의 proto 를 보면 YY 가 그들의 관 계 를 대략 example {features: {'feature 1': xxx, 'feature 2': yy,..., 'featuren': 23333} 로 표시 할 수 있 습 니 다.
관 계 를 분명히 정리 한 후에 문 제 를 생각 할 수 있다.제 데 이 터 는 한 장의 그림 입 니 다. 가장 원시 적 인 특징 은 픽 셀 입 니 다. 그래서 그림 의 픽 셀 을 바이트 가 빠 른 것 으로 보고 문자열 로 정렬 하여 그림 을 표시 할 수 있 습 니 다.그래서 다음 코드 가 생 겼 습 니 다.
#   records
def conver_to_tfrecords(data_set, label_set, name):
    #proto    int64list
    def _int64_feature(value):
        return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

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

    print('     tfrecords', name)
    #   tfrecord writer,             
    writer = tf.python_io.TFRecordWriter(name)
    num_examples = len(data_set)
    for index in range(num_examples):
        image = data_set[index]
        height = image.shape[0]
        width = image.shape[1]
        #        
        image_raw = image.tostring()
        label = label_set[index]
        # onehot  label     
        label_raw = label_to_one_hot(label).tostring()
        #  example,  examp    , ,label,     
        example = tf.train.Example(features=tf.train.Features(feature={
            'height': _int64_feature(height),
            'width': _int64_feature(width),
            'label_raw': _bytes_feature(label_raw),
            'image_raw': _bytes_feature(image_raw)}))
        # example             name    
        writer.write(example.SerializeToString())
    writer.close()
    print('    !')

이때 데 이 터 는 tfrecords 파일 에 모두 기록 되 었 습 니 다.그럼 다음 에 해 야 할 일 은 대열 로 데 이 터 를 읽 는 것 이다.대기 열 로 데 이 터 를 읽 는 장점 은 메 인 스 레 드 를 훈련 모델 로 사용 할 수 있 고, 하위 스 레 드 는 대기 열 에서 데 이 터 를 가 져 올 수 있 으 며, 코드 를 쓴 사람 은 모두 이렇게 하면 무슨 좋 은 점 이 있 는 지 알 고 있다 는 것 이다.
데이터 읽 기
대기 열 을 사용 하려 면 먼저 대기 열 을 만들어 야 합 니 다. 그러면 대기 열 을 만 듭 니 다. 제 가 사용 하 는 tf. train. stringinput_producer, 내 그림 과 label 이 문자열 로 정렬 되 어 있 기 때 문 입 니 다.그럼 대열 이 있 으 면 내 가 대열 에서 데 이 터 를 가 져 올 거 야!!그래서 다음 코드 가 있 습 니 다.
def read_and_decode(filename_queue, img_height=IMG_HEIGHT, img_width=IMG_WIDTH, chars_num=CHAR_NUM, classes_num=len(CHAR_SET)):
    #   tfrecord reader,        
    reader = tf.TFRecordReader()
    #              ,             
    _, serialized_example = reader.read(filename_queue)
    #       ,PS:  tfrecords     label string,           string
    features = tf.parse_single_example(
        serialized_example,
        features={
          'image_raw': tf.FixedLenFeature([], tf.string),
          'label_raw': tf.FixedLenFeature([], tf.string),
      })
   #      string  float32,            ~~~
    image = tf.decode_raw(features['image_raw'], tf.float32)
    image.set_shape([img_height * img_width])
    image = tf.cast(image, tf.float32) * (1.0 / 255)-0.5
    reshape_image = tf.reshape(image, [img_height, img_width, 1])
    label = tf.decode_raw(features['label_raw'], tf.float32)
    label.set_shape([chars_num * classes_num])
    reshape_label = tf.reshape(label, [chars_num, classes_num])
    return tf.cast(reshape_image, tf.float32), tf.cast(reshape_label, tf.float32)


def inputs(train, batch_size, epoch):
    filename = os.path.join('./', TRAIN_RECORDS_NAME if train else TRAIN_VALIDATE_NAME)

    with tf.name_scope('input'):
        filename_queue = tf.train.string_input_producer([filename], num_epochs=epoch)
        image, label = read_and_decode(filename_queue)
        #       ,            batch    ,            batch
        if train:
            images, sparse_labels = tf.train.shuffle_batch([image, label], batch_size=batch_size, num_threads=6, capacity=2000 + 3 * batch_size, min_after_dequeue=2000)
        else:
            images, sparse_labels = tf.train.batch([image, label], batch_size=batch_size, num_threads=6, capacity=2000 + 3 * batch_size)

    return images, sparse_labels

코드 의 뜻 은 주석 으로 쓰 여 있 습 니 다. 그러나 주의해 야 할 것 은 tensor flow 가 graph 를 실행 하려 면 session 이 필요 하기 때문에 session 으로 inputs 를 실행 해 야 대기 열 에 데이터 가 있 습 니 다.이 대기 열 을 어떻게 실행 하 는 지 에 대해 서 는 뒤에서 다시 삐걱삐걱.오늘 은 여기까지.다음 편 은 CNN 전체 가 어떻게 어 울 리 는 지 기록 할 것 으로 보인다.

좋은 웹페이지 즐겨찾기