2016-08-28 5 views
0

나는 단지 tensorflow로 시작하고 있으며 좋은 첫 번째 단계는 내 자신의 용도로 CIFAR10 모델을 적용하는 것이라고 생각했습니다. 내 데이터베이스는 이미지가 아니지만 신호 및 전체 데이터베이스는 모양이 [16400,3000,1,1]입니다 (차원 적으로 : 모든 샘플, 높이, 너비 및 목적에 따라 추가 된 채널 수). MatConvNet 도구 상자로 이미이 문제를 해결하고 있습니다. 따라서이 질문은 엄격하게 텐톨 흐름에 대한 문제입니다. 코드가 아래Tensorflow CIFAR10 모델을 자체 데이터에 맞게 수정

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

import os 

from six.moves import xrange # pylint: disable=redefined-builtin 
import tensorflow as tf 
import numpy as np 

IMAGE_SIZE = 3000 

data = np.load('/home/tensorflow-master/tensorflow/models/image/cifar10 /konsensop/data.npy') 
labels = np.load('/home/tensorflow-master/tensorflow/models/image/cifar10/konsensop/labels.npy') 
labels = labels-1 
labels = labels.astype(int) 
data = tf.cast(data,tf.float32) 
labels = tf.cast(labels,tf.int64) 

NUM_CLASSES = 2 
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 10000 
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 6400 
def _generate_image_and_label_batch(data_sample, label, in_queue_examples, 
           batch_size, shuffle): 
num_preprocess_threads = 16 
if shuffle: 
    data, label_batch = tf.train.shuffle_batch(
    [data_sample, label], 
    batch_size=batch_size, 
    num_threads=num_preprocess_threads, 
    capacity=min_queue_examples + batch_size, 
    min_after_dequeue=min_queue_examples) 
else: 
    data, label_batch = tf.train.batch(
    [data_sample, label], 
    batch_size=batch_size, 
    num_threads=num_preprocess_threads, 
    capacity=min_queue_examples + batch_size) 

    return data, tf.reshape(label_batch, [batch_size]) 

def inputs(data,labels, batch_size): 
    for i in xrange(0, data.shape[0]/batch_size): 
    data_sample = data[i,:,:,:] 
    label = labels[i,0] 
    height = 3000 
    width = 1 
    min_fraction_of_examples_in_queue = 0.4 
    min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN* 
     min_fraction_of_examples_in_queue) 
    print('Filling queue with %d data before starting to train' % min_queue_examples) 
    return _generate_image_and_label_batch(data_sample, label, 
            min_queue_examples, batch_size, 
            shuffle=True) 

은 내가 aleady 가지고 생성 데이터를로드하기 위해 노력하고있어 교육 스크립트 읽을 수 있도록 데이터를 준비하는 나의 시도에서 데이터베이스는 위의 크기의 준비 NumPy와 텐서입니다 방법의 cifar10 모델의 배치는했지만 트레이너 코드를 실행할 때 나는 data,labels = konsensop_input.inputs(data,labels,batch_size) UnboundcocalError: local variable 'data' referenced before assigment

data = konsensop_input.data 
labels = konsensop_input.labels 
def train(): 
    with tf.Graph().as_default(): 
    global_step = tf.Variable(0, trainable = False) 
    data, labels = konsensop_input.inputs(data, labels, batch_size) 
    logits = konsensop_train.inference(data) 
# calculate loss 
    loss = konsensop.loss(logits, labels) 
    train_op = konsensop.train(loss, global_step) 
# create a saver 
    saver = tf.train.Saver(tf.all_variables()) #saves all variables in a graph 
# build the summary operation based on the TF collection of summaries 
    summary_op = tf.merge_all_summaries() 
# build an initialization operation to run below 
    init = tf.initialize_all_variables() 
# start running operations on the graph 
    sess = tf.Session(config = tf.ConfigProto(log_device_placement=False)) 
    sess.run(init) 
# start the queue runners 
    tf.train.start_queue_runners(sess = sess) #co to i po co to""" 
    summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph) 

    for step in xrange(FLAGS.max_step): 
    start_time = time.time() 
    _, loss_value = sess.run([train_op, loss]) 
    duration = time.time() - start_time 
    assert not np.isnan(loss_value), 'Model diverged with loss = NaN' 

    if step % 10 == 0: 
     num_examples_per_step = FLAGS.batch_size 
     examples_per_sec = num_examples_per_step/duration 
     sec_per_batch = float(duration) 

     format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f sec/batch)') 
     print (format_str % (datetime.now(), step, loss_value, examples_per_sec, sec_per_batch)) 

    if step % 100 == 0: 
     summary_str = sess.run(summary_op) 
     summary_writer.add_summary(summary_str, step) 

    if step % 1000 == 0 or (step + 1) == FLAGS.max_steps: 
     checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt') 
     saver.save(sess, checkpoint_path, global_step = step) 

def main(argv=None): 
train() 

if __name__=='__main__': 
tf.app.run() 

나는 상대적으로 작은 여기를 합리적인 데이터 공급 기술

답변

0

을 구현하는 방법을 알아낼 싶습니다에 오류가 원하는 데이터 세트 k를 사용하는 경우 큰 번호 매기기 배열로로드 한 다음 미니 배치로 반복하여 계산합니다. 및 feed_dict 메커니즘을 통해 계산 그래프로 전달할 수 있습니다.

이 같은 (당신은 아마 각 시대 이후 랜덤 셔플을 추가해야합니다) 볼 수있는 미니 배치 반복 :.이 파이썬 발전기 구글,

def iterate_batches(X, y, batch_size, num_epochs): 
    N = np.size(X, 0) 
    batches_per_epoch = N/float(batch_size) 
    for i in range(num_epochs): 
     for j in range(batches_per_epoch): 
      start, stop = j*batch_size, (j+1)*batch_size 
      yield X[start:stop, :], y[start:stop] 

(파이썬의 yield 메커니즘에 익숙하지 않은 경우를 웹에 좋은 소개의 제비.)

당신이 NumPy와 배열 X_train, y_train로 설정 전체 데이터를로드하는 메커니즘을 가지고 있음을 감안할 때, 당신은 다음이

처럼 훈련 루프를 쓸 수 있습니다

여기에서 X_tensory_tensor은 네트워크 아키텍처에서 지정해야하는 데이터의 경우 tf.placeholder입니다.

관련 문제