tensorflow学习笔记 -- 变量可视化和模型保存

10. 变量可视化

为了方便查看训练的效果,可以将每一步训练的变量值可视化,代码如下:

import tensorflow as tf


def regression():
    """
    用Tensorflow实现一个简单的线性回归
    我们预设一个线性函数然后通过线性回归看看能否得到这个函数对应的参数
    预设的函数:y = 0.7 * x + 0.5 (其中0.7和0.5是我们需要通过训练得到的参数,也就是最终需要的得到模型)
    """
    with tf.variable_scope("data"):
        # 1. 自己生成一些训练数据,真实项目中这些数据应该是给定的
        # 1.1 随机生成100个数作为x的训练数据
        x_true = tf.random_normal([100, 1], mean=2.0, stddev=1.5, name="x")
        # 1.2 根据x值和预设好的函数来生成100个数作为y的训练数据
        y_true = tf.matmul(x_true, [[0.7]]) + 0.5
    with tf.variable_scope("model"):
        # 2. 构建线性回归模型,由于我们已经预设了函数模型所以直接知道了模型的大概结构是由一个权重(w)和一个偏置(b)组成
        # 2.1 创建权重变量,由于权重只有一个所以生成1行1列的随机数
        weight = tf.Variable(tf.random_normal([1, 1], mean=0.0, stddev=0.1), name="w")
        # 2.2 创建偏置变量,由于偏置是相加所以不需要创建矩阵类型的数据,直接随便定义一个数即可
        bias = tf.Variable(2.0, name="b")
        # 2.3 创建模型,其实就是写一遍预设函数(实际项目中就是猜想的函数模型)
        y_predict = tf.matmul(x_true, weight) + bias
    with tf.variable_scope("loss"):
        # 3. 构建损失函数,这里取的数均方
        loss = tf.reduce_mean(tf.square(y_true - y_predict))
    with tf.variable_scope("optimizer"):
        # 4. 梯度下降优化误差,梯度下降优化器的API的唯一参数就是学习率
        train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    # 变量可视化
    # 1. 收集变量
    # 一维变量用scalar去收集
    tf.summary.scalar("losses", loss)
    # 二维以上变量用histogram去收集
    tf.summary.histogram("weights", weight)
    # 2. 合并变量
    merged_collection = tf.summary.merge_all()

    # 初始化变量
    init_op = tf.global_variables_initializer()

    with tf.Session() as sess:
        # 执行初始化变量
        sess.run(init_op)
        # 创建事件文件
        file_writer = tf.summary.FileWriter("./summary/learning/", graph=sess.graph)
        # 循环100次训练,相当于用10000个训练数据来训练
        for i in range(100):
            sess.run(train_op)
            # 运行合并后的变量
            summary = sess.run(merged_collection)
            # 将变量写入事件文件中
            file_writer.add_summary(summary, i)
            print("第%d次训练后的权重参数为:%f,偏置参数为:%f" % (i+1, weight.eval(), bias.eval()))


if __name__ == "__main__":
    regression()

加入的变量在可视化界面的表示如下:

上面是一维的变量根据训练步数的变化曲线,下面是二维以上的变量的表示:

 

11. 模型保存

当模型比较复杂是训练的步数和时间会比较长,中间可能会有外界因素导致训练终端,所以需要实时保存模型训练成果,以防需要重新训练,代码如下:

import tensorflow as tf
import os


def regression():
    """
    用Tensorflow实现一个简单的线性回归
    我们预设一个线性函数然后通过线性回归看看能否得到这个函数对应的参数
    预设的函数:y = 0.7 * x + 0.5 (其中0.7和0.5是我们需要通过训练得到的参数,也就是最终需要的得到模型)
    """
    with tf.variable_scope("data"):
        # 1. 自己生成一些训练数据,真实项目中这些数据应该是给定的
        # 1.1 随机生成100个数作为x的训练数据
        x_true = tf.random_normal([100, 1], mean=2.0, stddev=1.5, name="x")
        # 1.2 根据x值和预设好的函数来生成100个数作为y的训练数据
        y_true = tf.matmul(x_true, [[0.7]]) + 0.5
    with tf.variable_scope("model"):
        # 2. 构建线性回归模型,由于我们已经预设了函数模型所以直接知道了模型的大概结构是由一个权重(w)和一个偏置(b)组成
        # 2.1 创建权重变量,由于权重只有一个所以生成1行1列的随机数
        weight = tf.Variable(tf.random_normal([1, 1], mean=0.0, stddev=0.1), name="w")
        # 2.2 创建偏置变量,由于偏置是相加所以不需要创建矩阵类型的数据,直接随便定义一个数即可
        bias = tf.Variable(2.0, name="b")
        # 2.3 创建模型,其实就是写一遍预设函数(实际项目中就是猜想的函数模型)
        y_predict = tf.matmul(x_true, weight) + bias
    with tf.variable_scope("loss"):
        # 3. 构建损失函数,这里取的数均方
        loss = tf.reduce_mean(tf.square(y_true - y_predict))
    with tf.variable_scope("optimizer"):
        # 4. 梯度下降优化误差,梯度下降优化器的API的唯一参数就是学习率
        train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    # 变量可视化
    # 1. 收集变量
    # 一维变量用scalar去收集
    tf.summary.scalar("losses", loss)
    # 二维以上变量用histogram去收集
    tf.summary.histogram("weights", weight)
    # 2. 合并变量
    merged_collection = tf.summary.merge_all()

    # 初始化变量
    init_op = tf.global_variables_initializer()

    # 创建保存模型的实例
    saver = tf.train.Saver()

    with tf.Session() as sess:
        # 执行初始化变量
        sess.run(init_op)
        # 创建事件文件
        file_writer = tf.summary.FileWriter("./summary/learning/", graph=sess.graph)
        
        # 加载模型,覆盖随机生成的变量
        if os.path.exists("./save/checkpoint"):
            saver.restore(sess, "./save/model")

        # 循环100次训练,相当于用10000个训练数据来训练
        for i in range(100):
            sess.run(train_op)
            # 运行合并后的变量
            summary = sess.run(merged_collection)
            # 将变量写入事件文件中
            file_writer.add_summary(summary, i)
            print("第%d次训练后的权重参数为:%f,偏置参数为:%f" % (i+1, weight.eval(), bias.eval()))

            # 每50步保存一次模型变量
            if i % 50 == 0:
                saver.save(sess, "./save/model")



if __name__ == "__main__":
    regression()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值