如何在TensorFlow神经网络中获取并显示损失值?
Hey there! It looks like you're building a simple 2-layer neural network for MNIST but got stuck on displaying the loss value, plus your code is cut off mid-way. Let's fix this step by step.
Step 1: Complete the Core Network & Loss Definition
First, let's fill in the missing parts of your code—starting with the placeholders, weight/bias variables, network layers, and crucially, the loss function.
Here's the full, completed code with comments explaining each part:
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Load MNIST data mnist = input_data.read_data_sets("MNIST_data", one_hot=True) x_input = mnist.train.images[:100,:] # Using only 100 samples for quick testing y_input = mnist.train.labels[:100,:] # Hyperparameters LearningRate = 0.01 noOfEpocs = 10 # Network parameters hidden_1_Neurons = 50 hidden_2_Neurons = 50 inputNeurons = 784 noOfClasses = 10 # --- Missing placeholders added --- X = tf.placeholder(tf.float32, shape=[None, inputNeurons]) Y = tf.placeholder(tf.float32, shape=[None, noOfClasses]) # --- Weight and bias variables --- def create_weights(shape): return tf.Variable(tf.random_normal(shape, stddev=0.01)) def create_biases(shape): return tf.Variable(tf.random_normal(shape)) # Layer 1 w1 = create_weights([inputNeurons, hidden_1_Neurons]) b1 = create_biases([hidden_1_Neurons]) layer1 = tf.nn.relu(tf.matmul(X, w1) + b1) # Layer 2 w2 = create_weights([hidden_1_Neurons, hidden_2_Neurons]) b2 = create_biases([hidden_2_Neurons]) layer2 = tf.nn.relu(tf.matmul(layer1, w2) + b2) # Output layer w_out = create_weights([hidden_2_Neurons, noOfClasses]) b_out = create_biases([noOfClasses]) logits = tf.matmul(layer2, w_out) + b_out # --- Loss function definition --- # Using softmax cross entropy for classification loss loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=Y)) # Optimizer to minimize loss optimizer = tf.train.GradientDescentOptimizer(LearningRate).minimize(loss) # Initialize all variables init = tf.global_variables_initializer()
Step 2: Add Logic to Track & Print Loss
The key part you're missing is running the loss tensor in your training loop and printing its value. Here's how to add the training loop with loss display:
# Start TensorFlow session with tf.Session() as sess: sess.run(init) for epoch in range(noOfEpocs): # Run optimizer and calculate loss in one step _, current_loss = sess.run([optimizer, loss], feed_dict={X: x_input, Y: y_input}) # Print loss after each epoch print(f"Epoch {epoch+1}/{noOfEpocs}, Loss: {current_loss:.4f}") # Optional: Test accuracy after training correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) print(f"\nTraining Accuracy: {sess.run(accuracy, feed_dict={X: x_input, Y: y_input}):.4f}")
Key Notes for Loss Display
- Run the loss tensor: You need to include
lossin the list of tensors you run withsess.run()—this returns the current loss value you can print. - Feed the data: Always pass your input and label data via
feed_dictwhen running the optimizer or loss. - Formatting: Using
:.4frounds the loss to 4 decimal places for readability.
If you were seeing issues like no loss output, it's likely because you weren't explicitly fetching the loss tensor during training. This code should fix that and show you the loss decreasing each epoch (since we're training on the same small dataset, the loss will drop quickly).
内容的提问来源于stack exchange,提问作者Whoami

