【问题标题】:Tensorflow Multi-layer perceptron graph won't convergeTensorflow 多层感知器图不会收敛
【发布时间】:2016-11-28 06:53:27
【问题描述】:

我是 python 和 tensorflow 的新手。在更好地(也许)理解 DNN 及其数学之后。我开始通过练习学习使用 tensorflow。

我的一个练习是预测 x^2。这意味着经过良好的训练。当我给出 5.0 时,它会预测 25.0。

参数及设置:

成本函数 = E((y-y')^2)

两个隐藏层,它们是完全连接的。

学习率 = 0.001

n_hidden_​​1 = 3

n_hidden_​​2 = 2

n_input = 1

n_output = 1

def multilayer_perceptron(x, weights, biases):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Hidden layer with RELU activation
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # Output layer with linear activation
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

def generate_input():
    import random

    val = random.uniform(-10000, 10000)
    return np.array([val]).reshape(1, -1), np.array([val*val]).reshape(1, -1)


# tf Graph input
# given one value and output one value
x = tf.placeholder("float", [None, 1])
y = tf.placeholder("float", [None, 1])
pred = multilayer_perceptron(x, weights, biases)

# Define loss and optimizer
distance = tf.sub(pred, y)
cost = tf.reduce_mean(tf.pow(distance, 2))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    avg_cost = 0.0

    for iter in range(10000):
        inp, ans = generate_input()
        _, c = sess.run([optimizer, cost], feed_dict={x: inp, y: ans})
        print('iter: '+str(iter)+' cost='+str(c))

然而,事实证明,c 有时会变大,有时会变小。 (但它很大)

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    由于val = random.uniform(-10000, 10000)的说法,您的训练数据范围似乎很大,请在训练之前尝试进行一些数据预处理。例如,

    val = random.uniform(-10000, 10000)
    val = np.asarray(val).reshape(1, -1)
    val -= np.mean(val, axis=0)
    val /= np.std(val, axis=0)
    

    至于损失值,有时它会变大,有时会变低是可以的,只要确保在训练时期一般增加时损失是减少的。 PS:我们经常使用 SGD 优化器。

    【讨论】:

    • 谢谢,我现在使用平均成本,我看到它下降了。我们应该扩展输入的原因是为了让成本函数更好地工作?我对吗?如果输入值范围太大。即使可以接受,成本也会变大。例如 100^2 = 10000,它预测 9800。成本将是 200^2。然而,改变成本函数需要改变优化器。到目前为止,这是我的理解。如果我错了,请纠正我
    • 是的,大价值需要更多时间才能收敛。而关于优化器,不同的代价函数可以使用同一个优化器,但一般我们为了简单起见选择SGD。
    猜你喜欢
    • 2018-10-05
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 2021-06-28
    • 2020-08-01
    • 2018-02-21
    • 2013-10-09
    相关资源
    最近更新 更多