python 3.x - functions - Logits y etiquetas no coinciden en Tensorflow
tensorflow cost functions (1)
hay una falta de coincidencia entre los logits y los lables en Tensorflow después de una codificación en caliente. Y el tamaño de mi lote es 256. ¿Cómo puedo obtener el tamaño del lote en las etiquetas Tensor también? Supongo que este problema está relacionado con LabelEncoder y One-Hot Codder. Cualquier ayuda es apreciable.
Por favor encuentre el código a continuación.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = tf.one_hot(le.fit_transform(labels), n_classes)))
optimizer = tf.train.GradientDescentOptimizer(learning_rate = learn_rate).minimize(cost)
correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(tf.one_hot(le.fit_transform(labels), n_classes),1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
batchSize = 256
epochs = 20 # 200epoch+.5lr = 99.6
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
total_batches = batches(batchSize, train_features, train_labels)
for epoch in range(epochs):
for batch_features, batch_labels in total_batches:
train_data = {features: batch_features, labels : batch_labels, keep_prob : 0.5}
sess.run(optimizer, feed_dict = train_data)
# Print status for every 100 epochs
if epoch % 10 == 0:
valid_accuracy = sess.run(
accuracy,
feed_dict={
features: val_features,
labels: val_labels,
keep_prob : 0.5})
print(''Epoch {:<3} - Validation Accuracy: {}''.format(
epoch,
valid_accuracy))
Accuracy = sess.run(accuracy, feed_dict={features : test_features, labels :test_labels, keep_prob : 1.0})
# Save the model
saver.save(sess, save_file)
print(''Trained Model Saved.'')
prediction=tf.argmax(logits,1)
output_array = le.inverse_transform(prediction.eval(feed_dict={features : test_features, keep_prob: 1.0}))
prediction = np.reshape(prediction, (test_features.shape[0],1))
np.savetxt("prediction.csv", prediction, delimiter=",")
Y recibo el Error de argumento inválido como se indica a continuación.
InvalidArgumentError: logits and labels must be same size: logits_size=[256,1161] labels_size=[1,1161]
[[Node: SoftmaxCrossEntropyWithLogits = SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](Reshape, Reshape_1)]]
Caused by op ''SoftmaxCrossEntropyWithLogits'', defined at:
File "C:/Anaconda/envs/gpu/lib/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:/Anaconda/envs/gpu/lib/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:/Anaconda/envs/gpu/lib/site-packages/ipykernel/__main__.py", line 3, in <module>
app.launch_new_instance()
File "C:/Anaconda/envs/gpu/lib/site-packages/traitlets/config/application.py", line 658, in launch_instance
app.start()
File "C:/Anaconda/envs/gpu/lib/site-packages/ipykernel/kernelapp.py", line 477, in start
ioloop.IOLoop.instance().start()
File "C:/Anaconda/envs/gpu/lib/site-packages/zmq/eventloop/ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "C:/Anaconda/envs/gpu/lib/site-packages/tornado/ioloop.py", line 888, in start
handler_func(fd_obj, events)
File "C:/Anaconda/envs/gpu/lib/site-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "C:/Anaconda/envs/gpu/lib/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "C:/Anaconda/envs/gpu/lib/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "C:/Anaconda/envs/gpu/lib/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "C:/Anaconda/envs/gpu/lib/site-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "C:/Anaconda/envs/gpu/lib/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "C:/Anaconda/envs/gpu/lib/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
handler(stream, idents, msg)
File "C:/Anaconda/envs/gpu/lib/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
user_expressions, allow_stdin)
File "C:/Anaconda/envs/gpu/lib/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "C:/Anaconda/envs/gpu/lib/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "C:/Anaconda/envs/gpu/lib/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "C:/Anaconda/envs/gpu/lib/site-packages/IPython/core/interactiveshell.py", line 2802, in run_ast_nodes
if self.run_code(code, result):
File "C:/Anaconda/envs/gpu/lib/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-9a6fe2134e3e>", line 52, in <module>
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = logits, labels = tf.one_hot(le.fit_transform(labels), n_classes)))
File "C:/Anaconda/envs/gpu/lib/site-packages/tensorflow/python/ops/nn_ops.py", line 1594, in softmax_cross_entropy_with_logits
precise_logits, labels, name=name)
File "C:/Anaconda/envs/gpu/lib/site-packages/tensorflow/python/ops/gen_nn_ops.py", line 2380, in _softmax_cross_entropy_with_logits
features=features, labels=labels, name=name)
File "C:/Anaconda/envs/gpu/lib/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
op_def=op_def)
File "C:/Anaconda/envs/gpu/lib/site-packages/tensorflow/python/framework/ops.py", line 2506, in create_op
original_op=self._default_original_op, op_def=op_def)
File "C:/Anaconda/envs/gpu/lib/site-packages/tensorflow/python/framework/ops.py", line 1269, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): logits and labels must be same size: logits_size=[256,1161] labels_size=[1,1161]
[[Node: SoftmaxCrossEntropyWithLogits = SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](Reshape, Reshape_1)]]
El problema fue con tf.one_hot (le.fit_transform (labels), n_classes).
Esto pasa un tensor donde se necesitaba la matriz numpy. Después de llamar a eval () para este Tensor, el problema se resuelve.