简单的前馈神经网络与TensorFlow不会学习
我正尝试用TensorFlow建立一个简单的神经网络。 目标是在32像素x 32像素的图像中找到矩形的中心。 该矩形由五个向量描述。 第一个矢量是位置矢量,其他四个是方向矢量并组成矩形边缘。 一个矢量有两个值(x和y)。
该图像的相应输入将是(2,5)(0,4)(6,0)(0,-4)( - 6,0) 。 中心(以及所需的输出)位于(5,7)处 。
我想出的代码如下所示:
import tensorflow as tf
import numpy as np
import Rectangle_Records
def init_weights(shape):
""" Weight initialization """
weights = tf.random_normal(shape, stddev=0.1)
return tf.Variable(weights)
def forwardprop(x, w_1, w_2):
""" Forward-propagation """
h = tf.nn.sigmoid(tf.matmul(x, w_1))
y_predict = tf.matmul(h, w_2)
return y_predict
def main():
x_size = 10
y_size = 2
h_1_size = 256
# Prepare input data
input_data = Rectangle_Records.DataSet()
x = tf.placeholder(tf.float32, shape = [None, x_size])
y_label = tf.placeholder(tf.float32, shape = [None, y_size])
# Weight initializations
w_1 = init_weights((x_size, h_1_size))
w_2 = init_weights((h_1_size, y_size))
# Forward propagation
y_predict = forwardprop(x, w_1, w_2)
# Backward propagation
cost = tf.reduce_mean(tf.square(y_predict - y_label))
updates = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
# Run
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
for i in range(200):
batch = input_data.next_batch(10)
sess.run(updates, feed_dict = {x: batch[0], y_label: batch[1]})
sess.close()
if __name__ == "__main__":
main()
可悲的是,网络将无法正确学习。 结果太遥远了。 例如,[[3.74561882,3.70766664]]应该是[[3.,7.]]。 我究竟做错了什么?
主要的问题是你的整个训练只进行one epoch ,这没有足够的训练。 尝试以下更改:
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
for j in range(30):
input_data = Rectangle_Records.DataSet()
for i in range(200):
batch = input_data.next_batch(10)
loss, _ = sess.run([cost,updates], feed_dict = {x: batch[0], y_label: batch[1]})
pred = sess.run(y_predict, feed_dict={x: batch[0]})
print('Cost:', loss )
print('pred:', pred)
print('actual:', batch[1])
sess.close()
将优化器更改为动量优化器以加快收敛速度: tf.train.AdamOptimizer(0.01).minimize(cost)
有很多方法可以提高神经网络的性能。 请尝试以下一项或多项措施:
你忘了添加偏见。
def init_bias(shape):
biases = tf.random_normal(shape)
return tf.Variable(biases)
def forwardprop(x, w_1, w_2, b_1, b_2):
""" Forward-propagation """
h = tf.nn.sigmoid(tf.matmul(x, w_1) + b_1)
y_predict = tf.matmul(h, w_2) + b_2
return y_predict
里面主要改变它到这个
w_1 = init_weights((x_size, h_1_size))
w_2 = init_weights((h_1_size, y_size))
b_1 = init_bias((h_1_size,))
b_2 = init_bias((y_size,))
# Forward propagation
y_predict = forwardprop(x, w_1, w_2, b_1, b_2)
这会给你更好的准确性。 然后,您可以尝试添加更多图层,尝试不同的激活功能,如上所述,以进一步改进。
链接地址: http://www.djcxy.com/p/5505.html上一篇: Simple Feedforward Neural Network with TensorFlow won't learn
下一篇: Multi layered perceptron in tensorflow not behaving as expected
