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

标签 python numpy tensorflow machine-learning neural-network

我刚刚学习了神经网络教程,并试图将我的知识用于测试。我制作了一个简单的 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] 输出实际上更难。如果删除它,网络会收敛得更快。

关于python - Tensorflow 神经网络在训练后总是有 50% 的把握,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49687358/

相关文章:

python - 如何比较 tensorflow 中的张量?

python - 如何根据列到值的映射为 DataFrame 赋值?

python - 使用seaborn jointplot 绘制统一的背景颜色

python - 使用数组时无法解决 "List index out of range"错误

python - 在 Python 中将函数应用于 numpy 数组

python pandas dataframe单元格更新错误

Tensorflow tf.reshape : None/-1, 是一样的吗?

python - 将 matplotlib AxesImage 转换为 PIL PhotoImage,如何在 Tkinter 中绘制 matplotlib 结果

python - Numpy 数组转 PIL 图片格式

python - 如何使用 Tensorflow LSTM 获得预测的 future 跟随值?