我已經用Google的TensorFlow庫構建了MLP。網絡正在工作,但不知何故它拒絕正確學習。無論輸入的是什麼,它總是收斂到接近1.0的輸出。TensorFlow MLP不訓練XOR
完整代碼可以看到here。
任何想法?
的輸入和輸出(批次大小4)如下:
input_data = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]] # XOR input
output_data = [[0.], [1.], [1.], [0.]] # XOR output
n_input = tf.placeholder(tf.float32, shape=[None, 2], name="n_input")
n_output = tf.placeholder(tf.float32, shape=[None, 1], name="n_output")
隱藏層配置:
# hidden layer's bias neuron
b_hidden = tf.Variable(0.1, name="hidden_bias")
# hidden layer's weight matrix initialized with a uniform distribution
W_hidden = tf.Variable(tf.random_uniform([2, hidden_nodes], -1.0, 1.0), name="hidden_weights")
# calc hidden layer's activation
hidden = tf.sigmoid(tf.matmul(n_input, W_hidden) + b_hidden)
輸出層配置:
W_output = tf.Variable(tf.random_uniform([hidden_nodes, 1], -1.0, 1.0), name="output_weights") # output layer's weight matrix
output = tf.sigmoid(tf.matmul(hidden, W_output)) # calc output layer's activation
我學習方法是這樣的:
loss = tf.reduce_mean(cross_entropy) # mean the cross_entropy
optimizer = tf.train.GradientDescentOptimizer(0.01) # take a gradient descent for optimizing
train = optimizer.minimize(loss) # let the optimizer train
我都嘗試設置爲交叉熵:
cross_entropy = -tf.reduce_sum(n_output * tf.log(output))
和
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(n_output, output)
其中n_output
是如在我的網絡output_data
和output
預測/計算值描述的原始輸出。
的培訓內部的for循環(n個時期)是這樣的:
cvalues = sess.run([train, loss, W_hidden, b_hidden, W_output],
feed_dict={n_input: input_data, n_output: output_data})
我節省了成果cvalues爲loss
,W_hidden
調試printig,...
無論我嘗試過什麼,當我測試我的網絡時,試圖驗證輸出,它總是產生一些東西E本:
(...)
step: 2000
loss: 0.0137040186673
b_hidden: 1.3272010088
W_hidden: [[ 0.23195425 0.53248233 -0.21644847 -0.54775208 0.52298909]
[ 0.73933059 0.51440752 -0.08397482 -0.62724304 -0.53347367]]
W_output: [[ 1.65939867]
[ 0.78912479]
[ 1.4831928 ]
[ 1.28612828]
[ 1.12486529]]
(--- finished with 2000 epochs ---)
(Test input for validation:)
input: [0.0, 0.0] | output: [[ 0.99339396]]
input: [0.0, 1.0] | output: [[ 0.99289012]]
input: [1.0, 0.0] | output: [[ 0.99346077]]
input: [1.0, 1.0] | output: [[ 0.99261558]]
所以不是學習方法不當,但總是收斂到接近1.0無論哪個輸入饋。
你'b_hidden'變量是一個標量 - 是故意的嗎?我認爲你應該把它創建爲'b_hidden = tf.Variable(tf.constant(0.1,shape = [hidden_nodes]),name =「hidden_bias」)',這可能會有所幫助。另一個嘗試的方法是在輸出層中添加一個「b_output」偏差項。 – mrry
感謝您的評論。事實上,我只是沒有注意到'b_hidden'應該也是一個矢量,而不是一個標量......但是,對於每個輸入,有或沒有隱藏的偏差,網絡仍然收斂到將近1.0,作爲標量或矢量,或者對輸出層沒有偏差。我真的認爲我錯過了學習方法或網絡體系結構中的一些錯誤:/ – daniel451