tensorflow实现两层神经网络,并打印中间参数变化

1.主要思考的是如何打印tensorflow跑程序过程中的w和b的变化过程,有三种思路:

        * 思路一.使用图像化(tensorboard)显示,但是效果不好,不对劲

        *思路二.使用tf.saver去间隔匹配的保存,保存到不同文件中去,最后再从保存的文件中进行读取,有点麻烦,但是也能实现。

        *思路三.最后发现直接返回run就可以了, 返回了很多数组。

2.直接使用第三种思路,其中可视化的方法是:

        *命令行下cd 到项目目录

        *命令行:tensorboard --logdir log

   如果可视化显示有重叠,是因为log目录下有多个文件。

# coding=gbk

import tensorflow as tf
import numpy as np
import os

'''
思路一.使用图像化(tensorboard)显示,但是效果不好,不对劲
思路二.使用tf.saver去间隔匹配的保存,保存到不同文件中去,最后再从保存的文件中进行读取,有点麻烦,但是也能实现。
思路三.最后发现直接返回run就可以了, 返回了很多数组

可视化方式:  命令行下cd 到项目目录
            命令行:tensorboard --logdir log

如果显示重叠,是因为log目录下有多个文件。
'''


def add_layer(inputs, in_size, out_size, activation_function=None):
    with tf.variable_scope('Weights') as scope:
        Weights = tf.Variable(tf.random_normal([in_size, out_size]))
        tf.summary.histogram('/Weights', Weights)
    with tf.variable_scope('bias') as scope:
        biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
        tf.summary.histogram('/biase', biases)
    with tf.variable_scope('matmul') as scope:
        Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs, Weights, biases


def model_strucre(xs):
    l1, weight1, bias1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
    prediction, weight2, bias2 = add_layer(l1, 10, 1, activation_function=None)
    return prediction, weight1, weight2, bias1, bias2


def train_and_save():
    x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]
    noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
    y_data = np.square(x_data) - 0.5 + noise

    xs = tf.placeholder(tf.float32, [None, 1])
    ys = tf.placeholder(tf.float32, [None, 1])

    prediction, weight1, weight2, bias1, bias2 = model_strucre(xs)

    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
    with tf.name_scope('loss'):
        # 图形化展示loss的变化,在tensorboard中查看
        tf.summary.scalar('loss', loss)
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    merged = tf.summary.merge_all()
    init = tf.global_variables_initializer()
    sess = tf.Session()
    # 设置summary总结形式的保存,用于图形化
    log_dir = os.getcwd()
    save_path = os.getcwd()
    sess.run(init)
    test_writer = tf.summary.FileWriter(log_dir + '/log', tf.get_default_graph())
    saver = tf.train.Saver()
    for i in range(1001):
        print('#############################' + '   第' + str(i) + '次迭代    ' + '####################################')
        summary, _ = sess.run([merged, train_step], feed_dict={xs: x_data, ys: y_data})
        test_writer.add_summary(summary, i)
        print('第', str(i), '次的w1值为:', sess.run(weight1))
        print('第', str(i), '次的b1值为:', sess.run(bias1))
        print('第', str(i), '次的w2值为:', sess.run(weight2))
        print('第', str(i), '次的b2值为:', sess.run(bias2))
        if i % 50 == 0:
            print('loss 值为:', sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
            saver.save(sess, save_path + '/save_file/train_model' + str(i) + '.ckpt')
    test_writer.close()


def read_params():
    '''
    读取保存文件中的model,从中读取w和b参数,这是可使用的第二个方式  ,首先要指定好要恢复的结构
    :return:
    '''
    # 读取存放的model,把参数获取下来。
    xs = tf.placeholder(tf.float32, [None, 1])
    prediction, weight1, weight2, bias1, bias2 = model_strucre(xs)
    saver = tf.train.Saver()
    i = 750  # 指定批次数
    with tf.Session() as sess:
        saver.restore(sess, os.getcwd() + '/save_file/train_model' + str(i) + '.ckpt')
        print(sess.run(weight1))
    return 0


if __name__ == '__main__':
    train_and_save()

效果如下,可以发现记录了每次迭代时,权重w和偏置b的变化过程

猜你喜欢

转载自blog.csdn.net/maqunfi/article/details/84502694