【发布时间】:2016-05-11 14:52:32
【问题描述】:
以下代码用于学习 XOR 函数,但大约有一半的时间网络没有学习,并且每个 epoch 后的损失保持不变。
train_f = [[0, 0], [0, 1], [1, 0], [1, 1]]
train_c = [[0], [1], [1], [0]]
test_f = train_f
test_c = train_c
import tensorflow as tf
import tflearn
X = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]
Y_xor = [[0.], [1.], [1.], [0.]]
# Graph definition
with tf.Graph().as_default():
# Building a network with 2 optimizers
net = tflearn.input_data(shape=[None, 2])
# Nand operator definition
net = tflearn.fully_connected(net, 2, activation='relu')
net = tflearn.fully_connected(net, 2, activation='relu')
net = tflearn.fully_connected(net, 1, activation='sigmoid')
regressor = tflearn.regression(net, optimizer='adam', learning_rate=0.005, loss="mean_square",)
# Training
m = tflearn.DNN(regressor)
m.fit(X, Y_xor, n_epoch=256, snapshot_epoch=False)
# Testing
print("Testing XOR operator")
print("0 xor 0:", m.predict([[0., 0.]]))
print("0 xor 1:", m.predict([[0., 1.]]))
print("1 xor 0:", m.predict([[1., 0.]]))
print("1 xor 1:", m.predict([[1., 1.]]))
有时我会得到这样的正确结果:
Testing XOR operator
0 xor 0: [[0.1487255096435547]]
0 xor 1: [[0.9297153949737549]]
1 xor 0: [[0.9354135394096375]]
1 xor 1: [[0.1487255096435547]]
但通常是这样的:
Testing XOR operator
0 xor 0: [[0.4999997615814209]]
0 xor 1: [[0.5000002384185791]]
1 xor 0: [[0.4999997615814209]]
1 xor 1: [[0.5000001788139343]]
我的 2x2x1 网络应该能够执行 XOR,甚至有一些证据表明这个网络应该总是收敛 http://www.ncbi.nlm.nih.gov/pubmed/12662805
我也试过把relu层改成sigmoid,进行2048次迭代,做成4x4x1和6x6x1的网络,但是有时候还是会出现同样的问题。
权重的初始化方式可能有问题吗? 如何使用 tflearn 让神经网络学习 xor 函数?
【问题讨论】:
-
尝试普通的 SGD(而不是 Adam),调整学习率...
-
不幸的是,SGD 没有帮助(使用任何激活函数)
标签: python machine-learning tensorflow deep-learning