Tensorflow训练CNN但准确性不变

时间:2017-11-01 01:55:17

标签: tensorflow

第一步 First train step

第二步 Second step

第三步 Third step

第四步 Fourth step

损失逐渐下降。 但准确率始终在50%左右。

# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
    # Conv2D wrapper, with bias and relu activation
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

def maxpool2d(x, k=2):
    # MaxPool2D wrapper
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
                          padding='SAME')

def conv_net(x, weights, biases, dropout):
    # Tensor input become 4-D: [Batch Size, Height, Width, Channel]

    # Convolution Layer
    conv1 = conv2d(x, weights['wc1'], biases['bc1'])
    # Max Pooling (down-sampling)
    conv1 = maxpool2d(conv1, k=2)

    # Convolution Layer
    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
    # Max Pooling (down-sampling)
    conv2 = maxpool2d(conv2, k=2)

    # Fully connected layer
    # Reshape conv2 output to fit fully connected layer input
    fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
    fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
    fc1 = tf.nn.relu(fc1)
    # Apply Dropout
    fc1 = tf.nn.dropout(fc1, dropout)

    # Output, class prediction
    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
    return out

# Store layers weight & bias
weights = {
    # 5x5 conv, 1 input, 32 outputs
    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
    # 5x5 conv, 32 inputs, 64 outputs
    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
    # fully connected, 7*7*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
    # 1024 inputs, 10 outputs (class prediction)
    'out': tf.Variable(tf.random_normal([1024, num_classes]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([32])),
    'bc2': tf.Variable(tf.random_normal([64])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([num_classes]))
}

# Construct model
logits = conv_net(X, weights, biases, keep_prob)
prediction = tf.nn.softmax(logits)

# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss_op)


# Evaluate model
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()

#Saver use to store the model
saver = tf.train.Saver() 

from sklearn.model_selection import train_test_split

# Start training
with tf.Session() as sess:

    # Run the initializer
    sess.run(init)

    for epoch in range(1, numOfEpoch):
        train_x, val_x, train_y, val_y = train_test_split(Input, Labels, test_size = 0.1)   

        for i in range(0, len(train_x), batch_size):
            trainLoss, _ = sess.run([loss_op, optimizer], feed_dict = {
                X: train_x[i: i+batch_size],
                Y: train_y[i: i+batch_size],
                keep_prob: dropout
            })
            if i % 5 == 0:
                print("The step is in "+ str(i)+ " step")

        valAcc, valLoss = sess.run([accuracy, loss_op], feed_dict={
            X: val_x,
            Y: val_y,
            keep_prob: 1.0})

        print("Step " + str(epoch) + ", Minibatch Loss= " + \
                  "{:.4f}".format(valLoss) + ", Training Accuracy= " + \
                  "{:.3f}".format(valAcc))

    print("Optimization Finished!")
    saver.save(sess, "../model.ckpt")  

以上是整个代码。 图像为[28 * 28 * 1]

图像的预处理是标准化。

在每个时代,损失总是在减少。在断断续续的时代之后,损失接近0.72。 但准确度仍然在50%左右。当参数初始化时,精度已经在50%左右。在火车上它永远不会改变很多。

预测中也有一些奇怪的事情。因为预测的输出接近1和0,而不是1和0之间的浮点值。

1 个答案:

答案 0 :(得分:0)

当我将初始化程序更改为xavier初始化程序时。 这似乎很正常。