基於tensorflow的簡單BP神經網路的結構搭建
阿新 • • 發佈:2019-01-30
tensorflow的構建封裝的更加完善,可以任意加入中間層,只要注意好維度即可,不過numpy版的神經網路程式碼經過適當地改動也可以做到這一點,這裡最重要的思想就是層的模型的分離。下面介紹關於tensorflow的構建神經網路的方法,特此記錄。
- 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 isNone:
- 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=
- 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})