Machine learning 为什么不断初始化的CNN会学习呢?

Machine learning 为什么不断初始化的CNN会学习呢?,machine-learning,tensorflow,conv-neural-network,gradient-descent,mnist,Machine Learning,Tensorflow,Conv Neural Network,Gradient Descent,Mnist,通常,神经网络的权值是随机初始化的,以便它们接收不同的梯度并学习不同的权值。理论上,如果所有权重都以相同的方式初始化,则无论训练多长时间,所有节点都将具有相同的权重。因此,培训根本不应该起作用 然而,以下代码给出了7000个时代后MNIST的56%准确率。为什么会这样 代码 阴谋 Nr 1 将10**-7添加到tf.log(..)术语后,NAN消失: Nr 2 这是一个旧的绘图,在16k个纪元之后,由于log(0)而出现问题 损失在这里标出。三角形是南边 这是精度-由于平滑,精度不会直接下

通常,神经网络的权值是随机初始化的,以便它们接收不同的梯度并学习不同的权值。理论上,如果所有权重都以相同的方式初始化,则无论训练多长时间,所有节点都将具有相同的权重。因此,培训根本不应该起作用

然而,以下代码给出了7000个时代后MNIST的56%准确率。为什么会这样

代码 阴谋 Nr 1 将
10**-7
添加到
tf.log(..)
术语后,NAN消失:

Nr 2 这是一个旧的绘图,在16k个纪元之后,由于
log(0)
而出现问题

损失在这里标出。三角形是南边

这是精度-由于平滑,精度不会直接下降到~10%


tf.log
中添加一个小epsilon,这是
NaN
problem@Kh40tiK非常感谢。我修正了:-)你能获取卷积核的实际值来验证它们的权重是否完全相似吗?在标准(小批量)梯度下降的情况下,你的直觉是正确的。你用的是亚当,这是自适应的。尝试用GradientDescentOptimizer重新绘制adam,你的直觉将得到验证。你必须“打破对称”。当层大小=1时,查看结果。向
tf.log
添加一个小ε,这是
NaN
的可能解决方案之一problem@Kh40tiK非常感谢。我修正了:-)你能获取卷积核的实际值来验证它们的权重是否完全相似吗?在标准(小批量)梯度下降的情况下,你的直觉是正确的。你用的是亚当,这是自适应的。尝试用GradientDescentOptimizer重新绘制adam,你的直觉将得到验证。你必须“打破对称”。查看图层大小=1时的结果。
#!/usr/bin/env python

"""MNIST with Tensorflow."""

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

import os
import numpy as np

epochs = 20000
model_checkpoint_path = 'checkpoints/mnist_tf_model.ckpt'


def weight_variable(shape):
    #initial = tf.truncated_normal(shape, stddev=0.01)
    initial = tf.constant(0.0, shape=shape)
    return tf.get_variable(initializer=initial, name='weights')


def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.get_variable(initializer=initial, name='biases')


def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                          strides=[1, 2, 2, 1], padding='SAME')


def eval_network(sess, summary_writer, dataset, correct_prediction, epoch):
    correct_sum = 0
    total_test = 0
    training_summary = tf.get_default_graph().get_tensor_by_name("training_accuracy:0")
    loss_summary = tf.get_default_graph().get_tensor_by_name("loss:0")
    for i in range(dataset.labels.shape[0] / 1000):
        feed_dict = {x: dataset.images[i * 1000:(i + 1) * 1000],
                     y_: dataset.labels[i * 1000:(i + 1) * 1000]}

        [test_correct, train_summ, loss_summ] = sess.run([correct_prediction,
                                                          training_summary,
                                                          loss_summary],
                                                         feed_dict=feed_dict)
        summary_writer.add_summary(train_summ, epoch)
        summary_writer.add_summary(loss_summ, epoch)
        test_correct = correct_prediction.eval(feed_dict=feed_dict)
        correct_sum += sum(test_correct)
        total_test += len(test_correct)
    return float(correct_sum) / total_test


def log_score(sess, summary_writer, filename, mnist, scoring, epoch):
    with open(filename, "a") as myfile:
        train = eval_network(sess, summary_writer, mnist.train, scoring, epoch)
        test = eval_network(sess, summary_writer, mnist.test, scoring, epoch)
        myfile.write("%i;%0.6f;%0.6f\n" % (epoch, train, test))


mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

with tf.Session() as sess:
    x = tf.placeholder(tf.float32, shape=[None, 784])
    y_ = tf.placeholder(tf.float32, shape=[None, 10])
    x_image = tf.reshape(x, [-1, 28, 28, 1])

    with tf.variable_scope('conv1') as scope:
        W_conv1 = weight_variable([5, 5, 1, 32])
        b_conv1 = bias_variable([32])
        h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1, name='ReLU1')
    h_pool1 = max_pool_2x2(h_conv1)

    with tf.variable_scope('conv2') as scope:
        W_conv2 = weight_variable([5, 5, 32, 64])
        b_conv2 = bias_variable([64])
        h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2, name='ReLU2')
    h_pool2 = max_pool_2x2(h_conv2)

    with tf.variable_scope('fc1'):
        W_fc1 = weight_variable([7 * 7 * 64, 1024])
        b_fc1 = bias_variable([1024])

        h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
        h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

    with tf.variable_scope('softmax'):
        W_fc2 = weight_variable([1024, 10])
        b_fc2 = bias_variable([10])

        y_conv = tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)

    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv * 10**-7),
                                                  reduction_indices=[1]))
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    tf.scalar_summary("training_accuracy", accuracy, name="training_accuracy")
    tf.scalar_summary("loss", cross_entropy, name="loss")

    summary_writer = tf.train.SummaryWriter('summary_dir', sess.graph)

    sess.run(tf.initialize_all_variables())

    for i in range(epochs):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            log_score(sess, summary_writer,
                      'validation-curve-accuracy.csv',
                      mnist, correct_prediction, i)
        train_step.run(feed_dict={x: batch[0],
                                  y_: batch[1]})

    log_score(sess, summary_writer, 'validation-curve-accuracy.csv',
              mnist, correct_prediction, epochs)