TensorFlow-重新学习第2天

线性回归

见注释

#! -*- coding: utf-8 -*-
import tensorflow.compat.v1 as tf
import time

# 设置GPU和Session
gpu_options = tf.GPUOptions(allow_growth=True)
sess_config = tf.ConfigProto(
        log_device_placement=False,
        allow_soft_placement=False,
        gpu_options=gpu_options)

# 生成数据
# 目标是拟合y = 2x这个函数
import numpy as np
train_x = np.linspace(-1, 1, num=50)
train_y = 2 * train_x + np.random.randn(*train_x.shape) * 0.3

# 可视化数据
import matplotlib.pyplot as plt
plt.plot(train_x, train_y, 'ro', label='origin data')
plt.legend()
plt.show(block=False)

# 构建模型
# # 模型参数,变量
W = tf.Variable(initial_value=tf.random.normal(shape=[1]), dtype=tf.float32)
b = tf.Variable(initial_value=tf.zeros(shape=[1]), dtype=tf.float32)
tf.summary.histogram('weights', W)
tf.summary.histogram('biases', b)

# # 模型输入占位符
input_x = tf.placeholder(dtype=tf.float32)
input_y = tf.placeholder(dtype=tf.float32)

# # 模型
z = tf.multiply(input_x, W) + b
tf.summary.histogram('z', z)

# 损失函数
cost = tf.reduce_mean(tf.square(z - input_y))
tf.summary.scalar('loss_function', cost)

# 优化函数
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

# 训练模型迭代次数
train_epochs = 50

# 训练细节显示频率
display_steps = 1

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

# Saver
saver = tf.train.Saver()
save_dir = 'models/'

merged_summary_op = tf.summary.merge_all()

with tf.Session(config=sess_config) as sess:
    sess.run(init_op)
    summary_writer = tf.summary.FileWriter('logs/liner_with_summary', sess.graph)

    for epoch in range(0, train_epochs):
        for x, y in zip(train_x, train_y):
            sess.run(optimizer, feed_dict={ input_x: x, input_y: y})
        
        summary_str = sess.run(merged_summary_op, feed_dict={input_x: train_x, input_y: train_y})
        summary_writer.add_summary(summary_str, epoch)
        
        # 显示训练中的详细信息
        if epoch % display_steps == 0:
            loss = sess.run(cost, feed_dict={ input_x: train_x, input_y: train_y})
            print('Epoch: {}, cost: {}, W: {}, b: {}'.format(epoch + 1, loss, W.eval(), b.eval()))

        # 保存模型
        saver.save(sess, save_dir + "linermodel.cpkt", global_step=epoch)

    print('Finished')
    print('Epoch: {}, cost: {}, W: {}, b: {}'.format(epoch + 1, loss, W.eval(), b.eval()))

TensorBoard

  1. 损失
    TensorFlow-重新学习第2天_第1张图片

  2. TensorFlow-重新学习第2天_第2张图片
  3. 参数
    TensorFlow-重新学习第2天_第3张图片
  4. 直方图
    TensorFlow-重新学习第2天_第4张图片

你可能感兴趣的:(深度学习-框架,TensorFLow)