수색…


CSV 파일의 예제 계산

import tensorflow as tf
filename_queue = tf.train.string_input_producer(["file.csv"], num_epochs=1)
reader = tf.TextLineReader()
key, value = reader.read(filename_queue)
col1, col2 = tf.decode_csv(value, record_defaults=[[0], [0]])

with tf.Session() as sess:
  sess.run(tf.initialize_local_variables())
  tf.train.start_queue_runners()
  num_examples = 0
  try:
    while True:
      c1, c2 = sess.run([col1, col2])
      num_examples += 1
  except tf.errors.OutOfRangeError:
    print "There are", num_examples, "examples"

num_epochs=1 은 목록의 각 파일을 한 번 처리 한 후 string_input_producer 대기열을 닫습니다. 그것은 try: 잡힌 OutOfRangeError 를 발생 OutOfRangeError . 기본적으로 string_input_producer 는 파일 이름을 무한대로 생성합니다.

tf.initialize_local_variables() 는 실행될 때 string_input_producer 내부에서 num_epoch 지역 변수를 초기화하는 tensorflow Op입니다.

tf.train.start_queue_runners() 는 큐에 비동기 적으로 데이터를 추가하는 것을 처리하는 여분의 밟기를 시작합니다.

TFRecord 파일 읽기 및 구문 분석

TFRecord 파일 은 데이터 (텐서)를 저장하기위한 고유 텐서 흐름 이진 형식입니다. 파일을 읽으려면 CSV 예제와 비슷한 코드를 사용할 수 있습니다.

import tensorflow as tf
filename_queue = tf.train.string_input_producer(["file.tfrecord"], num_epochs=1)
reader = tf.TFRecordReader()
key, serialized_example = reader.read(filename_queue)

그런 다음 serialized_example Queue에서 예제를 파싱해야합니다. 당신은 사용하여 하나를 수행 할 수 tf.parse_example 이전 배치를 필요로하지만입니다 빨리 또는 tf.parse_single_example :

batch = tf.train.batch([serialized_example], batch_size=100)
parsed_batch = tf.parse_example(batch, features={
  "feature_name_1": tf.FixedLenFeature(shape=[1], tf.int64),
  "feature_name_2": tf.FixedLenFeature(shape=[1], tf.float32)
})

tf.train.batch 는 주어진 텐서 형태의 [x, y, z] 의 연속 된 값을 텐서의 형태 [batch_size, x, y, z] 합니다. features dict는 기능의 이름을 tensorflow의 기능 정의에 매핑 합니다 . 유사한 방식으로 parse_single_example 을 사용합니다.

parsed_example = tf.parse_single_example(serialized_example, {
  "feature_name_1": tf.FixedLenFeature(shape=[1], tf.int64),
  "feature_name_2": tf.FixedLenFeature(shape=[1], tf.float32)
})

tf.parse_exampletf.parse_single_example 은 값을 사용하여 기능 이름을 텐서에 매핑하는 사전을 반환합니다.

parse_single_example 에서 나온 예제를 배치하려면 dict에서 tensors를 추출하고 이전과 같이 tf.train.batch 를 사용해야합니다.

parsed_batch = dict(zip(parsed_example.keys(),
    tf.train.batch(parsed_example.values(), batch_size=100)

이전과 같이 데이터를 읽은 다음 sess.run 으로 평가할 모든 텐서 목록을 전달합니다.

with tf.Session() as sess:
  sess.run(tf.initialize_local_variables())
  tf.train.start_queue_runners()
  try:
    while True:
      data_batch = sess.run(parsed_batch.values())
      # process data
  except tf.errors.OutOfRangeError:
    pass

예제를 무작위로 섞는다.

예제를 무작위로 tf.train.batch 다음과 같이 tf.train.batch 대신 tf.train.shuffle_batch 함수를 사용할 수 있습니다.

parsed_batch = tf.train.shuffle_batch([serialized_example],
    batch_size=100, capacity=1000,
    min_after_dequeue=200)

tf.train.shuffle_batch (뿐만 아니라 tf.train.batch )는 tf.Queue 만들고 serialized_examples 를 계속 추가합니다.

capacity 은 한 번에 대기열에 몇 개의 요소를 저장할 수 있는지를 측정합니다. 용량이 클수록 메모리 사용량은 많아 지지만 스레드가이를 채우기를 기다리는 대기 시간이 짧아집니다.

min_after_dequeue 는 요소를 가져온 후 큐에있는 요소의 최소 수입니다. shuffle_batch 큐는 요소들을 완벽하게 균일하게 뒤섞어 놓지 않습니다. 이것은 엄청난 양의 데이터를 기억하고 있습니다. 대신, min_after_dequeuecapacity 요소 사이를 읽어 메모리에 저장하고 무작위로 배치를 선택합니다. 그런 다음 min_after_dequeuecapacity 사이의 수를 유지하기 위해 몇 가지 요소를 추가로 포함 capacity . 따라서 min_after_dequeue 값이 클수록 더 많은 요소가 무작위 적입니다. batch_size 요소의 선택은 최소한 min_after_dequeue 연속 요소에서 가져 min_after_dequeue 보장되지만 더 큰 capacity 이 있어야하고 처음에는 큐를 채우는 데 더 오래 걸립니다.

일괄 처리로 n 개 에포크의 데이터 읽기

데이터 예제가 이미 파이썬 변수로 읽혀지고 주어진 크기의 일괄 처리로 n 번 읽으 려한다고 가정합니다.

import numpy as np
import tensorflow as tf
data = np.array([1, 2, 3, 4, 5])
n = 4

일괄 적으로 데이터를 병합하려면 임의의 셔플 링을 사용하여 tf.train.batch 또는 tf.train.batch_shuffle 사용할 수 있지만 전체 데이터를 n 번 생성하는 텐서를 전달해야합니다.

limited_tensor = tf.train.limit_epochs(data, n)
batch = tf.train.shuffle_batch([limited_tensor], batch_size=3, enqueue_many=True, capacity=4)

limit_epochs 는 numpy 배열을 후드 아래의 텐서로 변환하고 n 번 생성 한 텐서를 반환하고 나중에 OutOfRangeError를 던집니다. shuffle_batch 전달 된 enqueue_many=True 인수는 텐서 목록 [limited_tensor] 의 각 텐서가 많은 예제를 포함하는 것으로 해석되어야 함을 나타냅니다. 일괄 처리 대기열의 용량은 텐서의 예제 수보다 작을 수 있습니다.

평소와 같이 데이터를 처리 할 수 ​​있습니다.

with tf.Session() as sess:
  sess.run(tf.initialize_local_variables())
  tf.train.start_queue_runners()
  try:
    while True:
      data_batch = sess.run(batch)
      # process data
  except tf.errors.OutOfRangeError:
    pass

TXT 파일에서 이미지 및 레이블을로드하는 방법

TXT 파일에서 직접 이미지와 레이블을로드하는 방법은 Tensorflow 설명서에서 설명하지 않았습니다. 아래 코드는 내가 어떻게 그것을 달성했는지 보여줍니다. 그러나 이것이 그것이 최선의 방법이라는 것을 의미하지는 않으며,이 방법은 추가 단계에서 도움이 될 것입니다.

예를 들어, 문서에서 단일 핫 벡터 [0,1]를 사용하는 동안 레이블을 하나의 정수 값 {0,1}에로드합니다.

# Learning how to import images and labels from a TXT file
#
# TXT file format
#
# path/to/imagefile_1 label_1
# path/to/imagefile_2 label_2
# ...                 ...
#
# where label_X is either {0,1}

#Importing Libraries
import os
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes

#File containing the path to images and the labels [path/to/images label]
filename = '/path/to/List.txt'

#Lists where to store the paths and labels
filenames = []
labels = []

#Reading file and extracting paths and labels
with open(filename, 'r') as File:
    infoFile = File.readlines() #Reading all the lines from File
    for line in infoFile: #Reading line-by-line
        words = line.split() #Splitting lines in words using space character as separator
        filenames.append(words[0])
        labels.append(int(words[1]))

NumFiles = len(filenames)

#Converting filenames and labels into tensors
tfilenames = ops.convert_to_tensor(filenames, dtype=dtypes.string)
tlabels = ops.convert_to_tensor(labels, dtype=dtypes.int32)

#Creating a queue which contains the list of files to read and the value of the labels
filename_queue = tf.train.slice_input_producer([tfilenames, tlabels], num_epochs=10, shuffle=True, capacity=NumFiles)

#Reading the image files and decoding them
rawIm= tf.read_file(filename_queue[0])
decodedIm = tf.image.decode_png(rawIm) # png or jpg decoder

#Extracting the labels queue
label_queue = filename_queue[1]

#Initializing Global and Local Variables so we avoid warnings and errors
init_op = tf.group(tf.local_variables_initializer() ,tf.global_variables_initializer())

#Creating an InteractiveSession so we can run in iPython
sess = tf.InteractiveSession()

with sess.as_default():
    sess.run(init_op)
    
    # Start populating the filename queue.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for i in range(NumFiles): #length of your filenames list
        nm, image, lb = sess.run([filename_queue[0], decodedIm, label_queue])
        
        print image.shape
        print nm
        print lb
        
        #Showing the current image
        plt.imshow(image)
        plt.show()

    coord.request_stop()
    coord.join(threads)


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow