用tensorflow创建神经网络,并输出可视化demo(莫凡)

import tensorflow.compat.v1 as tf
import numpy as np
import matplotlib.pyplot as plt

tf.disable_v2_behavior()

# 定义一个神经层
def add_layer(inputs, in_size, out_size, activatioin_function=None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))  # normal distribution是正态分布随机数
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)  # 建议biases不为0,所以加上0.1
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    # inputs的大小是1*in_size,Weight的大小是in_size*out_size,相乘后大小是1*out_size的行向量
    if activatioin_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activatioin_function(Wx_plus_b)
    return outputs


# 生成原始数据
x_data = np.linspace(-1, 1, 300)[:, np.newaxis].astype('float32')
# 在-1到1之间生成300个数的等差数列。
# [:,np.newaxis]加一个维度,使其变成300行,1列的矩阵,
# astype('float32')作为类型转换
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])  # None代表行和列不固定,1代表只有1列
ys = tf.placeholder(tf.float32, [None, 1])

# add hidden layer and output layer
l1 = add_layer(xs, 1, 10, activatioin_function=tf.nn.relu)  # 输入层一个神经元,隐藏层10个神经元
prediction = add_layer(l1, 10, 1, activatioin_function=None)  # 输出层1个神经元

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
# reduction_indices=[1]是对行方向压缩,按行求和;=[0]是对列方向压缩,按列求和
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)  # 0.1是学习率

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# 结果可视化
fig = plt.figure()  # 生成一个图片框
ax = fig.add_subplot(1, 1, 1)  # 连续性的画图需要用ax,一行一列第一个
ax.scatter(x_data, y_data)  # 以点的形式画出原始数据
plt.ion()  # 展示动态图或多个窗口,使matplotlib的显示模式转换为交互(interactive)模式。即使在脚本中遇到plt.show(),代码还是会继续执行。
plt.show()

for i in range(1500):
    # training
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})  # 用placeholder,就需要用feed_dict来定义所用到的餐宿
    if i % 50 == 0:
        try:
            ax.lines.remove(lines[0])  # 去除掉lines的第一条
        except Exception:
            pass
        prediction_value = sess.run(prediction, feed_dict={xs: x_data})
        lines = ax.plot(x_data, prediction_value, 'r-', lw=5)  # 红色的线,线的宽度为5
        plt.pause(0.2)

你可能感兴趣的:(tensorflow,神经网络,python)