一、基于TensorFlow的NN
用张量表示数据
用计算图搭建神经网络
用会话执行计算图
优化线上的权重(参数)
得到模型
实现过程:
1、准备数据集,提取特征,作为输入喂给神经网络
2、搭建NN结构,从输入到输出(先搭建计算图,再用会话执行)
(NN前向传播算法——>计算输出)
3、大量特征数据喂给NN,迭代优化NN参数
(NN反向传播算法——>优化参数训练模型)
4、使用训练好的模型预测和分类
二、基本概念
其中X是神经元,W是参数
1、张量(tensor):多维数组
1、阶:张量的维数
0阶:标量
1阶:向量
2阶:矩阵
3阶:张量
张量可以表示0阶到n阶数组(列表)
2、数据类型
tf.float32
tf.int32
3、计算图(Graph):搭建神经网络的计算过程,只搭建,不计算
# 计算图.py
>>> import tensorflow as tf
>>> a = tf.constant([1.0,2.0])
>>> b = tf.constant([3.0,4.0])
>>> result = a + b
>>> print(result)
# 节点名:add
# 第0个输出:0
# 维度:shape
# 一维数组长度2:(2,0)
# 数据类型:dtype
Tensor("add:0", shape=(2,), dtype=float32)
# 结果只显示了计算图,不显示的结果
# 计算图只描述运算过程,不运算4、会话(Session):执行计算图中的节点运算
import tensorflow as tf x = tf.constant([[1.0,2.0]]) w = tf.constant([[3.0],[4.0]]) y = tf.matmul(x,w) # 矩阵输入乘法 print(y) with tf.Session() as sess: # 其中计算方法为向量的乘积 print(sess.run(y))
三、向前传播
基本步骤
定义好计算图
使用会话传递参数然后计算
1、参数:即W,用变量表示,随机给初值
2、计算层
输入X = [X1,X2]
输入不算在层数中
x1,x2 a11,a12,a13是第一层W1(2X3矩阵)
a11,a12,a13 y是第二层W2(3X1矩阵)
a = X x W1
y = a x W2
3、变量计算
(1)使用with结构的session计算
(2)变量初始化
init_op = tf.global_variable_initializer()
(3)计算节点运算
sessioin.run(y)
练习
2、喂入单组特征
w = tf.Variable(tf.random_normal([2.3], stddev=2, mean=0, seed=1))
# coding:utf-8
# 向前传播过程
# FrontSpread.py
import tensorflow as tf
# 定义输入和参数
x = tf.constant([[0.7,0.5]])
w1 = tf.Variable(tf.random_normal([2,3], stddev=1,seed=1))
w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))
# 定义前向传播过程
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
# 用会话计算结果
with tf.Session() as session:
init_op = tf.global_variables_initializer()
session.run(init_op)
print('y in 向前传播 is:\n', session.run(y))4、喂入多组特征
import tensorflow as tf
# 用placeholder实现输入定义 (session.run中喂一组数据)
x = tf.placeholder(tf.float32, shape=(1,2))
w1 = tf.Variable(tf.random_normal([2,3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))
# 定义前向传播过程,使用矩阵乘法
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
# 用会话计算结果
with tf.Session() as session:
init_op = tf.global_variables_initializer()
session.run(init_op)
# 定义字典把x的一组数据输入
print('y in 向前传播 is:\n', session.run(y, feed_dict={x: [[0.7,0.5]]}))5、喂入N组特征
import tensorflow as tf
# 用placeholder实现输入定义 (session.run中喂N组数据)
x = tf.placeholder(tf.float32, shape=(None,2))
w1 = tf.Variable(tf.random_normal([2,3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))
# 定义前向传播过程,使用矩阵乘法
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
# 用会话计算结果
with tf.Session() as session:
# 把初始化所有变量的函数简写为init_op
init_op = tf.global_variables_initializer()
session.run(init_op)
print('y in 向前传播 is:\n', session.run(y,
feed_dict={x: [[0.7,0.5], [0.2,0.3], [0.1,0.9]]}))四、反向传播
1、概念:训练模型参数,在所有参数上用梯度下降,使NN模型在训练数据上的损失函数最小
(1)损失函数
预测值(y)- 已知答案(y_)
(2)均方误差MSE
loss = tf.reduce_mean(tf.square(y_-y)
(3)反向传播方法:以减小loss值为优化目标
(4)优化率:决定参数每次更新的幅度