tensorflow构建BP神经网络的方法
之前的一篇博客专门介绍了神经网络的搭建,是在python环境下基于numpy搭建的,之前的numpy版两层神经网络,不能支持增加神经网络的层数。最近看了一个介绍tensorflow的视频,介绍了关于tensorflow的构建神经网络的方法,特此记录。
tensorflow的构建封装的更加完善,可以任意加入中间层,只要注意好维度即可,不过numpy版的神经网络代码经过适当地改动也可以做到这一点,这里最重要的思想就是层的模型的分离。
import tensorflow as tf import numpy as np def addLayer(inputData,inSize,outSize,activity_function = None): Weights = tf.Variable(tf.random_normal([inSize,outSize])) basis = tf.Variable(tf.zeros([1,outSize])+0.1) weights_plus_b = tf.matmul(inputData,Weights)+basis if activity_function is None: ans = weights_plus_b else: ans = activity_function(weights_plus_b) return ans x_data = np.linspace(-1,1,300)[:,np.newaxis] # 转为列向量 noise = np.random.normal(0,0.05,x_data.shape) y_data = np.square(x_data)+0.5+noise xs = tf.placeholder(tf.float32,[None,1]) # 样本数未知,特征数为1,占位符最后要以字典形式在运行中填入 ys = tf.placeholder(tf.float32,[None,1]) l1 = addLayer(xs,1,10,activity_function=tf.nn.relu) # relu是激励函数的一种 l2 = addLayer(l1,10,1,activity_function=None) loss = tf.reduce_mean(tf.reduce_sum(tf.square((ys-l2)),reduction_indices = [1]))#需要向相加索引号,redeuc执行跨纬度操作 train = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 选择梯度下降法 init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) for i in range(10000): sess.run(train,feed_dict={xs:x_data,ys:y_data}) if i%50 == 0: print sess.run(loss,feed_dict={xs:x_data,ys:y_data})
相关推荐
Micusd 2020-11-19
xjtukuixing 2020-10-27
lybbb 2020-10-15
lybbb 2020-09-29
ghjk0 2020-09-24
yamaxifeng 2020-09-09
GDGYZL 2020-08-28
lybbb 2020-08-28
Icevivian 2020-08-25
comwayLi 2020-08-16
carbon0 2020-08-16
源式羽语 2020-08-09
sherry颖 2020-08-01
songbinxu 2020-07-19
sherry颖 2020-07-18
Niteowl 2020-07-15
Kindle君 2020-07-15
源式羽语 2020-07-04
源式羽语 2020-06-28