tensorflow 2.1搭建神经网络

1.Session会话控制

Session是 Tensorflow 为了控制,和输出文件的执行的语句. 运行 session.run() 可以获得你要得知的运算结果, 或者是你所要运算的部分。

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

matrix1 = tf.constant([[3, 2]])
matrix2 = tf.constant([[2], [2]])

product = tf.matmul(matrix1, matrix2)

# method1
sess = tf.compat.v1.Session()
result = sess.run(product)
print(result)
sess.close()

# method2
with tf.compat.v1.Session() as sess:
    result = sess.run(product)
    print(result)
2.Variable 变量

Varible定义变量,在 Tensorflow 中变量是需要提前定义的。

import tensorflow as tf

tf.compat.v1.disable_eager_execution()  # 保证sess.run()能够正常运行

state = tf.Variable(0, name='counter')  # 变量state的名字为“counter”
# print(state.name)   # counter:0
one = tf.constant(1)  # 创建常量

new_value = tf.add(state, one)
update = tf.compat.v1.assign(state, new_value)  # assign: 将new_value赋值给state

init = tf.compat.v1.initialize_all_variables()  # 变量初始化

with tf.compat.v1.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))



###  tensorflow 2.1  ###

# state = tf.Variable(0, name='counter')
# one = tf.constant(1)
# new_value = tf.add(state, one)
#
# for _ in range(3):
#     state.assign_add(new_value)
#     tf.print(state)
3.placeholder 占位符

placeholder 是 Tensorflow 中的占位符,暂时储存变量.

Tensorflow 如果想要从外部传入data, 那就需要用到 tf.placeholder(), 然后以这种形式传输数据 sess.run(***, feed_dict={input: **})

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

input1 = tf.compat.v1.placeholder(tf.float32)  # 需要定义placeholder的type,一般为float32形式
input2 = tf.compat.v1.placeholder(tf.float32)

output = tf.multiply(input1, input2)  # 乘法运算

# 接下来, 传值的工作交给了 sess.run()
# 需要传入的值放在了feed_dict={} 并逐一对应每一个input.
# placeholder 与 feed_dict={} 是绑定在一起出现的。
with tf.compat.v1.Session() as sess:
    print(sess.run(output, feed_dict={input1:[7.], input2:[2.]}))

4.激活函数(激励函数)

激活函数(activation function)为神经元提供规模化非线性化能力。激活函数运行时激活神经网络中某一部分神经元,将激活信息向后传入下一层的神经系统。激活函数的实质是非线性方程。最大作用就是非线性化,将线形函数变成非线性函数。

常用:relu, sigmoid, tanh

在这里插入图片描述

这里的 AF 就是指的激活函数, 激活函数拿出自己最擅长的”掰弯利器”, 嵌套在原有的结果之上, 强行把原有的线性结果给扭曲。

5.add_layer() 添加层

在 Tensorflow 里定义一个添加层的函数可以很容易的添加神经层,为之后的添加省下不少时间.

神经层里常见的参数通常有weightsbiasesactivation function

import tensorflow as tf

def add_layer(inputs, in_size, out_size, activation_function=None):
    '''
    :param inputs: 输入值
    :param in_size: 输入值的大小
    :param out_size: 输出值的大小
    :param activation_function: 激活函数
    :return: outputs
    '''

    # 定义Weights为一个 in_size行 out_size列 的随机变量矩阵
    Weights = tf.Variable(tf.compat.v1.random_normal([in_size, out_size]))
    # biases一般不推荐0, 所以在0的基础上加0.1
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    # 矩阵相乘
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    # Wx_plus_b = tf.matmul(tf.cast(inputs, tf.float32), Weights) + biases

    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs
6. numpy.linspace()

使用方法:numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

在指定的间隔内返回均匀间隔的数字。

返回num个均匀分布的样本,在[start, stop]

这个区间的端点可以任意的被排除在外。

import numpy as np

x_data = np.linspace(0, 1, 5)

print(x_data)

运行结果:

[0.   0.25 0.5  0.75 1.  ]
7. np.newaxis

numpynewaxis的作用就是将现有数组的维度增加一个维度。
即1维数组转为2维,2维数组转为3维,…

import numpy as np

A = np.array([1, 2, 3, 4])
# A.shape:  (4, )

B = A[np.newaxis, :]
# B.shape:  (4, 1)

C = A[:, np.newaxis]
# C.shape:  (1, 4)
8. np.random.normal()

numpy.random.normal(loc=0.0, scale=1.0, size=None) :从正态分布(高斯分布)中抽取随机样本。

参数:loc: 正态分布的均值,scale:正态分布的标准差, size: 输出的形式

输出:从参数化的正态分布中提取的样本

9. 建造神经网络
import tensorflow as tf
import numpy as np

tf.compat.v1.disable_eager_execution()


def add_layer(inputs, in_size, out_size, activation_function=None):
    '''
    :param inputs: 输入值
    :param in_size: 输入值的大小
    :param out_size: 输出值的大小
    :param activation_function: 激活函数
    :return: outputs
    '''

    # 定义Weights为一个 in_size行 out_size列 的随机变量矩阵
    Weights = tf.Variable(tf.compat.v1.random_normal([in_size, out_size]))
    # biases一般不推荐0, 所以在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:
        outputs = activation_function(Wx_plus_b)
    return outputs

# 导入(构建)数据
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

xs = tf.compat.v1.placeholder(tf.float32, [None, 1])
ys = tf.compat.v1.placeholder(tf.float32, [None, 1])

# 搭建网络
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
prediction = add_layer(l1, 10, 1, activation_function=None)

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), axis=[1]))
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.1).minimize(loss)  # 以0.1的效率梯度下降往loss减小的方向

init = tf.compat.v1.initialize_all_variables()
sess = tf.compat.v1.Session()
sess.run(init)

# 训练网络
for i in range(1000):
    sess.run(train_step, feed_dict={xs:x_data, ys:y_data})
    if i % 50 == 0:
        print(sess.run(loss, feed_dict={xs:x_data, ys:y_data}))


运行结果:

0.6750809
0.013817048
0.008210192
0.00718851
0.006341555
0.0057298364
0.0052224123
0.004809527
0.0044626314
0.0042014774
0.0039773313
0.0038042339
0.0036624034
0.0035274748
0.0034029614
0.0032667653
0.0031756295
0.0031010623
0.0030320964
0.0029665316
10. matpoltlib 可视化
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

tf.compat.v1.disable_eager_execution()
# plt.use("TkAgg")

def add_layer(inputs, in_size, out_size, activation_function=None):
    '''
    :param inputs: 输入值
    :param in_size: 输入值的大小
    :param out_size: 输出值的大小
    :param activation_function: 激活函数
    :return: outputs
    '''

    # 定义Weights为一个 in_size行 out_size列 的随机变量矩阵
    Weights = tf.Variable(tf.compat.v1.random_normal([in_size, out_size]))
    # biases一般不推荐0, 所以在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:
        outputs = activation_function(Wx_plus_b)
    return outputs

# 导入(构建)数据
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

xs = tf.compat.v1.placeholder(tf.float32, [None, 1])
ys = tf.compat.v1.placeholder(tf.float32, [None, 1])

# 搭建网络
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.tanh)
prediction = add_layer(l1, 10, 1, activation_function=None)

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), axis=[1]))
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.1).minimize(loss)  # 以0.1的效率梯度下降往loss减小的方向

init = tf.compat.v1.initialize_all_variables()
sess = tf.compat.v1.Session()
sess.run(init)

# 构建图形
fig = plt.figure()  # 生成图片框
ax = fig.add_subplot(1, 1, 1)  # 做一个连续性的画图需要用到add_subplot函数
ax.scatter(x_data, y_data)  # plot真实的数据
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:
        # print(sess.run(loss, feed_dict={xs:x_data, ys:y_data}))
        # 图形显示预测数据
        try:
            # 如果想连续plot出线,就需要把之前的线去除掉,否则太多的线看不清最后的结果
            ax.lines.remove(lines[0])
        except:
            pass
        # 定义预测数据
        prediction_value = sess.run(prediction, feed_dict={xs:x_data})
        # 用红色、宽度为5的线来显示我们的预测数据和输入之间的关系,并暂停0.1s
        lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
        plt.pause(0.1)

结果最终显示:

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值