2017-09-21 11 views
0

私はテンソルフローとPythonにはかなり新しく、現在は240x320x3イメージのための専門家のチュートリアルのためにMNISTを修正しようとしています。私は2の.pyスクリプトテンソルフローとラベルは同じサイズでなければなりません

tfrecord_reeader.pyを持って

import tensorflow as tf 
import numpy as np 
import matplotlib.pyplot as plt 

data_path = 'train.tfrecords' # address to save the hdf5 file 

def read_data(): 
    with tf.Session() as sess: 
     feature = {'train/image': tf.FixedLenFeature([], tf.string), 
        'train/label': tf.FixedLenFeature([], tf.int64)} 

     # Create a list of filenames and pass it to a queue 
     filename_queue = tf.train.string_input_producer([data_path], num_epochs=1) 

     # Define a reader and read the next record 
     reader = tf.TFRecordReader() 
     _, serialized_example = reader.read(filename_queue) 

     # Decode the record read by the reader 
     features = tf.parse_single_example(serialized_example, features=feature) 

     # Convert the image data from string back to the numbers 
     image = tf.decode_raw(features['train/image'], tf.float32) 

     # Cast label data into int32 
     label = tf.cast(features['train/label'], tf.int32) 

     # Reshape image data into the original shape 
     image = tf.reshape(image, [240, 320, 3]) 

    sess.close() 
    return image, label 

def next_batch(image, label, batchSize): 
    imageBatch, labelBatch = tf.train.shuffle_batch([image, label], batch_size=batchSize, capacity=30, num_threads=1, 
              min_after_dequeue=10) 
    return imageBatch, labelBatch 

train.py

import tensorflow as tf 
from random import shuffle 
import glob 
import sys 
#import cv2 
from tfrecord_reader import read_data, next_batch 
import argparse # For passing arguments 
import numpy as np 
import math 
import time 

IMAGE_WIDTH = 240 
IMAGE_HEIGHT = 320 
IMAGE_DEPTH = 3 
IMAGE_SIZE = 240*320*3 
NUM_CLASSES = 5 
BATCH_SIZE = 50 

# Creates a weight tensor sized by shape 
def weight_variable(shape): 
    initial = tf.truncated_normal(shape, stddev=0.1) 
    return tf.Variable(initial) 

# Creates a bias tensor sized by shape 
def bias_variable(shape): 
    initial = tf.constant(0.1, shape=shape) 
    return tf.Variable(initial) 

def conv2d(x, W): 
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 

def max_pool_2x2(x): 
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 
         strides=[1, 2, 2, 1], padding='SAME') 

def main(argv): 
    # Perform training 
    x = tf.placeholder(tf.float32, [None, IMAGE_SIZE]) # 240*320=76800 
    W = tf.Variable(tf.zeros([IMAGE_SIZE, NUM_CLASSES])) 
    b = tf.Variable(tf.zeros([NUM_CLASSES])) 
    y = tf.matmul(x, W) + b 

    # Define loss and optimizer 
    y_ = tf.placeholder(tf.float32, [None, NUM_CLASSES]) # Desired output 

    # First convolutional layer 
    W_conv1 = weight_variable([5, 5, IMAGE_DEPTH, 32]) 
    b_conv1 = bias_variable([32]) 

    x_image = tf.reshape(x, [-1, IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_DEPTH]) 

    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 
    h_pool1 = max_pool_2x2(h_conv1) 

    # Second convolutional layer 
    W_conv2 = weight_variable([5, 5, 32, 64]) 
    b_conv2 = bias_variable([64]) 
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 
    h_pool2 = max_pool_2x2(h_conv2) 

    # First fully connected layer 
    W_fc1 = weight_variable([60 * 80 * 64, 1024]) 
    b_fc1 = bias_variable([1024]) 

    # Flatten the layer 
    h_pool2_flat = tf.reshape(h_pool2, [-1, 60 * 80 * 64]) 
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 

    # Drop out layer 
    keep_prob = tf.placeholder(tf.float32) 
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 

    # Second fully connected layer 
    W_fc2 = weight_variable([1024, NUM_CLASSES]) 
    b_fc2 = bias_variable([NUM_CLASSES]) 

    # Output layer 
    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 
    # print(y_conv.shape) 
    # print(y_conv.get_shape) 

    # Get the loss 
    cross_entropy = tf.reduce_mean(
     tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) 

    # Minimize the loss 
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 

    # Read all data from tfrecord file 
    imageList, labelList = read_data() 
    imageBatch, labelBatch = next_batch(imageList, labelList, BATCH_SIZE) 

    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) 
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 

    with tf.Session() as sess: 
     sess.run(tf.local_variables_initializer()) 
     sess.run(tf.global_variables_initializer()) 

     coord = tf.train.Coordinator() 
     threads = tf.train.start_queue_runners(coord=coord) 

     train_images, train_labels = sess.run([imageBatch, labelBatch]) 
     train_images = np.reshape(train_images, (-1, IMAGE_SIZE)) 
     train_labels = np.reshape(train_labels, (-1, NUM_CLASSES)) 

     sess.run(train_step, feed_dict = {x: train_images, y_: train_labels, keep_prob: 1.0}) 

     coord.request_stop() 
     coord.join(threads) 
    sess.close() 

if __name__ == '__main__': 
    parser = argparse.ArgumentParser() 
    FLAGS, unparsed = parser.parse_known_args() 
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) 

私はプログラムを実行すると、私は私がしました

InvalidArgumentError (see above for traceback): logits and labels must be same size: logits_size=[50,5] labels_size=[10,5] 
    [[Node: SoftmaxCrossEntropyWithLogits = SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](Reshape_2, Reshape_3)]] 

を取得していますこの問題で数時間の検索を行ったが、なぜロットがラベルサイズに合致しないのか分からなかった。バッチサイズを10に変更すると、ラベルのサイズは常に5で割ったように[2,5]になります。誰か助けてくれますか?

+0

-

(あなただけの直接出力テンソルを使用することができますところで、あなたが実際にこの方法でデータを読み込む際にプレースホルダを使用する必要はありません。) 。 pdbはそれを行う良い方法です。 –

答えて

1

ほとんどの場合、ラベルはワンホットベクトルではなく単一の整数値なので、labelBatchは「1」や「4」などの単一の数値を含むサイズ[50]のベクトルです。今度は、train_labels = np.reshape(train_labels, (-1, NUM_CLASSES)) を使用してそれらの形状を変更すると、図形が[10、5]に変更されます。

tf.nn.softmax_cross_entropy_with_logits関数は、ラベルが "ワンホット"エンコーディングのラベルであることを前提としています(ラベル3は、サイズ5のベクトルに変換され、3の位置に1、他の場所に0が入ります)。 tf.nn.one_hot関数を使用してこれを実現できますが、より簡単な方法は、これらの単一値ラベルを使用するように設計されたtf.nn.sparse_softmax_cross_entropy_with_logits関数を使用することです。

y_ = tf.placeholder(tf.float32, [None]) # Desired output

cross_entropy = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))

そしてtrain_labels = np.reshape(train_labels, (-1, NUM_CLASSES))ラインを取り除く:これを実現するには、これらの行を変更する必要があります。あなたはREAD_DATAとnext_batch後にラベルの形状を確認する必要がある

+0

ありがとうございました。y_はfloat32の代わりにtf.int32が必要ですが、コードは修正後に動作します。そうしないとエラーが発生します。 を副次的な質問として、あなたが言ったようにプレースホルダの代わりにバッチデータをどのように割り当てるのですか? –

関連する問題