搭建神经网络
准备
准备阶段包括常量定义、构建输入数据集等。
import tensorflow as tf
import numpy as np
BATCH_SIZE = 8
seed = 23455
//构造输入数据
rng = np.random.RandomState(seed)
X = rng.rand(32,2)
Y = [[int(x0 + x1 < 1)] for (x0,x1) in X]
print(X)
print(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,mean=0,seed=1))
w2 = tf.Variable(tf.random_normal([3,1],stddev=1,mean=0,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_step1 = tf.train.MomentumOptimizer(learning_rate,momentum).minimize(loss)
//train_step2 = tf.train.AdamOptimizer(learning_rate).minimize(loss)
产生会话,训练神经网络
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(w1))
print(sess.run(w2))
//模型开始训练
STEPS = 3000
for i in range(STEPS):
start = (i*BATCH_SIZE)%32
end = start + BATCH_SIZE
print('start:',end='')
print(start)
print('end:',end='')
print(end)
sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
if i % 500:
total_loss = sess.run(loss,feed_dict={x:X,y_:Y})
print('loss:',end='')
print(total_loss)
print(sess.run(w1))
print(sess.run(w2))