根据此链接,keep_prob的值必须介于(0,1]之间:
Tensorflow manual

否则我会得到值错误:

ValueError: If keep_prob is not in (0, 1] or if x is not a floating point tensor.


我将以下代码用于具有一个隐藏层的简单神经网络:

n_nodes_input = len(train_x.columns) # number of input features
n_nodes_hl = 30     # number of units in hidden layer
n_classes = len(np.unique(Y_train_numeric))
lr = 0.25
x = tf.placeholder('float', [None, len(train_x.columns)])
y = tf.placeholder('float')
dropout_keep_prob = tf.placeholder(tf.float32)

def neural_network_model(data, dropout_keep_prob):
    # define weights and biases for all each layer
    hidden_layer = {'weights':tf.Variable(tf.truncated_normal([n_nodes_input, n_nodes_hl], stddev=0.3)),
                      'biases':tf.Variable(tf.constant(0.1, shape=[n_nodes_hl]))}
    output_layer = {'weights':tf.Variable(tf.truncated_normal([n_nodes_hl, n_classes], stddev=0.3)),
                    'biases':tf.Variable(tf.constant(0.1, shape=[n_classes]))}
    # feed forward and activations
    l1 = tf.add(tf.matmul(data, hidden_layer['weights']), hidden_layer['biases'])
    l1 = tf.nn.sigmoid(l1)
    l1 = tf.nn.dropout(l1, dropout_keep_prob)
    output = tf.matmul(l1, output_layer['weights']) + output_layer['biases']

    return output

def main():
    prediction = neural_network_model(x, dropout_keep_prob)
    cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y,logits=prediction))
    optimizer = tf.train.AdamOptimizer(lr).minimize(cost)

    sess = tf.InteractiveSession()

    tf.global_variables_initializer().run()
    for epoch in range(1000):
        loss = 0
        _, c = sess.run([optimizer, cost], feed_dict = {x: train_x, y: train_y, dropout_keep_prob: 4.})
        loss += c

        if (epoch % 100 == 0 and epoch != 0):
            print('Epoch', epoch, 'completed out of', 1000, 'Training loss:', loss)
    correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
    accuracy = tf.reduce_mean(tf.cast(correct, tf.float32), name='op_accuracy')

    writer = tf.summary.FileWriter('graph',sess.graph)
    writer.close()

    print('Train set Accuracy:', sess.run(accuracy, feed_dict = {x: train_x, y: train_y, dropout_keep_prob: 1.}))
    print('Test set Accuracy:', sess.run(accuracy, feed_dict = {x: test_x, y: test_y, dropout_keep_prob: 1.}))
    sess.close()


if __name__ == '__main__':
     main()


如果对sess.run中的dropout_keep_prob使用范围(0,1]范围内的数字,则精度会急剧下降;如果使用大于1的数字(如4),则精度会超过0.9。
一旦我在tf.nn.dropout()前面使用shift + tab,它就会作为描述的一部分写入:

With probability `keep_prob`, outputs the input element scaled up by
`1 / keep_prob`, otherwise outputs `0`.  The scaling is so that the expected
sum is unchanged.


在我看来,keep_prob必须大于1,否则任何内容都不会丢失!

底线,我很困惑。我在辍学的哪个部分实施了错误的结果,我的结果变得最糟,而keep_drop的合适数字是多少?

谢谢

最佳答案

在我看来,keep_prob必须大于1,否则任何内容都不会丢失!


描述说:


  以概率keep_prob,输出按以下比例放大的输入元素
  1 / keep_prob,否则输出0。缩放比例应符合预期
  总和不变。


这意味着:


keep_prob用作概率,因此根据定义,它应始终位于[0, 1]中(超出该范围的数字永远不会是概率)
以概率keep_prob,输入元素乘以1 / keep_prob。既然我们已经写了0 <= keep_prob <= 1,则除法1 / keep_prob总是大于1.0(如果1.0则精确地为keep_prob == 1)。因此,以概率keep_prob,某些元素将变得比没有辍学的情况更大
对于概率为1 - keep_prob(描述中为“否则”),将元素设置为0。这是辍学,如果将元素设置为0,则会将其删除。如果将keep_prob精确设置为1.0,则意味着删除任何节点的概率变为0。因此,如果要删除某些节点,则应设置keep_prob < 1,而如果不想删除任何内容,则应设置keep_prob = 1


重要说明:您只想在训练期间使用辍学,而不是在测试期间使用。


  如果对sess.run中的dropout_keep_prob使用范围(0,1]范围内的数字,则准确性会急剧下降。


如果您要对测试集进行此操作,或者您是说要报告训练集的准确性,那并不会让我感到惊讶。辍学意味着丢失信息,因此确实会失去准确性。虽然这应该是一种正规化的方式。您有意在训练阶段失去准确性,但希望这样做可以提高泛化能力,并因此在测试阶段(无需再使用辍学者)改善准确性。


  如果我使用大于1的数字(如4),则精度将超过0.9。


我很惊讶您完全可以运行此代码。基于source code,我不希望它运行吗?

08-24 13:48