Skip to main content
 首页 » 编程设计

python之Tensorflow 神经网络在训练后总是有 50% 的把握

2025年05月04日20grandyang

我刚刚学习了神经网络教程,并试图将我的知识用于测试。我制作了一个简单的 XOR 逻辑学习网络,但由于某种原因它总是返回 0.5(50% 确定)。这是我的代码:

import tensorflow as tf 
import numpy as np 
 
def random_normal(shape=1): 
    return (np.random.random(shape) - 0.5) * 2 
 
train_x = np.array([[1, 0], [0, 1], [1, 1], [0, 0]]) 
train_y = np.array([1, 1, 0, 0]) 
 
input_size = 2 
hidden_size = 16 
output_size = 1 
 
x = tf.placeholder(dtype=tf.float32, name="X") 
y = tf.placeholder(dtype=tf.float32, name="Y") 
 
W1 = tf.Variable(random_normal((input_size, hidden_size)), dtype=tf.float32, name="W1") 
W2 = tf.Variable(random_normal((hidden_size, output_size)), dtype=tf.float32, name="W2") 
 
b1 = tf.Variable(random_normal(hidden_size), dtype=tf.float32, name="b1") 
b2 = tf.Variable(random_normal(output_size), dtype=tf.float32, name="b2") 
 
l1 = tf.sigmoid(tf.add(tf.matmul(x, W1), b1), name="l1") 
result = tf.sigmoid(tf.add(tf.matmul(l1, W2), b2), name="l2") 
 
r_squared = tf.square(result - y) 
loss = tf.reduce_mean(r_squared) 
 
optimizer = tf.train.GradientDescentOptimizer(0.1) 
train = optimizer.minimize(loss) 
 
hm_epochs = 10000 
 
with tf.Session() as sess: 
    sess.run(tf.global_variables_initializer()) 
    for itr in range(hm_epochs): 
        sess.run(train, {x: train_x, y: train_y}) 
        if itr % 100 == 0: 
            print("Epoch {} done".format(itr)) 
    print(sess.run(result, {x: [[1, 0]]})) 

抱歉,如果这是一个糟糕的问题,我是机器学习的新手。

请您参考如下方法:

您的神经网络实际上是正确的,答案可能会让您大吃一惊。改变...

train_x = np.array([[1, 0], [0, 1], [1, 1], [0, 0]]) 
train_y = np.array([1, 1, 0, 0]) 

为了...

train_x = np.array([[1, 0], [0, 1], [1, 1], [0, 0]]).reshape((4, 2)) 
train_y = np.array([1, 1, 0, 0]).reshape((4, 1)) 

您可以检查 np.array([1, 1, 0, 0]).shape 是 (4,),而不是 (4, 1)。结果,y 的形状也变为 (4,) 因此 result - y 的形状为 (4 , 4)!换句话说,损失计算了 16 个与预测和标签的实际比较无关的差异。因此,我对 future 的建议是:始终明确指定占位符的形状,以便更容易地找到这些错误。

您可以在 this GitHub gist 中找到完整的代码我创建。 还有一点要注意:最后一个 sigmoid 使得学习 [0, 1] 输出实际上更难。如果删除它,网络会收敛得更快。