TensorFlow学习程序(三):构造一个简单的神经网络并通过Matplotlib可视化

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt #使输出数据可视化

def add_layer(inputs, in_size, out_size, activation_function = None):  #构造神经网络层
    with tf.name_scope('layer'):
        with tf.name_scope('weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]))
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)  #由于biases一般为不为0的数,所以再加上0.1
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.matmul(inputs, Weights) + biases #相当于numpy中的np.dot(inputs, Weights)
        if activation_function is None: #如果没有激活函数,则为线性运算,outputs为Wx_plus_b
            outputs = Wx_plus_b
        else: #如果有激活函数,则需对Wx_plus_b进行进一步运算从而得到outputs
            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'): #创立神经网络的x_input和y_input两个输入(inputs包括这两者)
    xs = tf.placeholder(tf.float32, [None, 1], name = 'x_input') #因为x_data的属性只有1,None的作用是指传入多少个值都可以
    ys = tf.placeholder(tf.float32, [None, 1], name = 'y_input') #因为y_data的属性只有1,None的作用是指传入多少个值都可以

#构建输入层、隐藏层(黑箱部分)、输出层,对于输入层有几个data就有几个神经元,隐藏层神经元个数自定义
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) #relu有默认名字
prediction = add_layer(l1, 10, 1, activation_function=None) #直接输出,没有激活函数
#其中xs是输入层的输入数据,prediction是输出层的输出数据,两个add_layer是隐藏层(黑箱部分)

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)

#激活定义的placeholder!
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
    init = tf.initialize_all_variables()
else:
    init = tf.global_variables_initializer()

with tf.Session() as sess:
    writer = tf.summary.FileWriter("logs/",sess.graph) #graph的作用是将前面已经构建好的框架集合起来放入“”中的文件夹
    sess.run(init)
    
    fig = plt.figure() #生成一个图片框
    ax = fig.add_subplot(1, 1, 1)
    ax.scatter(x_data, y_data) #生成标准图像
    plt.ion() #不加的话执行完plt.show()之后会暂停
    plt.show() #显示生成的标准图像
    
    lines = None
    for step in range(1000):
        sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
        #向xs与ys中传值,利用placeholder的优点是可以将x(y)_data中的任意数量的数据传入,故可以实现数据的分批输入从而提高训练效率
        if step % 50 == 0:
            print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
            prediction_picture = sess.run(prediction, feed_dict={xs: x_data}) #因为要生成预测图象,所以运行prediction,并且只向其中传入x_data
            try:
                ax.lines.remove(lines[0])
            except Exception:
                pass
            lines = ax.plot(x_data, prediction_picture, 'r-', lw=5)
            plt.pause(0.1) #输出的图像之间的间隔是0.1秒
    plt.pause(100)

	注意,其中的with tf.name_scope()的作用是生成相应代码在数据流图中的名称。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值