2016-06-22 60 views
0

我是tensorflow新手,我正在爲所有36個字符(0-9和a-z)訓練神經網絡。ValueError:廣播不兼容形狀

我轉換了幾個圖片使用tfrecords做:

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


import numpy as np 
import os 
import cv2 
import tensorflow as tf 

tf.app.flags.DEFINE_string('directory', '/root/data2', 
          'Directory to download data files and write the ' 
          'converted result') 
FLAGS = tf.app.flags.FLAGS 

def _int64_feature(value): 
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) 


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

def le_imagens(aux_folder): 
    cont=0 
    img=np.empty([1,28,28,1]) 
    for letter in os.listdir(aux_folder): 
     folder=aux_folder+letter+"/" 
     for imagem in os.listdir(folder): 
      os.chdir(folder) 
      img_temp=cv2.imread(imagem) 
      img_temp = cv2.cvtColor(img_temp,cv2.COLOR_BGR2GRAY) 
      img_temp= np.expand_dims(img_temp, axis=0) 
      img_temp= np.expand_dims(img_temp, axis=3) 
      img=np.vstack((img,img_temp)) 
      cont=cont+1 
      print (cont) 
    print (img.shape) 
    return img 

def calcula_label(letter): 
    aux_label=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"] 
    label= np.zeros([1,36]) 
    cont=0 
    for let in aux_label: 
     if let==letter: 
      label[0,cont]=1 
     else: 
      label[0,cont]=0 
     cont=cont+1 
    return label 

def cria_array_labels(aux_folder): 
    cont=0 
    lab=np.empty([1,36]) 
    for letter in os.listdir(aux_folder): 
     lab_temp=calcula_label(letter) 
     folder=aux_folder+letter+"/" 
     for imagem in os.listdir(folder): 
      lab=np.vstack((lab,lab_temp)) 
      cont=cont+1 
      print (cont) 
    print (lab.shape) 
    return lab 


def convert_to(images, labels, name): 
    #identifica quantidade de imagens e labels 
    num_examples = labels.shape[0] 
    if images.shape[0] != num_examples: 
    raise ValueError("Images size %d does not match label size %d." % 
        (images.shape[0], num_examples)) 
    #pega parametros da imagem 
    rows = images.shape[1] 
    cols = images.shape[2] 
    depth = 1 

    #cria nome do arquivo de saida-acho que todas as imagens vao ser escritas aqui 
    filename = os.path.join(FLAGS.directory, name + '.tfrecords') 
    print('Writing', filename) 
    writer = tf.python_io.TFRecordWriter(filename) 
    #faz um loop para cada uma das imagens 
    for index in range(num_examples): 
    #converte a imagem para string 
    image_raw = images[index].tostring() 
    labels_raw = labels[index].tostring() 
    #aloca no exemplo as dimensoes da img, o label e a imagem convertida 
    example = tf.train.Example(features=tf.train.Features(feature={ 
     'height': _int64_feature(rows), 
     'width': _int64_feature(cols), 
     'depth': _int64_feature(depth), 
     'label': _bytes_feature(labels_raw), 
     'image_raw': _bytes_feature(image_raw)})) 
    #escreve o exemplo 
    writer.write(example.SerializeToString()) 
    writer.close() 

def main(argv): 
    #Train 
    aux_folder="/root/captchas/captchas_lft/" 
    img_treino=le_imagens(aux_folder) 
    lab_treino=cria_array_labels(aux_folder) 
    print ("Base de Treino Preparada") 

    #Cross Validation 
    aux_folder="/root/captchas/captchas_lfcv/" 
    img_cv=le_imagens(aux_folder) 
    lab_cv=cria_array_labels(aux_folder) 
    print ("Base de CV Preparada") 

    #Test Set 
    aux_folder="/root/captchas/captchas_lfts/" 
    img_ts=le_imagens(aux_folder) 
    lab_ts=cria_array_labels(aux_folder) 
    print ("Base de Teste Preparada") 

    convert_to(img_treino, lab_treino, 'train') 
    convert_to(img_cv, lab_cv, 'validation') 
    convert_to(img_ts, lab_ts, 'test') 

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

而且我餵了以下網絡(這是MNIST2 Tensorflow教程的改編):

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

import os.path 
import time 

import numpy as np 
import tensorflow as tf 

from tensorflow.examples.tutorials.mnist import mnist 

# Basic model parameters as external flags. 
flags = tf.app.flags 
FLAGS = flags.FLAGS 
flags.DEFINE_integer('num_epochs', 2, 'Number of epochs to run trainer.') 
flags.DEFINE_integer('batch_size', 100, 'Batch size.') 
flags.DEFINE_string('train_dir', '/root/data', 'Directory with the training data.') 
#flags.DEFINE_string('train_dir', '/root/data2', 'Directory with the training data.') 

# Constants used for dealing with the files, matches convert_to_records. 
TRAIN_FILE = 'train.tfrecords' 
VALIDATION_FILE = 'validation.tfrecords' 


# Set-up dos pacotes 
sess = tf.InteractiveSession() 

def read_and_decode(filename_queue): 
    reader = tf.TFRecordReader() 
    _, serialized_example = reader.read(filename_queue) 
    features = tf.parse_single_example(
     serialized_example, 
     dense_keys=['image_raw', 'label'], 
     # Defaults are not specified since both keys are required. 
     dense_types=[tf.string, tf.string]) 
    # Convert from a scalar string tensor (whose single string has 
    # length mnist.IMAGE_PIXELS) to a uint8 tensor with shape 
    # [mnist.IMAGE_PIXELS]. 

    image = tf.decode_raw(features['image_raw'], tf.uint8) 
    image.set_shape([784]) 
    #print (mnist.IMAGE_PIXELS) 

    # OPTIONAL: Could reshape into a 28x28 image and apply distortions 
    # here. Since we are not applying any distortions in this 
    # example, and the next step expects the image to be flattened 
    # into a vector, we don't bother. 

    # Convert from [0, 255] -> [-0.5, 0.5] floats. 
    image = tf.cast(image, tf.float32) * (1./255) - 0.5 

    # Convert label from a scalar uint8 tensor to an int32 scalar. 
    label = tf.cast(features['label'], tf.float32) 
    #print (label) 
    #label.set_shape([1]) 
    #print (label) 
    return image, label 


def inputs(train, batch_size, num_epochs): 
    """Reads input data num_epochs times. 
    Args: 
    train: Selects between the training (True) and validation (False) data. 
    batch_size: Number of examples per returned batch. 
    num_epochs: Number of times to read the input data, or 0/None to 
     train forever. 
    Returns: 
    A tuple (images, labels), where: 
    * images is a float tensor with shape [batch_size, 30,26,1] 
     in the range [-0.5, 0.5]. 
    * labels is an int32 tensor with shape [batch_size] with the true label, 
     a number in the range [0, char letras). 
    Note that an tf.train.QueueRunner is added to the graph, which 
    must be run using e.g. tf.train.start_queue_runners(). 
    """ 
    if not num_epochs: num_epochs = None 
    filename = os.path.join(FLAGS.train_dir, 
          TRAIN_FILE if train else VALIDATION_FILE) 

    with tf.name_scope('input'): 
    filename_queue = tf.train.string_input_producer(
     [filename], num_epochs=num_epochs) 

    # Even when reading in multiple threads, share the filename 
    # queue. 
    image, label = read_and_decode(filename_queue) 

    # Shuffle the examples and collect them into batch_size batches. 
    # (Internally uses a RandomShuffleQueue.) 
    # We run this in two threads to avoid being a bottleneck. 
    images, sparse_labels = tf.train.shuffle_batch(
     [image, label], batch_size=batch_size, num_threads=2, 
     capacity=1000 + 3 * batch_size, 
     # Ensures a minimum amount of shuffling of examples. 
     min_after_dequeue=1000) 

    return images, sparse_labels 

def weight_variable(shape): 
    initial = tf.truncated_normal(shape, stddev=0.1) 
    return tf.Variable(initial) 

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') 

#Variaveis 
x, y_ = inputs(train=True, batch_size=FLAGS.batch_size, num_epochs=FLAGS.num_epochs) 
#y_ = tf.string_to_number(y_, out_type=tf.int32) 
teste=tf.convert_to_tensor(y_) 

#Layer 1 
W_conv1 = weight_variable([5, 5, 1, 32]) 
b_conv1 = bias_variable([32]) 
x_image = tf.reshape(x, [-1,28,28,1]) 
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 
h_pool1 = max_pool_2x2(h_conv1) 

#Layer 2 
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) 

#Densely Connected Layer 
W_fc1 = weight_variable([7 * 7 * 64, 1024]) 
b_fc1 = bias_variable([1024]) 
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 

#Dropout - reduz overfitting 
keep_prob = tf.placeholder(tf.float32) 
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 

#Readout layer 
W_fc2 = weight_variable([1024, 36]) 
b_fc2 = bias_variable([36]) 
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 
#y_conv=tf.cast(y_conv, tf.int32) 

#Train and evaluate 
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) 
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) 
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
sess.run(tf.initialize_all_variables()) 

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

for i in range(20000): 
    if i%100 == 0: 
    train_accuracy = accuracy.eval(feed_dict={keep_prob: 1.0}) 
    print("step %d, training accuracy %g"%(i, train_accuracy)) 
    train_step.run(feed_dict={keep_prob: 0.5}) 

x, y_ = inputs(train=True, batch_size=2000) 
#y_ = tf.string_to_number(y_, out_type=tf.int32) 
print("test accuracy %g"%accuracy.eval(feed_dict={keep_prob: 1.0})) 

coord.join(threads) 
sess.close() 

但磨片涉及到

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) 

出現以下錯誤:

ValueError: Incompatible shapes for broadcasting: TensorShape([Dimension(100)]) and TensorShape([Dimension(100), Dimension(36)]) 

我認爲問題是de label張量,但我不知道如何解決它以便具有(None,36)維度。有誰知道如何解決這個問題?

感謝 馬塞洛

回答

0

,使這項工作的最簡單方法是使用tf.one_hot()一熱編碼來代替y_

onehot_y_ = tf.one_hot(y_, 36, dtype=tf.float32) 

cross_entropy = tf.reduce_mean(-tf.reduce_sum(onehot_y_ * tf.log(y_conv), 
           reduction_indices=[1])) 

另一種方法是切換到使用專門的運算tf.nn.sparse_softmax_cross_entropy_with_logits() ,這是更高效,更穩定的數字。要使用它,你就必須刪除調用tf.nn.softmax()y_conv定義:

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 

cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(y_conv, y_)) 
+0

這聽起來像你可能會使用舊版本TensorFlow的。這兩家運營商都在最新版本(0.9)中提供。 – mrry

+0

嗨!謝謝回答! 這兩種方法返回種類相同的錯誤消息的: 1) 回溯(最近最後調用): 文件 「4_Treino_Rede_Neural.py」,線路147,在 onehot_y_ = tf.one_hot(Y_,36,D型= TF .float32) AttributeError的: '模塊' 對象沒有屬性 'one_hot' 2) 回溯(最近最後調用): 文件 「4_Treino_Rede_Neural.py」,線路153,在 cross_entropy = tf.reduce_mean(TF。 nn.sparse_softmax_cross_entropy_with_logits(y_conv,y_)) AttributeError:'模塊'對象沒有屬性'sparse_softmax_cross_entropy_with_logits' 可以嗎被修復? –

+0

更新,因爲我們說:) –

相關問題