神经网络实现过程:
-
准备数据集,提取特征,作为输入喂给神经网络
-
code snippet widget搭建NN结构,从输入到输出(先搭建计算图,再用会话执行)(NN前向传播算法->计算输出)
-
大量特征数据喂给NN,迭代优化NN参数(NN反向传播算法->优化参数训练模型)
-
使用训练好的模型预测和分类
变量初始化、计算图节点运算都要用会话(with结构)实现
with tf.Session() as sess:
sess.run()
变量初始化:在sess.run函数中用tf.global_variables_initializer()
init_op = tf.global_variables_initializer()
sess.run(init_op) #实现了所有变量的初始化
计算图节点运算:在sess.run函数中写入待运算的节点
sess.run(y)
用tf.placeholder占位,在sess.run函数中用feed_dict喂数据
- 喂一组数据:
x = tf.placeholder(tf.float32,shape=(1,2))
sess.run(y,feed_dict={x:[[0.5,0.6]]})
- 喂两组数据:
x = tf.placeholder(tf.float32,shape=(None,2))
sess.run(y,feed_dict={x:[[0.1,0.2],[0.2,0.3],[0.4,0.5]})
实践:
#coding:utf-8
#两层简单神经网络
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.matmal(x,w1)
y = tf.matmal(a,w2)
#用会话计算结果
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op) #变量全部初始化
print("y is:\n",sess.run(y))
反向传播->训练数据模型,在所有参数上用梯度下降,使NN模型在训练数据上损失函数最小。
损失函数(loss):预测值(y)与已知答案(y_)的差距
均方误差MSE:loss = tf.reduce_mean(tf.square(y_-y))
反向传播训练方法:以减小loss值为优化目标
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)#梯度下降
train_step = tf.train.MomentumOptimizer(learning_rate,momentum).minimize(loss)
train_step = tf.train.AdamOptimizer(learn_rate).minimize(loss)
学习率:决定参数每次更新的幅度
#coding utf-8
#0导入模块,生成模拟数据集
import tensorflow as tf
import numpy as np
BATCH_SIZE= 8
seed = 23455
#基于seed产生随机数
rng = np.random.RandomState(seed)
#随机数返回32行2列的矩阵,表示32组 体积和重量 作为输入数据集
X = rng.rand(32,2)
#从X这个32行2列的矩阵中,取出一行,判断如果和小于1 给Y赋值1 如果和不小于1 给Y赋值0
#作为输入数据集的标签(正确答案)
Y = [[int(x0 + x1 < 1) for (x0,x1) in X]]
print("X:\n",X)
print("Y:\n",Y)
#定义神经网络的输入、参数和输出,定义前向传播过程
x = tf.placeholder(tf.float32,shape = (None,2))
y_ =tf.placeholder(tf.float32,shape = (None,1))
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)
#定义损失函数及反向传播方法
loss = tf.reduce_mean(tf.square(y-y_))
train_step = tf.train.GradientDescentOPtimizer(0.001).minimize(loss)
#train_step = tf.train.MomentumOptimizer(0.001,0.9).minimizi(loss)
#train_step = tf.train.AdamOPtimizer(0.001).minimize(loss)
#生成会话,训练steps轮
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.(init_op)
#输出目前(未经训练)的参数取值
print("w1:\n",sess.run(w1))
print("w2:\n",sess.run(w2))
print("\n")
#训练模型
STEPS =3000
for i in range(STEPS):
start = (i*BATCH_SIZE) % 32
end = start + BATCH_SIZE
sess.run(train_step,feed_dict={x:X[start:end],y:Y[start:end]})
if i %500 ==0:
total_loss = sess.run(loss,feed_dict={x:X,y_:Y})
print("After %d training steps,loss on all date is %g" %(i,total_loss))
#输出训练后的参数取值
print("\n")
print("w1:\n",sess.run(w1))
print("w2:\n",sess.run(w2))
神经网络搭建八股:准备、前传、反传、迭代