Tensorflow学习笔记-例子3建造神经网络&可视化

前言

Tensorflow学习笔记,一个简单的例子,建立一个3层的神经网络(输入层1个神经元 隐藏层10个神经元 输出层1个神经元),通过训练去接近并拟合real_data,目标为误差loss的下降,并用pyplot将过程可视化出来。

学习目的:熟悉神经网络建造逻辑,熟悉Tensorflow功能性函数的应用。

最终输出:

img


代码

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# 添加一个新的层,输入值,输入单位数,输出单位数,激励函数默认为None,即线性函数
def add_layer(inputs,in_size,out_size,activation_function=None):

# 定义一个随机变量,数据格式为 in_size行 out_size列
Weights = tf.Variable(tf.random_normal([in_size,out_size]))

# 定义一个变量,从零开始,数据格式为1行out_size列
# 在机器学习中 biases的初始值推荐不为0,所以+0.1
biases = tf.Variable(tf.zeros([1,out_size]) + 0.1)

# 预测函数
Wx_plus_b = tf.matmul(inputs,Weights) + biases

if activation_function is None:
outputs = Wx_plus_b
else:
# 用激励函数掰弯Wx_plus_b
outputs = activation_function(Wx_plus_b)

return outputs


### 制作真实数据 ###

# 生成等差数列,x_data有300行(或者说300个实例),范围-1到1,np.newaxis加一个维度
x_data = np.linspace(-1,1,300)[:,np.newaxis]
# 添加噪音,让数据更接近真实,方差0.05,格式与x_data一样
noise = np.random.normal(0,0.05,x_data.shape)

y_data = np.square(x_data) - 0.5 + noise # np.square()平方计算

xs = tf.placeholder(tf.float32,[None,1]) # 占位,将在sess.run(train_step)时传参,None表示有多少实例都ok
ys = tf.placeholder(tf.float32,[None,1]) # 占位,将在sess.run(train_step)时传参

### 制作真实数据 ###

# 输入层1个神经元 隐藏层10个 输出层1个

### 设置层参数 ###

# 定义隐藏层
l1 = add_layer(xs,1,10,activation_function=tf.nn.relu) # tf提供多种activation_function 这里通常选择tf.nn.relu
# 定义输出层
prediction = add_layer(l1,10,1,activation_function=None)

### 设置层参数 ###

# 误差,predition与ys的差值
# tf.square(ys - predition)每个例子的平方
# tf.reduce_sum()所有例子求和
# tf.reduce_mean()求平均值
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))

# 训练,减少误差, tf.train.GradientDescentOptimizer为常用方法,学习效率0.1(要求小于1),对象为loss
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# 初始化
init = tf.global_variables_initializer()

# 指针
sess = tf.Session()
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(1000):
# 训练并传参
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0: # 每隔50个
# print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
try:
# 每次循环抹除上次的线,第一次时没有就pass
ax.lines.remove(lines[0])
except Exception: # 所有异常都是基类 Exception的成员
pass

prediction_value = sess.run(prediction, feed_dict={xs: x_data, ys: y_data})
# 用了线段表示预测值prediction_value,红色,线宽5
lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
# 暂停0.1秒
plt.pause(0.1)

1.创建并定义新的神经层

一个新的神经层的逻辑关系如下图

img

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import tensorflow as tf
import numpy as np

# 添加一个新的层,输入值,输入单位数,输出单位数,激励函数默认为None,即线性函数
def add_layer(inputs,in_size,out_size,activation_function=None):

# 定义一个随机变量,数据格式为 in_size行 out_size列
Weights = tf.Variable(tf.random_normal([in_size,out_size]))

# 定义一个变量,从零开始,数据格式为1行out_size列
# 在机器学习中 biases的初始值推荐不为0,所以+0.1
biases = tf.Variable(tf.zeros([1,out_size]) + 0.1)

# 预测函数
Wx_plus_b = tf.matmul(inputs,Weights) + biases

if activation_function is None:
outputs = Wx_plus_b
else:
# 用激励函数掰弯Wx_plus_b
outputs = activation_function(Wx_plus_b)

return outputs

2.制作真实数据

代码:

1
2
3
4
5
6
# 生成等差数列,x_data有300行(或者说300个实例),范围-1到1,np.newaxis加一个维度
x_data = np.linspace(-1,1,300)[:,np.newaxis]
# 添加噪音,让数据更接近真实,方差0.05,格式与x_data一样
noise = np.random.normal(0,0.05,x_data.shape)

y_data = np.square(x_data) - 0.5 + noise # np.square()平方计算

3.设置占位xs&ys

代码:

1
2
3
4
xs = tf.placeholder(tf.float32,[None,1]) 
# 占位,将在sess.run(train_step)时传参,None表示有多少实例都ok
ys = tf.placeholder(tf.float32,[None,1])
# 占位,将在sess.run(train_step)时传参
  • tf.placeholder()占位符

    1
    2
    3
    4
    5
    6
    tf.placeholder 函数
    placeholder(
    dtype,
    shape=None,
    name=None
    )

    ​tf.placeholder()与feed_dict={} 是前后绑定的,先占位,后传参

  • tf.float32 是tensorflow中通常采用的默认格式

4.设置层参数

先声明:输入层1个神经元 隐藏层10个神经元 输出层1个神经元

代码:

1
2
3
4
# 定义隐藏层
l1 = add_layer(xs,1,10,activation_function=tf.nn.relu) # tf提供多种activation_function 这里通常选择tf.nn.relu
# 定义输出层
prediction = add_layer(l1,10,1,activation_function=None)

激励函数 activation_function

img

查看所有activation_function:官方文档

  • tf.nn.relu 小于0时等于0大于时线性增加

    1
    2
    3
    4
    relu(
    features,
    name=None
    )
  • tf.nn.relu6

    1
    2
    3
    4
    relu6(
    features,
    name=None
    )
  • tf.nn.crelu

    1
    2
    3
    4
    crelu(
    features,
    name=None
    )
  • tf.nn.elu

    1
    2
    3
    4
    elu(
    features,
    name=None
    )
  • tf.nn.selu

    1
    2
    3
    4
    selu(  
    features, 
    name=None
    )
  • tf.nn.softplus

    1
    2
    3
    4
    softplus( 
    features, 
    name=None
    )
  • tf.nn.softsign

    1
    2
    3
    4
    softsign(   
    features,   
    name=None
    )
  • tf.nn.dropout

    1
    2
    3
    4
    5
    6
    7
    dropout( 
    x,   
    keep_prob, 
    noise_shape=None, 
    seed=None, 
    name=None
    )
  • tf.nn.bias_add

    1
    2
    3
    4
    5
    6
    bias_add(   
    value,   
    bias, 
    data_format=None, 
    name=None
    )
  • tf.sigmoid

    1
    2
    3
    4
    sigmoid( 
    x, 
    name=None
    )
  • tf.tanh

    1
    2
    3
    4
    tanh(   
    x, 
    name=None
    )

TensorFlow提供了多种激励函数的选择,根据不同情况推荐使用不同的激励函数:

  • 2-3层神经网络:随意使用,不会有太大影响。
  • 在卷积神经网络中:首选 relu
  • 在循环神经网络中:首选 relu or tanh

5.误差

代码:

1
2
3
4
5
# 误差,predition与ys的差值
# tf.square(ys - predition)每个例子的平方
# tf.reduce_sum()所有例子求和
# tf.reduce_mean()求平均值
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))

6.训练设置

代码:

1
2
# 训练,减少误差, tf.train.GradientDescentOptimizer为常用方法,学习效率0.1(要求小于1),对象为loss
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

tf.train训练函数

tf.train 提供了一组帮助训练模型的类和函数。

optimizer优化器

查看所有 optimizer优化器:官方文档

下图是不同optimizer优化器达到相同训练目标的效率对比:

img

7.初始化&指针

代码:

1
2
3
4
5
6
# 初始化
init = tf.global_variables_initializer()

# 指针
sess = tf.Session()
sess.run(init) # 激活

8.循环训练

代码:

1
2
3
4
5
for i in range(1000):
# 训练并传参
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i % 50 == 0: # 每隔50个
print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
  • feed_dict={xs:x_data,ys:y_data}

    在每次sess.run()时以feed_dict的形式传入参数(dict)

9.可视化

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data,y_data)
plt.ion() # 使图像编辑连续进行
plt.show()


for i in range(1000):
# 训练并传参
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0: # 每隔50个
try:
# 每次循环抹除上次的线,第一次时没有就pass
ax.lines.remove(lines[0])
except Exception: # 所有异常都是基类 Exception的成员
pass

prediction_value = sess.run(prediction, feed_dict={xs: x_data, ys: y_data})
# 用了线段表示预测值prediction_value,红色,线宽5
lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
# 暂停0.1秒
plt.pause(0.1)

输出:

img

用钱砸我,不要停!