2017-11-30 17 views
0

私はテンソルフローを使用して独自の大きな画像ライブラリ(数百万のラベル付き画像)で画像分類を行うのが好きです。私はstackoverflow、python、tensorflowを初めて使っていて、いくつかのチュートリアル(mnistなど)を通して自分自身を開発し、ポイントに達しました。ここでは、TensorFlowデータセットを辞書から準備できました。ラベル。しかし、私はTensorFlowセッションでデータセットを使用している時点で立ち往生しています。トレーニングのためにTensorFlowセッションでデータセットを使用する方法

from __future__ import absolute_import 
from __future__ import division 
from __future__ import print_function 
import tensorflow as tf 
import numpy as np 
import time 
import mymodule # I build my module to read the images and labels 
from tensorflow.python.framework import ops 
from tensorflow.python.framework import dtypes 
from tensorflow.contrib.data import Iterator 

beginTime = time.time() 
batch_size = 100 
learning_rate = 0.005 
max_steps = 2 
NUM_CLASSES = 25 

def input_parser(img_path, label): 
    one_hot = tf.one_hot(label, NUM_CLASSES) 

    img_file = tf.read_file(img_path) 
    img_decoded = tf.image.decode_jpeg(img_file, channels = 3) 

    return img_decoded, one_hot 

#Import Training data (returns the dicitonary with paths and labels) 
train_dict = mymodule.getFileMap(labelList, imageList) 

#Import Test data 
test_dict = mymodule.getFileMap(labelList, imageList) 

#Get train data 
train_file_list, train_label_list = get_file_label_list(train_dict) 
train_images_tensor = ops.convert_to_tensor(train_file_list, dtype=dtypes.string) 
train_labels_tensor = ops.convert_to_tensor(train_label_list, dtype=dtypes.int64) 

#Get test data 
test_file_list, test_label_list = get_file_label_list(test_dict) 
test_images_tensor = ops.convert_to_tensor(test_file_list, dtype=dtypes.string) 
test_labels_tensor = ops.convert_to_tensor(test_label_list, dtype=dtypes.int64) 

#Create TensorFlow Datset object 
train_data = tf.data.Dataset.from_tensor_slices((train_images_tensor, train_labels_tensor)) 
test_data = tf.data.Dataset.from_tensor_slices((test_images_tensor, test_labels_tensor)) 

# Transform the datset so that it contains decoded images 
# and one-hot vector labels 
train_data = train_data.map(input_parser) 
test_data = test_data.map(input_parser) 

# Batching --> How to do it right? 
#train_data = train_data.batch(batch_size = 100) 
#test_data = train_data.batch(batch_size = 100) 

#Define input placeholders 
image_size = 990*990*3 
images_placeholder = tf.placeholder(tf.float32, shape=[None, image_size]) 
labels_placeholder = tf.placeholder(tf.int64, shape=[None]) 

# Define variables (these afe the values we want to optimize) 
weigths = tf.Variable(tf.zeros([image_size, NUM_CLASSES])) 
biases = tf.Variable(tf.zeros([NUM_CLASSES])) 

# Define the classifier´s result 
logits = tf.matmul(images_placeholder, weigths) + biases 

# Define the loss function 
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels = labels_placeholder)) 

# Define the training operation 
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) 

# Operation comparing prediciton with true label 
correct_prediciton = tf.equal(tf.argmax(logits, 1), labels_placeholder) 

# Operation calculating the accuracy of our predicitons 
accuracy = tf.reduce_mean(tf.cast(correct_prediciton, tf.float32)) 

#Create TensorFlow Iterator object 
iterator = Iterator.from_structure(train_data.output_types, 
            train_data.output_shapes) 
next_element = iterator.get_next() 

#Create two initialization ops to switch between the datasets 
train_init_op = iterator.make_initializer(train_data) 
test_init_op = iterator.make_initializer(test_data) 


with tf.Session() as sess: 
    #Initialize variables 
    sess.run(tf.global_variables_initializer()) 
    sess.run(train_init_op) 
    for _ in range(10): 
     try: 
      elem = sess.run(next_element) 
      print(elem) 
     except tf.errors.OutOfRangeError: 
      print("End of training datset.") 
      break 

私は訓練のためにtensorflowセッションで(画像およびラベル)のデータセットを使用する方法の問題を解決することができませんでしたthisthisチュートリアル後:ここに私の(例)コードです。私はそれを繰り返してdatsetを印刷することができましたが、学習のために使用することはできませんでした。

私はthe 2nd tutorialによってrequriedとして、彼らは、train_data = tf.data.Dataset.from_tensor_slices((train_images_tensor、train_labels_tensor))操作中に合併された後に別々の画像とラベルにアクセスする方法を理解ドント。また、バッチ処理を正しく実装する方法もわかりません。どのような私はセッションでやりたいこと(the 2nd tutorialから)基本的にはこれです

# Generate input data batch 
indices = np.random.choice(data_sets['images_train'].shape[0], batch_size) 
images_batch = data_sets['images_train'][indices] 
labels_batch = data_sets['labels_train'][indices] 

# Periodically print out the model's current accuracy 
if i % 100 == 0: 
    train_accuracy = sess.run(accuracy, feed_dict={ 
    images_placeholder: images_batch, labels_placeholder: labels_batch}) 
    print('Step {:5d}: training accuracy {:g}'.format(i, train_accuracy)) 

# Perform a single training step 
sess.run(train_step, feed_dict={images_placeholder: images_batch, 
    labels_placeholder: labels_batch}) 

# After finishing the training, evaluate on the test set 
test_accuracy = sess.run(accuracy, feed_dict={ 
    images_placeholder: data_sets['images_test'], 
    labels_placeholder: data_sets['labels_test']}) 
print('Test accuracy {:g}'.format(test_accuracy)) 

endTime = time.time() 
print('Total time: {:5.2f}s'.format(endTime - beginTime)) 

誰もがsepearatelyデータセット内の画像やラベルにアクセスし、トレーニングのためにそれを使用する方法を、私に言うことができる場合、私は本当に感謝しています。また、バッチ処理を行う場所と方法についてもご理解いただけます。 ありがとうございます。

答えて

1

コードのnext_elementは、データセットの構造に一致する2つのテンソルのタプルです。つまり、最初の要素がイメージで、2番目の要素がラベルです。個々のテンソルにアクセスするには、次の操作を行うことができます。

next_element = iterator.get_next() 
next_image = next_element[0] 
next_label = next_element[1] 

# Or, in a single line: 
next_image, next_label = iterator.get_next() 

バッチtf.data.Datasetするには、Dataset.batch()変換を使用することができます。あなたのコメントアウトされたコードは、次のように単純に動作するはずです。

train_data = train_data.batch(batch_size = 100) 
test_data = train_data.batch(batch_size = 100) 
+0

ありがとうございました。イテレータを使って、私はイメージを印刷し、テンソルをセッションで別々にラベル付けすることができますが、 "feed_dict"にフィードすれば、フィードがテンソルにならないと言ってTypeErrorを取得します。 – makrobos

+0

それはshouldn 'feed_dict'でイテレータの出力をフィードする必要があります。 'tf.placeholder()'を使ってイメージとラベルの入力を定義する代わりに、 'next_element'のテンソルをモデルの入力として使うようにコードの順序を変更してください。 – mrry

関連する問題