最近在学习tensorflow相关知识,主要参考的课程有MOOC北京大学曹健老师的tensorflow笔记,
课程链接:https://www.icourse163.org/learn/PKU-1002536002?tid=1002700003
课程中的搭建实例:
具体包括四个步骤:导入模块生成数据,定义神经网络输入输出定义神经网络模型,定义损失函数和优化放方法,生成会话开始训练。
1 #coding:utf-8
2 #step0:导入模块,生成模拟数据集
3 import tensorflow as tf
4 import numpy as np
5 BATCH_SIZE=8
6 seed=23455
7
8 #基于seed产生随机数
9 rng=np.random.RandomState(seed)
10 X=rng.rand(32,2)
11 Y=[[int(x0+x1<1)] for (x0,x1) in X]
12 print "X:\n",X
13 print "Y:\n",Y
14
15 #step1:定义神经网络输入、参数和输出,定义前向传播过程
16 x=tf.placeholder(tf.float32,shape=(None,2))
17 y_=tf.placeholder(tf.float32,shape=(None,1))
18
19 w1=tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
20 w2=tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))
21
22 #定义前向传播
23 a=tf.matmul(x,w1)
24 y=tf.matmul(a,w2)
25
26
27 #step2:定义损失函数和反向传播方法
28 loss=tf.reduce_mean(tf.square(y-y_))
29 train_step=tf.train.GradientDescentOptimizer(0.01).minimize(loss)
30
31 #step3:生成会话,训练STEPS轮
32 with tf.Session() as sess:
33 init_op=tf.global_variables_initializer()
34 sess.run(init_op)
35 print "w1:\n",sess.run(w1)
36 print "w2:\n",sess.run(w2)
37 print "\n"
38
39 #训练模型
40 STEPS=3000
41 for i in range(STEPS):
42 start = (i*BATCH_SIZE)%32
43 end = start+BATCH_SIZE
44 sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
45 if i%500 ==0:
46 total_loss=sess.run(loss,feed_dict={x:X,y_:Y})
47 print("After %d training step(s),loss on all data is %g" %(i,total_loss))
48
49
50
51 print "\n"
52 print "w1:\n",sess.run(w1)
53 print "w2:\n",sess.run(w2)
54