Tensorflow学习之实现简单的神经网络
栖迟于一丘的《Tensorflow学习之旅》系列文章目录
关于神经网络的知识这里就不介绍了,重点关注实现方法。
tensorflow中tf.Variable()用于保存和更新参数,tf.matmul()用于矩阵计算,tf.random_normal()定义正太分布。先来看一个前向传播计算:
import tensorflow as tf #定义变量 w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) #stddev为标准差,seed为随机种子 w2= tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) x = tf.constant([[0.7, 0.9]]) #tf.constant()设定固定值 #定义前向传播网络 a = tf.matmul(x, w1) y = tf.matmul(a, w2) #定义会话运算 sess = tf.Session() sess.run(w1.initializer) sess.run(w2.initializer) print(sess.run(y)) sess.close()
上面是一个三层神经网络计算,如果是复杂网络的初始化,可以使用
init_op=tf.global_variables_initializer() print(sess.run(init_op))
来初始化(注意,旧版方法是init_op=tf.initialize_all_variables())
2.
另一种方法是使用placeholder机制来定义计算。其中feed_dict是一个字典,定义了placeholder的取值,即y的值。
import tensorflow as tf w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2= tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) **x = tf.placeholder(tf.float32, shape=(1, 2), name="input")** a = tf.matmul(x, w1) y = tf.matmul(a, w2) sess = tf.Session() init_op = tf.global_variables_initializer() sess.run(init_op) print(sess.run(y, feed_dict={x: [[0.7,0.9]]}))
如果使用反向传播来定义神网络则需要设定更复杂的参数:
import tensorflow as tf from numpy.random import RandomState #参数设定包括输入输出节点 batch_size = 8 #每次选取的样本数 w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2= tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) x = tf.placeholder(tf.float32, shape=(None, 2), name="x-input") y_= tf.placeholder(tf.float32, shape=(None, 1), name='y-input') #定义前向传播过程,损失函数及反向传播算法 a = tf.matmul(x, w1) y = tf.matmul(a, w2) #反向传播,除了AdamOptimizer还有其它优化方法 cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0))) train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy) #生成模拟数据集,这里定义的规则是x1+x2<1表示合格的样本 rdm = RandomState(1) X = rdm.rand(128,2) Y = [[int(x1+x2 < 1)] for (x1, x2) in X] #创建一个会话来运行程序 with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) # 输出目前(未经训练)的参数取值。 print(u"未训练参数是") print ("w1:", sess.run(w1)) print ("w2:", sess.run(w2)) print ("\n") # 训练模型。 STEPS = 5000 #设定训练轮数 for i in range(STEPS): start = (i*batch_size) % 128 end = (i*batch_size) % 128 + batch_size sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]}) if i % 1000 == 0: total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_: Y}) print(u"在第 %d 次训练后, 所有数据的交叉熵是 %g" % (i, total_cross_entropy)) # 输出训练后的参数取值。 print ("\n") print(u"训练后参数是") print ("w1:", sess.run(w1)) print ("w2:", sess.run(w2))
以上就是使用tensorflow实现简单的神经网络。
原文地址:https://www.hongweipeng.com/index.php/archives/1269/