Skip to main content
 首页 » 编程设计

python之tensorflow session.run() 的参数之你是否传递操作

2025年05月04日21think

我正在关注这个 tutorial for tensorflow :

我正在尝试理解 tf.session.run() 的参数。我知道您必须在 session 中的图形中运行操作。

传入train_step是因为它封装了这个特定例子中网络的所有操作吗?我试图理解为什么我不需要将任何其他变量传递给 session ,例如 cross_entropy。

sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) 

完整代码如下:

from tensorflow.examples.tutorials.mnist import input_data 
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 
 
import tensorflow as tf 
 
x = tf.placeholder(tf.float32, [None, 784]) 
 
W = tf.Variable(tf.zeros([784, 10])) 
 
b = tf.Variable(tf.zeros([10])) 
 
y = tf.nn.softmax(tf.matmul(x, W) + b) 
 
y_ = tf.placeholder(tf.float32, [None, 10]) 
 
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) 
 
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) 
 
sess = tf.InteractiveSession() 
 
tf.global_variables_initializer().run() 
 
for _ in range(10): 
    batch_xs, batch_ys = mnist.train.next_batch(100) 
 
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) 
 
    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) 
 
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
 
    print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) 

请您参考如下方法:

在 TensorFlow session tf.Session 中,您想运行(或执行)优化器操作(在本例中为 train_step)。优化器最小化您的损失函数(在本例中为 cross_entropy),这是使用模型假设 y 评估或计算的。

在级联方法中,cross_entropy 损失函数最小化了计算y 时的误差,因此它找到了权重的最佳值W 当与 x 结合时,可以准确地近似于 y。

因此,使用 TensorFlow session 对象 tf.Session 作为 sess 我们运行优化器 train_step,然后它会评估整个计算图。

sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) 

因为级联方法最终会调用 cross_entropy,它使用了占位符 x 和 y,所以您必须使用 feed_dict 将数据传递给这些占位符。