tensorflow logits and labels must be same size

2024/10/12 14:17:11

I'm quite new to tensorflow and python, and currently trying to modify the MNIST for expert tutorial for a 240x320x3 image. I have 2 .py script

tfrecord_reeader.py

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as pltdata_path = 'train.tfrecords'  # address to save the hdf5 filedef 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 queuefilename_queue = tf.train.string_input_producer([data_path], num_epochs=1)# Define a reader and read the next recordreader = tf.TFRecordReader()_, serialized_example = reader.read(filename_queue)# Decode the record read by the readerfeatures = tf.parse_single_example(serialized_example, features=feature)# Convert the image data from string back to the numbersimage = tf.decode_raw(features['train/image'], tf.float32)# Cast label data into int32label = tf.cast(features['train/label'], tf.int32)# Reshape image data into the original shapeimage = tf.reshape(image, [240, 320, 3])sess.close()return image, labeldef 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 timeIMAGE_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 trainingx = tf.placeholder(tf.float32, [None, IMAGE_SIZE])    # 240*320=76800W = tf.Variable(tf.zeros([IMAGE_SIZE, NUM_CLASSES]))b = tf.Variable(tf.zeros([NUM_CLASSES]))y = tf.matmul(x, W) + b# Define loss and optimizery_ = tf.placeholder(tf.float32, [None, NUM_CLASSES])  # Desired output# First convolutional layerW_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 layerW_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 layerW_fc1 = weight_variable([60 * 80 * 64, 1024])b_fc1 = bias_variable([1024])# Flatten the layerh_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 layerkeep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)# Second fully connected layerW_fc2 = weight_variable([1024, NUM_CLASSES])b_fc2 = bias_variable([NUM_CLASSES])# Output layery_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2# print(y_conv.shape)# print(y_conv.get_shape)# Get the losscross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))# Minimize the losstrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)# Read all data from tfrecord fileimageList, 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)

When I run the program, I'm getting

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

I've done several hours of search on this problem, but could not see why the logits are not matching label size. If I change batchsize to 10, the labels size will become [2,5] as if it's always being divided by 5. Can someone help me out here?

Answer

Most likely your labels are single integer values rather than one-hot vectors, so your labelBatch is a vector of size [50] containing single numbers like "1" or "4". Now, when you reshape them using train_labels = np.reshape(train_labels, (-1, NUM_CLASSES)) you're changing the shape to [10, 5].

The tf.nn.softmax_cross_entropy_with_logits function expects labels to be "one-hot" encodings of the labels (this means that a label of 3 translates into a vector of size 5 with a 1 in position 3 and zeros elsewhere). You can achieve this using the tf.nn.one_hot function, but an easier way to do it is instead to use the tf.nn.sparse_softmax_cross_entropy_with_logits function which is designed to work with these single-valued labels. To achieve this, you'll need to change these line:

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

And get rid of the train_labels = np.reshape(train_labels, (-1, NUM_CLASSES)) line.

(By the way, you don't actually need to use placeholders when reading data in this way - you can just directly use the output tensors.)

https://en.xdnf.cn/q/118193.html

Related Q&A

How to call an action when a button is clicked in Tkinter

I am experimenting with Tkinter for the first time, and am trying to call a function when a button is clicked. This is part of my code. mt is referring to a label that I have made dynamic by attachin…

Access range of elements from an array Python

Considering the following dataset:>>> data[:10] array([(T, 2, 8, 3, 5, 1, 8, 13, 0, 6, 6, 10, 8, 0, 8, 0, 8),(I, 5, 12, 3, 7, 2, 10, 5, 5, 4, 13, 3, 9, 2, 8, 4, 10),(D, 4, 11, …

Python - Remove extended ascii

Okay, so I am new to the whole python world so bear with me. Background: We are trying to offload logs into mongo to be able to query and search for them quicker. The device already prints them in a de…

Selenium - Python - Select dropdown meun option - No ID or Name

I am trying to select and element in a dropdown menu:The HTML is:<div class="col-lg-6"><select data-bind="options: indicator_type_list,value: indicatorType,optionsCaption: Choos…

How to prevent triples from getting mixed up while uploading to Dydra programmatically?

I am trying to upload some data to Dydra from a Sesame triplestore I have on my computer. While the download from Sesame works fine, the triples get mixed up (the s-p-o relationships change as the obje…

Adding a new row to a dataframe in pandas for every iteration

Adding a new row to a dataframe with correct mapping in pandasSomething similar to the above question.carrier_plan_identifier ... hios_issuer_identifier 1 AU…

Twisted client protocol - attaching an interface frontend

I am following the tutorial on writing a client/server pair in Twisted located here:http://twistedmatrix.com/documents/current/core/howto/clients.htmlI have everything working for the communication of …

Get query string as function parameters on flask

Is there a way to get query string as function parameters on flask? For example, the request will be like this.http://localhost:5000/user?age=15&gender=MaleAnd hope the code similar to this.@app.…

cython.parallel cannot see the difference in speed

I tried to use cython.parallel prange. I can only see two cores 50% being used. How can I make use of all the cores. i.e. send the loops to the cores simultaneously sharing the arrays, volume and mc_vo…

Is it possible (how) to add a spot color to pdf from matplotlib?

I am creating a chart which has to use (multiple) spot colors. This color could be one that is neither accessible from RGB nor CMYK. Is there a possibility to specify a spot color for a line in matplot…