TensorFlow如何知道要优化哪些变量?

用户名

代码摘自:-http : //adventuresinmachinelearning.com/python-tensorflow-tutorial/

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Python optimisation variables
learning_rate = 0.5
epochs = 10
batch_size = 100

# declare the training data placeholders
# input x - for 28 x 28 pixels = 784
x = tf.placeholder(tf.float32, [None, 784])
# now declare the output data placeholder - 10 digits
y = tf.placeholder(tf.float32, [None, 10])
# now declare the weights connecting the input to the hidden layer
W1 = tf.Variable(tf.random_normal([784, 300], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([300]), name='b1')
# and the weights connecting the hidden layer to the output layer
W2 = tf.Variable(tf.random_normal([300, 10], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([10]), name='b2')
# calculate the output of the hidden layer
hidden_out = tf.add(tf.matmul(x, W1), b1)
hidden_out = tf.nn.relu(hidden_out)
# now calculate the hidden layer output - in this case, let's use a softmax activated
# output layer
y_ = tf.nn.softmax(tf.add(tf.matmul(hidden_out, W2), b2))
y_clipped = tf.clip_by_value(y_, 1e-10, 0.9999999)
cross_entropy = -tf.reduce_mean(tf.reduce_sum(y * tf.log(y_clipped)
                         + (1 - y) * tf.log(1 - y_clipped), axis=1))
# add an optimiser
optimiser = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)
# finally setup the initialisation operator
init_op = tf.global_variables_initializer()

# define an accuracy assessment operation
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# start the session
with tf.Session() as sess:
   # initialise the variables
   sess.run(init_op)
   total_batch = int(len(mnist.train.labels) / batch_size)
   for epoch in range(epochs):
        avg_cost = 0
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size=batch_size)
            _, c = sess.run([optimiser, cross_entropy], 
                         feed_dict={x: batch_x, y: batch_y})
            avg_cost += c / total_batch
        print("Epoch:", (epoch + 1), "cost =", "{:.3f}".format(avg_cost))
   print(sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}))

我想问一下,tensorflow如何识别需要优化的参数,就像上面的代码一样,我们需要优化w1,w2,b1和b2,但我们从未在任何地方指定它。我们确实要求GradientDescentOptimizer最小化cross_entropy,但我们从未告诉过它必须更改w1,w2,b1&b2的值才能这样做,那么它怎么知道cross_entropy所依赖的参数呢?

登林格

科里·内赞(Cory Nezin)的回答仅部分正确,可能导致错误的假设!

实际上您确实指定了哪些参数是优化的(=可训练的),即通过执行以下操作:

# now declare the weights connecting the input to the hidden layer
W1 = tf.Variable(tf.random_normal([784, 300], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([300]), name='b1')
# and the weights connecting the hidden layer to the output layer
W2 = tf.Variable(tf.random_normal([300, 10], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([10]), name='b2')

简而言之,TensorFlow只会更新tf.Variables如果您使用类似之类的东西tf.Variable(...,trainable=False),则无论“网络依赖于”什么,都不会获得任何更新。您仍将指定它,并且网络仍将通过该部分传播,但是您将永远不会收到该特定变量的任何更新。

Cory的回答是正确的,因为网络会自动识别要更新的值,但是您必须指定必须先定义/更新的值!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Mutex.Lock()如何知道要锁定哪些变量?

Terraform如何知道要加载哪些文件?

Tensorflow 如何知道哪些可训练变量需要最小化?

lm()如何知道哪些预测变量是分类的?

Promisify如何知道要返回哪个变量?

端口触发如何知道要打开哪些端口?

Windows如何知道重置期间要保留哪些文件

如何知道哪些变量是在try块的罪魁祸首?

哪些特定的优化标志负责优化变量

在升级过程中,rpm如何知道要删除哪些文件?

在单元测试时,您如何知道要导入哪些组件?

Web API中的更新方法:如何知道要更新哪些字段?

.net核心项目在构建时如何知道要包含哪些文件

如何知道单击了哪些Linklabel?

ValueError:没有要优化的变量

如何在不预先知道要更新哪些字段的情况下连续更新多个字段

当不从Controller类继承控制器时,asp.net mvc 6如何知道要添加哪些资源?

使用“find_package”:我如何知道必须使用哪些变量进行链接?

如何知道Jsoup删除了哪些文本?

如何知道我缺少哪些包裹?

如何知道安装了哪些PHP扩展

如何知道图中的哪些节点是可移动的

如何知道某些PID监听哪些端口?

如何知道AppIndicator提供哪些图标?

如何知道包包含哪些功能?

如何知道哪些文档属于集合

pytest-如何知道选择了哪些标记

CreateUpdateDownloader如何知道下载哪些文件?

如何知道查询中缺少哪些参数?