Python 如何将变量添加到tf.trainable_变量中?

Python 如何将变量添加到tf.trainable_变量中?,python,tensorflow,Python,Tensorflow,我读了这篇关于如何用TensorFlow快速构建神经网络的文章,效果非常好 但是,我想更多地了解它是如何工作的 在代码中,我们使用以下公式定义神经网络: def neural_network_model(data): hidden_1_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl0, n_nodes_hl1])), 'biases':tf.Variable(tf.rand

我读了这篇关于如何用TensorFlow快速构建神经网络的文章,效果非常好

但是,我想更多地了解它是如何工作的

在代码中,我们使用以下公式定义神经网络:

def neural_network_model(data):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl0, n_nodes_hl1])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}

    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}

    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}

    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
                    'biases':tf.Variable(tf.random_normal([n_classes]))}

    l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']), hidden_1_layer['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']), hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']), hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3,output_layer['weights']) + output_layer['biases']

    return output
然后最终逃跑

cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
optimizer = tf.train.AdamOptimizer().minimize(cost)
我想弄清楚AdamOptimizer是如何知道要更改哪些矩阵的,因为它们都没有传递到最小化函数中

因此,我查找发现
minimize
有一个可选参数:

var_list: Optional list or tuple of Variable objects to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES.
于是我抬头一看,发现:

When passed trainable=True, the Variable() constructor automatically adds new variables to the graph collection GraphKeys.TRAINABLE_VARIABLES. This convenience function returns the contents of that collection.
因此,我在代码中搜索了术语
trainable
,但什么也没找到


那么AdamOptimizer究竟是如何知道它应该更改什么以进行优化的呢?

可训练的
参数传递给
变量
构造函数,并隐式默认为true。在代码中将其设置为false,以避免对某些变量进行训练