Skip to main content
 首页 » 编程设计

python之在 TensorFlow 中获取一个简单的 MLP 来对 XOR 进行建模

2024年10月24日36youxin

我尝试构建一个简单的 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) 

输出 第 27 行 (...) ValueError:尺寸 Dimension(2) 和 Dimension(5) 不兼容。将行更改为:

hidden = tf.sigmoid(tf.matmul(W_hidden, n_input) + b_hidden) 

似乎可以正常工作,但错误出现在:

output = tf.sigmoid(tf.matmul(hidden, W_output)) 

告诉我:第 34 行 (...) ValueError:尺寸 Dimension(2) 和 Dimension(5) 不兼容

将语句转换为:

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 隐藏仍然有效(我什至不明白为什么它在没有转置的情况下工作)。但是,output 不断抛出错误,但此维度操作应该是 (1, 5) x (5, 1)?!

请您参考如下方法:

(0) 包含错误输出很有帮助 - 它也是一个值得关注的东西,因为它确实可以准确识别您遇到形状问题的位置。

(1) 出现形状错误是因为您在两个 matmuls 中都将 matmul 的参数倒置,并且将 tf.Variable 倒置。一般规则是,具有input_size, output_size 的层的权重应该是[input_size, output_size],matmul 应该是tf.matmul(input_to_layer, weights_for_layer)(然后添加形状为 [output_size] 的偏差)。

所以用你的代码,

W_hidden = tf.Variable(tf.random_uniform([hidden_nodes, 2], -1.0, 1.0)) 

应该是:

W_hidden = tf.Variable(tf.random_uniform([2, hidden_nodes], -1.0, 1.0)) 

和

hidden = tf.sigmoid(tf.matmul(W_hidden, n_input) + b_hidden) 

应该是tf.matmul(n_input, W_hidden);和

output = tf.sigmoid(tf.matmul(W_output, hidden)) 

应该是tf.matmul(hidden, W_output)

(2) 一旦你修复了这些错误,你的运行需要输入一个 feed_dict:

sess.run(train) 

应该是:

sess.run(train, feed_dict={n_input: input_data})  

至少,我认为这是您要实现的目标。