# coding=utf-8
from __future__ import print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
os.environ[‘TF_CPP_MIN_LOG_LEVEL‘] = ‘2‘
# ### 添加神经层
def add_layer(inputs, in_size, out_size, activation_function=None):
with tf.name_scope(‘layer‘): # 使用with tf.name_scope定义图层,并指定在可视化图层中的显示名称
with tf.name_scope(‘weights‘): # 定义图层并指定名称,注意这里是上一图层的子图层
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name=‘W‘) # 参数name指定名称
with tf.name_scope(‘biases‘): # 定义图层并指定名称
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name=‘b‘) # 参数name指定名称
with tf.name_scope(‘Wx_plus_b‘): # 定义图层并指定名称
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
# ### 构建数据
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
# ### 搭建网络
with tf.name_scope(‘inputs‘): # 定义图层并指定名称
xs = tf.placeholder(tf.float32, [None, 1], name=‘x_input‘) # 指定名称为x_input,也就是在可视化图层中的显示名称
ys = tf.placeholder(tf.float32, [None, 1], name=‘y_input‘) # 指定名称为y_input
h1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) # 隐藏层
prediction = add_layer(h1, 10, 1, activation_function=None) # 输出层
with tf.name_scope(‘loss‘): # 定义图层并指定名称
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
with tf.name_scope(‘train‘): # 定义图层并指定名称
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
sess = tf.Session()
writer = tf.summary.FileWriter("logs/", sess.graph) # 创建FileWriter对象和event文件,指定event文件的存放目录
init = tf.global_variables_initializer()
sess.run(init)
# ### 结果可视化
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show()
# ### 训练
for i in range(1001):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
result = sess.run(loss, feed_dict={xs: x_data, ys: y_data})
print("Steps:{} Loss:{}".format(i, result))
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value = sess.run(prediction, feed_dict={xs: x_data})
lines = ax.plot(x_data, prediction_value, ‘r-‘, lw=5)
plt.pause(0.2)
# ### TensorBoard
# TensorFlow自带的可视化工具:
# - 可视化学习:https://www.tensorflow.org/guide/summaries_and_tensorboard
# - 图的直观展示:https://www.tensorflow.org/guide/graph_viz;
# - 直方图信息中心:https://www.tensorflow.org/guide/tensorboard_histograms
# 能够以直观的流程图的方式,清楚展示出整个神经网络的结构和框架,便于理解模型和发现问题;
# 使用tf.name_scope()形成图层,图层名字就是方法里的参数;
#
# ### 启动TensorBoard
# 使用命令“tensorboard --logdir=path/to/log-directory”(或者“python -m tensorboard.main”);
# 参数logdir指向FileWriter将数据序列化的目录,建议在logdir上一级目录执行此命令;
# TensorBoard运行后,在浏览器输入“localhost:6006”即可查看TensorBoard;
原文:https://www.cnblogs.com/anliven/p/10424915.html