tensorflow(1) 基础: 神经网络基本框架

1.tensorflow 的计算得到的是计算图graph

import tensorflow as tf
a=tf.constant([1.0,2.0])
b=tf.constant([3.0,4.0])
c=a+b
print(c)

结果:Tensor("add_5:0", shape=(2,), dtype=float32)

得到计算图(graph),不计算 其中
shape=(2,0)表示一维 ,长度2 dtype是数据类型

若要计算, 需要用到会话session

x=tf.constant([[1.0,2.0]]) #张量
w=tf.constant([[3.0],[4.0]])
y=tf.matmul(x,w)
print(y)  #得到计算图 graph
with tf.Session()as sess: #利用会话 运行
    print(sess.run(y))

得到 y=11.0

除了tf.conatant, 还有其他: tf.zeros, tf.ones

 tf.fill 全定值数组

print(tf.zeros([3,2]))
print(tf.ones([3,2]))
print(tf.fill([3,2],6)) #全定值数组
print(tf.constant([3,2,1]))

得到未计算的计算graph
Tensor("zeros:0", shape=(3, 2), dtype=float32)
Tensor("ones:0", shape=(3, 2), dtype=float32)
Tensor("Fill:0", shape=(3, 2), dtype=int32)
Tensor("Const_20:0", shape=(3,), dtype=int32)

2.生成随机数  tf.Variable

w=tf.Variable(tf.random_normal([2,3],stddev=2,mean=0,seed=1))# 2行3列
print(w)

得到 <tf.Variable 'Variable_18:0' shape=(2, 3) dtype=float32_ref>

  若seed没有则随机数每次不同,  2*3shape
上述tf.random_normal() 可以用tf.truncated_normal()替换,
 表示去掉过大偏离点的正态分布
tf.random_uniform() 平均分布

3. 神经网络实现步骤

step1 准备数据集,提取特征,作为输入喂给神经网络(natural network NN)

step2 搭建NN结构, 从输入到输出(先搭建计算图,再用会话执行)(NN前向传播算法,计算输出)

step 3 大量特征数据喂给NN,迭代优化NN参数(NN反向传播算法,将输出反向传给神经网络,调节参数优化参数训练模型)

step4 使用训练好的模型预测和分类
其中上述123 是训练过程, 第4步是使用过程(应用)

eg: 前向传播的example

生产一批零件 体积x1 重量 x2 作为输入,通过NN后输出一个参数

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 sess: #会话计算结果
    init_op=tf.global_variables_initializer() #初始化所有变量的函数,初始化为一个节点
    sess.run(init_op)
    print(sess.run(y))

得到 [[3.0904665]]
#tf.placeholder喂入数据
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 sess: #用会话计算结果 init_op=tf.global_variables_initializer() sess.run(init_op) print(sess.run(y,feed_dict={x:[[0.7,0.5]]})) #喂一组数据

若要为喂入多组数据:

x=tf.placeholder(tf.float32,shape=(None,2)) #实现喂多组数据 不知喂几组,设为None
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 sess: #用会话计算结果
    init_op=tf.global_variables_initializer()
    sess.run(init_op)
    print(sess.run(y,feed_dict={x:[[0.7,0.5],[0.3,0.4],[0.4,0.5]]}))

得到:

[[3.0904665]
 [1.7270732]
 [2.2305048]]

4.反向传播:训练模型参数w1 w2 ,在所有参数上用梯度下降,使得NN模型在训练数据上的损失函数最小,损失函数loss 预测值y 与已知答案 y_ 的差距

loss可以用均方误差, 均方误差MSE MSE(y_,y)=sum(y-y_)^2/n

loss=tf.reduce_mean(tf.square(y_-y))
反向传播的训练方法,以减小loss为优化目标,可以选择以下三个方法,都需要学习率
(决定每次参数更新的幅度), 一般选一个小一点的值0.001

train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
train_step=tf.train.MomentumOptimizer(learning_rate,momentum).minimize(loss)
train_step=tf.train.AdamOptimizer(learning_rate).minimize(loss)
#神经网络基本框架 记住!!!
batch_size=8 #一次喂给神经网络多少数据 
seed=23455
rng=np.random.RandomState(seed) #基于seed产生随机数
X=rng.rand(32,2) #32组数据(每组两个数据,体积,重量)
#从x这32行的矩阵中取出一行小于 则y赋值为1,大于1则赋值为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)
y=tf.matmul(a,w2)   
#定义损失函数 后向传播方法
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).minimize(loss) #其他方法
#train_step=tf.train.AdamOptimizer(0.001).minimize(loss)   

#生成会话 训练    
with tf.Session() as sess: #用会话计算结果
    init_op=tf.global_variables_initializer()
    sess.run(init_op)   
    print('w1:\n', sess.run(w1)) #输出目前(未经训练的)参数取值
    print('w2:\n', sess.run(w2))
#训练模型 
    steps=3000 #训练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]}) #8组数据
        if i % 500==0:  #每500轮打印一次loss值
            total_loss=sess.run(loss,feed_dict={x:X,y_:Y})
            print('After %d training steps,loss on all data is %g' %(i,total_loss))
    print('w1:\n', sess.run(w1)) #输出训练后的参数
    print('w2:\n', sess.run(w2))

X:
 [[0.83494319 0.11482951]
 [0.66899751 0.46594987]
 [0.60181666 0.58838408]
 [0.31836656 0.20502072]
 [0.87043944 0.02679395]
 [0.41539811 0.43938369]
 [0.68635684 0.24833404]
 [0.97315228 0.68541849]
 [0.03081617 0.89479913]
 [0.24665715 0.28584862]
 [0.31375667 0.47718349]
 [0.56689254 0.77079148]
 [0.7321604  0.35828963]
 [0.15724842 0.94294584]
 [0.34933722 0.84634483]
 [0.50304053 0.81299619]
 [0.23869886 0.9895604 ]
 [0.4636501  0.32531094]
 [0.36510487 0.97365522]
 [0.73350238 0.83833013]
 [0.61810158 0.12580353]
 [0.59274817 0.18779828]
 [0.87150299 0.34679501]
 [0.25883219 0.50002932]
 [0.75690948 0.83429824]
 [0.29316649 0.05646578]
 [0.10409134 0.88235166]
 [0.06727785 0.57784761]
 [0.38492705 0.48384792]
 [0.69234428 0.19687348]
 [0.42783492 0.73416985]
 [0.09696069 0.04883936]]
Y:
 [[1], [0], [0], [1], [1], [1], [1], [0], [1], [1], [1], [0], [0], [0], [0], [0], [0], [1], [0], [0], [1], [1], [0], [1], [0], [1], [1], [1], [1], [1], [0], [1]]
w1:
 [[-0.8113182   1.4845988   0.06532937]
 [-2.4427042   0.0992484   0.5912243 ]]
w2:
 [[-0.8113182 ]
 [ 1.4845988 ]
 [ 0.06532937]]
After 0 training steps,loss on all data is 5.13118
After 500 training steps,loss on all data is 0.429111
After 1000 training steps,loss on all data is 0.409789
After 1500 training steps,loss on all data is 0.399923
After 2000 training steps,loss on all data is 0.394146
After 2500 training steps,loss on all data is 0.390597
w1:
 [[-0.7000663   0.9136318   0.08953571]
 [-2.3402493  -0.14641267  0.58823055]]
w2:
 [[-0.06024267]
 [ 0.91956186]
 [-0.0682071 ]]

猜你喜欢

转载自www.cnblogs.com/xuying-fall/p/8971306.html