TensorFlow输出某一层的具体数值

TensorFlow输出某一层的具体数值_第1张图片

直接看代码,更容易理解

import tensorflow as tf
import numpy as np

graph = tf.Graph()

with graph.as_default():
    x = tf.placeholder(dtype=tf.float32, shape=[None, 50], name='x_input')
    y = tf.placeholder(dtype=tf.float32, shape=[None, 50], name='y_label')

    x_val = np.arange(-25., 25., 1., dtype=np.float32).reshape([1, 50])
    y_val = np.square(x_val)

    with tf.variable_scope('net', reuse=tf.AUTO_REUSE):
        l1 = tf.layers.dense(x, 100, activation=tf.nn.relu, name='layer1')
        l2 = tf.layers.dense(l1, 100, activation=tf.nn.relu, name='layer2')
        out = tf.layers.dense(l2, 50, name='output')

    loss = tf.losses.mean_squared_error(y, out)
    optimizer = tf.train.AdamOptimizer(0.001)
    train_op = optimizer.minimize(loss)

    init = tf.global_variables_initializer()

    with tf.Session(graph=graph) as sess:
        writer = tf.summary.FileWriter('./simple_saved_graph', sess.graph)
        sess.run(init)
        for i in range(200):
            l, _ = sess.run([loss, train_op], feed_dict={x: x_val, y: y_val})
        
        # calculate the output value after training
        out_val = sess.run(out, feed_dict={x: x_val})    # after training, the output value, use the defined operator name
        print(out_val)
        # use function to find the output operator
        out_tensor= sess.graph.get_operation_byname('net/output/BiasAdd').outputs[0]
        out_t = sess.run(out_tensor, feed_dict={x: x_val})
        if np.array_equal(out_val, p):
        print('Yes, out_val is equal to p')   # Yes, out_val is equal to p
    # get the output of layer2 value
        l2_val = sess.run(l2, feed_dict={x: x_val})
        # use the function find the output of layer2
        l2_tensor = sess.graph.get_operation_by_name('net/layer2/Relu').outputs[0]
        l2_value = sess.run(l2_tensor, feed_dict={x: x_val})
        if np.arrayequal(l2_val, l2_value):     
        print('Yes, l2_val, is equal to l2_value')  # Yes, l2_val, is equal to l2_value

反复看最后几个类似的输出net中间各层具体值的写法,应该就发现书写规律了。即首先建立一个session,这个不必多说。

接着用session.run(net中希望输出的参数名称,给net灌入训练数据用fee_dict{})。

 

参考https://zhidao.baidu.com/question/1964775659871815340.html

https://zhuanlan.zhihu.com/p/55928459 

 

你可能感兴趣的:(TensorFlow)