ValueError: Incompatible shapes for broadcasting

ValueError: Incompatible shapes for broadcasting

我是 tensorflow 的新手,我正在为所有 36 个字符(0-9 和 a-z)训练一个神经网络。

我使用 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)])

我认为问题出在 label 张量上,但我不确定如何修复它以获得 (None,36) 维度。有谁知道如何解决这个问题?

谢谢 马塞洛

完成此工作的最简单方法是使用 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(),它更高效且数值更稳定。要使用它,您必须在 y_conv:

的定义中删除对 tf.nn.softmax() 的调用
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_))