python - 反向传播算法陷入训练 AND 函数的困境

标签 python machine-learning tensorflow neural-network

这是使用 tensorflow 的单个神经元的 AND 函数的实现:

def tf_sigmoid(x):
    return 1 / (1 + tf.exp(-x))

data = [
    (0, 0),
    (0, 1),
    (1, 0),
    (1, 1),
]

labels = [
    0,
    0,
    0,
    1,
]

n_steps = 1000
learning_rate = .1

x = tf.placeholder(dtype=tf.float32, shape=[2])
y = tf.placeholder(dtype=tf.float32, shape=None)

w = tf.get_variable('W', shape=[2], initializer=tf.random_normal_initializer(), dtype=tf.float32)
b = tf.get_variable('b', shape=[], initializer=tf.random_normal_initializer(), dtype=tf.float32)

h = tf.reduce_sum(x * w) + b
output = tf_sigmoid(h)

error = tf.abs(output - y)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(error)
sess.run(tf.initialize_all_variables())


for step in range(n_steps):
    for i in np.random.permutation(range(len(data))):
        sess.run(optimizer, feed_dict={x: data[i], y: labels[i]})

有时它工作得很好,但在某些参数上它会卡住并且不想学习。例如,使用这些初始参数:

w = tf.Variable(initial_value=[-0.31199348, -0.46391705], dtype=tf.float32)
b = tf.Variable(initial_value=-1.94877, dtype=tf.float32)

它几乎不会对成本函数做出任何改进。我做错了什么,也许我应该以某种方式调整参数的初始化?

最佳答案

您是否缺少一个平均值(错误)

您的问题是 sigmoid、成本函数和优化器的特定组合。

别难过,据我所知,这个问题让整个领域停滞了几年。

当您远离中间时,Sigmoid 是平坦的,并且您使用相对较大的数字来初始化它,请尝试/1000。

因此,您的绝对误差(或平方误差)也是平坦的,并且 GradientDescent 优化器采取与斜率成比例的步骤。

其中任何一个都可以修复它:

使用cross-entropy对于错误 - 它是凸的。

使用更好的优化器,例如 Adam ,步长对坡度的依赖要小得多。更多关于坡度一致性的信息。

奖励:不要使用自己的 sigmoid,使用 tf.nn.sigmoid ,这样你会得到更少的 NaN。

玩得开心!

关于python - 反向传播算法陷入训练 AND 函数的困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42614993/

相关文章:

python - 在 Visual Studio Code 中的同一项目文件夹中使用 python 包

python - 获取 NumPy 数组中多个索引处的元素

python - 使用重复嵌套模式从文本文件中提取文本

machine-learning - 二元分类

c++ - 构建 Tensorflow 调试时出错 LNK2019

python - plotly :如何摆脱多余的 xaxis 刻度?

python-3.x - XGBoost 最佳迭代

python - Keras 预测精度与训练精度不匹配

python - 为什么 SyntaxNet demo.sh 找不到正确的导入?

python - TensorFlow 与 skflow : AttributeError: 'module' object has no attribute 'saver_pb2'