【发布时间】:2016-03-02 21:32:35
【问题描述】:
我尝试构建一个简单的 MLP,其中包含一个输入层(2 个神经元)、一个隐藏层(5 个神经元)和一个输出层(1 个神经元)。我计划用[[0., 0.], [0., 1.], [1., 0.], [1., 1.]] 对其进行训练和喂养,以获得[0., 1., 1., 0.] 的所需输出(按元素)。
不幸的是,我的代码拒绝运行。无论我尝试什么,我都会不断收到维度错误。非常令人沮丧:/ 我想我遗漏了一些东西,但我不知道出了什么问题。
为了更好的可读性,我还将代码上传到了一个 pastebin:code
有什么想法吗?
import tensorflow as tf
#####################
# preparation stuff #
#####################
# define input and output data
input_data = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]] # XOR input
output_data = [0., 1., 1., 0.] # XOR output
# create a placeholder for the input
# None indicates a variable batch size for the input
# one input's dimension is [1, 2]
n_input = tf.placeholder(tf.float32, shape=[None, 2])
# number of neurons in the hidden layer
hidden_nodes = 5
################
# hidden layer #
################
b_hidden = tf.Variable(0.1) # hidden layer's bias neuron
W_hidden = tf.Variable(tf.random_uniform([hidden_nodes, 2], -1.0, 1.0)) # hidden layer's weight matrix
# initialized with a uniform distribution
hidden = tf.sigmoid(tf.matmul(W_hidden, n_input) + b_hidden) # calc hidden layer's activation
################
# output layer #
################
W_output = tf.Variable(tf.random_uniform([hidden_nodes, 1], -1.0, 1.0)) # output layer's weight matrix
output = tf.sigmoid(tf.matmul(W_output, hidden)) # calc output layer's activation
############
# learning #
############
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(output, n_input) # calc cross entropy between current
# output and desired output
loss = tf.reduce_mean(cross_entropy) # mean the cross_entropy
optimizer = tf.train.GradientDescentOptimizer(0.1) # take a gradient descent for optimizing with a "stepsize" of 0.1
train = optimizer.minimize(loss) # let the optimizer train
####################
# initialize graph #
####################
init = tf.initialize_all_variables()
sess = tf.Session() # create the session and therefore the graph
sess.run(init) # initialize all variables
# train the network
for epoch in xrange(0, 201):
sess.run(train) # run the training operation
if epoch % 20 == 0:
print("step: {:>3} | W: {} | b: {}".format(epoch, sess.run(W_hidden), sess.run(b_hidden)))
编辑:我仍然收到错误:/
hidden = tf.sigmoid(tf.matmul(n_input, W_hidden) + b_hidden)
输出line 27 (...) ValueError: Dimensions Dimension(2) and Dimension(5) are not compatible。将行更改为:
hidden = tf.sigmoid(tf.matmul(W_hidden, n_input) + b_hidden)
似乎工作正常,但随后错误出现在:
output = tf.sigmoid(tf.matmul(hidden, W_output))
告诉我:line 34 (...) ValueError: Dimensions Dimension(2) and Dimension(5) are not compatible
将语句转换为:
output = tf.sigmoid(tf.matmul(W_output, hidden))
也抛出异常:line 34 (...) ValueError: Dimensions Dimension(1) and Dimension(5) are not compatible。
EDIT2:我不太明白这一点。 hidden 不应该是 W_hidden x n_input.T,因为在维度上这将是 (5, 2) x (2, 1)?如果我转置n_input hidden 仍在工作(我什至不明白为什么它在没有转置的情况下工作)。但是,output 不断抛出错误,但是这个维度上的操作应该是 (1, 5) x (5, 1)?!
【问题讨论】:
标签: python machine-learning neural-network xor tensorflow