hhw9307
hhw9307
2017-09-12 09:11

用python和tensorflow构建神经网络学习XOR函数

  • python
  • 神经网络

构建2层来学习XOR函数,但是学习结果无论调试多少次一直都无法学习到正确结果。

 import tensorflow as tf
import numpy as np

def add_layer(inputs,in_size,out_size,activation_function=None):  
    Weights = tf.Variable(tf.random_normal([in_size,out_size]))  
    biases = tf.Variable(tf.zeros([1,out_size])) + 0.1 
    #biases=tf.constant(0.1,dtype='float32')
    Wx_plus_b = tf.matmul(inputs,Weights) + biases  
    if activation_function is None:  
        outputs = Wx_plus_b  
    else:  
        outputs = activation_function(Wx_plus_b)  
    return outputs,Weights,biases

X=np.array([[0,0],[1,0],[0,1],[1,1]],dtype=np.float32)
Y=np.array([[0,],[1,],[1,],[0,]],dtype=np.float32)

prediction1,w1,b1=add_layer(X,2,2,activation_function=tf.nn.relu)
prediction2,w2,b2=add_layer(prediction1,2,1,activation_function=tf.nn.sigmoid)
loss=tf.reduce_mean(tf.reduce_sum(tf.square(prediction2-Y),axis=1))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(1000):
    sess.run(train_step)
    #print(sess.run(tf.nn.sigmoid(tf.matmul(tf.matmul(X,sess.run(w1))+b1,w2)+b2)))
print(sess.run(prediction2))

以下是我的输出结果,与[0,1,1,0]相差甚远!
图片说明

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐

换一换