AI - TensorFlow First

建造第一个神经网络

 1 # coding=utf-8
 2 import tensorflow as tf
 3 import numpy as np
 4 import matplotlib.pyplot as plt
 5 import os
 6 
 7 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 8 
 9 
10 # ### 添加神经层
11 
12 
13 def add_layer(inputs, in_size, out_size, activation_function=None):  # 构造添加神经层的函数,这里设定默认激励函数为None
14     Weights = tf.Variable(tf.random_normal([in_size, out_size]))  # 定义weights:为一个in_size行, out_size列的随机变量矩阵
15     biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)  # 定义biases:在机器学习中biases的推荐值不为0
16     Wx_plus_b = tf.matmul(inputs, Weights) + biases  # 定义Wx_plus_b:神经网络未激活的值;tf.matmul()是矩阵的乘法
17     if activation_function is None:  # 当激励函数为None时,输出当前的预测值Wx_plus_b
18         outputs = Wx_plus_b
19     else:  # 不为None时,将Wx_plus_b传到activation_function()函数得到输出
20         outputs = activation_function(Wx_plus_b)
21     return outputs  # 返回输出
22 
23 
24 # ### 构建数据
25 x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]  # 构建数据x_data
26 noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)  # 构建噪声数据noise,模拟真实情况
27 y_data = np.square(x_data) - 0.5 + noise  # 构建数据y_data
28 
29 # ### 搭建网络
30 xs = tf.placeholder(tf.float32, [None, 1])  # 利用占位符定义神经网络的输入
31 ys = tf.placeholder(tf.float32, [None, 1])  # None代表无论输入有多少都可以,1表示输入只有一个特征
32 h1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)  # 定义隐藏层,激励函数使用TensorFlow自带的tf.nn.relu
33 prediction = add_layer(h1, 10, 1, activation_function=None)  # 定义输出层
34 loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
35                                     reduction_indices=[1]))  # 计算预测值prediction和真实值的误差,对二者差的平方求和再取平均
36 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)  # 以0.1的效率来最小化误差loss
37 init = tf.global_variables_initializer()  # 使用变量前,必须初始化
38 sess = tf.Session()  # 定义Session
39 sess.run(init)  # 执行init初始化步骤
40 
41 # ### 结果可视化
42 fig = plt.figure()  # 创建图形实例
43 ax = fig.add_subplot(1, 1, 1)  # 创建子图,作为1行1列图形矩阵中的第1个subplot
44 ax.scatter(x_data, y_data)  # 绘制散点图
45 plt.ion()  # 打开交互模式
46 plt.show()  # 显示图形
47 
48 # ### 训练
49 for i in range(1000):  # 学习次数1000
50     sess.run(train_step, feed_dict={xs: x_data, ys: y_data})  # 学习内容是train_step
51     if i % 50 == 0:  # 每隔50次训练输出机器学习的误差和刷新一次图形
52         print("loss: {}".format(sess.run(loss, feed_dict={xs: x_data, ys: y_data})))
53         try:
54             ax.lines.remove(lines[0])
55         except Exception:
56             pass
57         prediction_value = sess.run(prediction, feed_dict={xs: x_data})
58         lines = ax.plot(x_data, prediction_value, 'r-', lw=5)  # 用红色、宽度为5的线来显示预测数据和输入之间的关系
59         plt.pause(0.2)  # 暂停0.2秒
60 
61 # ### 添加神经层
62 # 通过在TensorFlow中定义一个添加层的函数,可以添加神经层;
63 # 神经层里常见的参数通常有weights、biases和激励函数等;
64 # 添加神经层的函数def add_layer()有四个参数:输入值、输入的大小、输出的大小和激励函数;
65 #
66 # ### 构建数据
67 # 模拟真实数据;
68 #
69 # ### 搭建网络
70 # 神经网络(输入层1个、隐藏层10个、输出层1个);
71 #
72 # ### 训练
73 # 机器学习的内容是train_step, 用Session来run每一次training的数据,逐步提升神经网络的预测准确性;
74 # 注意:当运算要用到placeholder时,就需要feed_dict这个字典来指定输入;
75 #
76 # ### 可视化
77 # 利用matplotlib模块绘制和显示图形;

猜你喜欢

转载自www.cnblogs.com/anliven/p/10029637.html