张流精度为.99但预测很糟糕

时间:2016-06-18 15:43:49

标签: python machine-learning neural-network artificial-intelligence tensorflow

也许我的预测错了?

这是项目...我有一个灰度输入图像,我试图分割。分段是一个简单的二元分类(考虑前景与背景)。因此,基本事实(y)是0和1的矩阵 - 因此有2个分类。哦,输入图像是正方形,所以我只使用一个名为n_input

的变量

我的准确度基本上收敛到0.99但是当我做出预测时,我得到全部为零。 编辑 - > 每个输出矩阵中只有一个,都在同一个地方......

这是我的会话代码(其他一切正常)......

with tf.Session() as sess:
    sess.run(init)
    summary = tf.train.SummaryWriter('/tmp/logdir/', sess.graph_def)
    step = 1
    from tensorflow.contrib.learn.python.learn.datasets.scroll import scroll_data
    data = scroll_data.read_data('/home/kendall/Desktop/')
    # Keep training until reach max iterations
    flag = 0
    # while flag == 0:
    while step * batch_size < training_iters:
        batch_y, batch_x = data.train.next_batch(batch_size)
        # pdb.set_trace()
        # batch_x = batch_x.reshape((batch_size, n_input))
        batch_x = batch_x.reshape((batch_size, n_input, n_input))
        batch_y = batch_y.reshape((batch_size, n_input, n_input))
        batch_y = convert_to_2_channel(batch_y, batch_size)
        # batch_y = batch_y.reshape((batch_size, n_output, n_classes))
        batch_y = batch_y.reshape((batch_size, 200, 200, n_classes))
        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,
                                       keep_prob: dropout})
        if step % display_step == 0:
            flag = 1
            # Calculate batch loss and accuracy
            loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
                                                              y: batch_y,
                                                              keep_prob: 1.})
            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                  "{:.6f}".format(loss) + ", Training Accuracy= " + \
                  "{:.5f}".format(acc)
        step += 1
    print "Optimization Finished!"
    save_path = "model.ckpt"
    saver.save(sess, save_path)

    im = Image.open('/home/kendall/Desktop/HA900_frames/frame0635.tif')
    batch_x = np.array(im)
    pdb.set_trace()
    batch_x = batch_x.reshape((1, n_input, n_input))
    batch_x = batch_x.astype(float)
    # pdb.set_trace()
    prediction = sess.run(pred, feed_dict={x: batch_x, keep_prob: 1.})
    print prediction
    arr1 = np.empty((n_input,n_input))
    arr2 = np.empty((n_input,n_input))
    for i in xrange(n_input):
        for j in xrange(n_input):
            for k in xrange(2):
                if k == 0:
                    arr1[i][j] = prediction[0][i][j][k]
                else:
                    arr2[i][j] = prediction[0][i][j][k]
    # prediction = np.asarray(prediction)
    # prediction = np.reshape(prediction, (200,200))
    # np.savetxt("prediction.csv", prediction, delimiter=",")
    np.savetxt("prediction1.csv", arr1, delimiter=",")
    np.savetxt("prediction2.csv", arr2, delimiter=",")

由于有两个分类,那个结束部分(带有几个循环)只是将预测分成两个2x2矩阵。

我将预测数组保存到CSV文件中,就像我说的那样,它们都是零。

我还确认所有数据都是正确的(尺寸和值)。

为什么训练会收敛,但预测很糟糕?

如果你想查看所有代码,这里是......

import tensorflow as tf
import pdb
import numpy as np
from numpy import genfromtxt
from PIL import Image

# Import MINST data
# from tensorflow.examples.tutorials.mnist import input_data
# mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)


# Parameters
learning_rate = 0.001
training_iters = 20000
batch_size = 128
display_step = 1

# Network Parameters
n_input = 200 # MNIST data input (img shape: 28*28)
n_output = 40000 # MNIST total classes (0-9 digits)
n_classes = 2
#n_input = 200

dropout = 0.75 # Dropout, probability to keep units

# tf Graph input
x = tf.placeholder(tf.float32, [None, n_input, n_input])
y = tf.placeholder(tf.float32, [None, n_input, n_input, n_classes])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)

# 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')


# Create model
def conv_net(x, weights, biases, dropout):
    # Reshape input picture
    x = tf.reshape(x, shape=[-1, n_input, n_input, 1])

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

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

    # Convolution Layer
    conv3 = conv2d(conv2, weights['wc3'], biases['bc3'])
    # Max Pooling (down-sampling)
    conv3 = tf.nn.local_response_normalization(conv3)
    conv3 = maxpool2d(conv3, k=2)

    # pdb.set_trace()

    # Fully connected layer
    # Reshape conv2 output to fit fully connected layer input
    fc1 = tf.reshape(conv3, [-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 = []
    for i in xrange(2):
        output.append(tf.nn.softmax(tf.add(tf.matmul(fc1, weights['out']), biases['out'])))

    return output
    # return tf.nn.softmax(tf.add(tf.matmul(fc1, weights['out']), biases['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])),
    # 5x5 conv, 32 inputs, 64 outputs
    'wc3': tf.Variable(tf.random_normal([5, 5, 64, 128])),
    # fully connected, 7*7*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([25*25*128, 1024])),
    # 1024 inputs, 10 outputs (class prediction)
    'out': tf.Variable(tf.random_normal([1024, n_output]))
}

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

# Construct model
pred = conv_net(x, weights, biases, keep_prob)
# pdb.set_trace()
pred = tf.pack(tf.transpose(pred,[1,2,0]))
pred = tf.reshape(pred, [-1,n_input,n_input,n_classes])
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

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

# Initializing the variables
init = tf.initialize_all_variables()
saver = tf.train.Saver()

def convert_to_2_channel(x, batch_size):
    #assume input has dimension (batch_size,x,y)
    #output will have dimension (batch_size,x,y,2)
    output = np.empty((batch_size, 200, 200, 2))

    temp_arr1 = np.empty((batch_size, 200, 200))
    temp_arr2 = np.empty((batch_size, 200, 200))

    for i in xrange(batch_size):
        for j in xrange(200):
            for k in xrange(200):
                if x[i][j][k] == 1:
                    temp_arr1[i][j][k] = 1
                    temp_arr2[i][j][k] = 0
                else:
                    temp_arr1[i][j][k] = 0
                    temp_arr2[i][j][k] = 1

    for i in xrange(batch_size):
        for j in xrange(200):
            for k in xrange(200):
                for l in xrange(2):
                    if l == 0:
                        output[i][j][k][l] = temp_arr1[i][j][k]
                    else:
                        output[i][j][k][l] = temp_arr2[i][j][k]

    return output

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    summary = tf.train.SummaryWriter('/tmp/logdir/', sess.graph_def)
    step = 1
    from tensorflow.contrib.learn.python.learn.datasets.scroll import scroll_data
    data = scroll_data.read_data('/home/kendall/Desktop/')
    # Keep training until reach max iterations
    flag = 0
    # while flag == 0:
    while step * batch_size < training_iters:
        batch_y, batch_x = data.train.next_batch(batch_size)
        # pdb.set_trace()
        # batch_x = batch_x.reshape((batch_size, n_input))
        batch_x = batch_x.reshape((batch_size, n_input, n_input))
        batch_y = batch_y.reshape((batch_size, n_input, n_input))
        batch_y = convert_to_2_channel(batch_y, batch_size)
        # batch_y = batch_y.reshape((batch_size, n_output, n_classes))
        batch_y = batch_y.reshape((batch_size, 200, 200, n_classes))
        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,
                                       keep_prob: dropout})
        if step % display_step == 0:
            flag = 1
            # Calculate batch loss and accuracy
            loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
                                                              y: batch_y,
                                                              keep_prob: 1.})
            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                  "{:.6f}".format(loss) + ", Training Accuracy= " + \
                  "{:.5f}".format(acc)
        step += 1
    print "Optimization Finished!"
    save_path = "model.ckpt"
    saver.save(sess, save_path)

    im = Image.open('/home/kendall/Desktop/HA900_frames/frame0635.tif')
    batch_x = np.array(im)
    pdb.set_trace()
    batch_x = batch_x.reshape((1, n_input, n_input))
    batch_x = batch_x.astype(float)
    # pdb.set_trace()
    prediction = sess.run(pred, feed_dict={x: batch_x, keep_prob: 1.})
    print prediction
    arr1 = np.empty((n_input,n_input))
    arr2 = np.empty((n_input,n_input))
    for i in xrange(n_input):
        for j in xrange(n_input):
            for k in xrange(2):
                if k == 0:
                    arr1[i][j] = prediction[0][i][j][k]
                else:
                    arr2[i][j] = prediction[0][i][j][k]
    # prediction = np.asarray(prediction)
    # prediction = np.reshape(prediction, (200,200))
    # np.savetxt("prediction.csv", prediction, delimiter=",")
    np.savetxt("prediction1.csv", arr1, delimiter=",")
    np.savetxt("prediction2.csv", arr2, delimiter=",")

    # Calculate accuracy for 256 mnist test images
    print "Testing Accuracy:", \
        sess.run(accuracy, feed_dict={x: data.test.images[:256],
                                      y: data.test.labels[:256],
                                      keep_prob: 1.})

1 个答案:

答案 0 :(得分:7)

代码中的错误

您的代码中存在多个错误:

  

警告:此操作需要未缩放的日志,因为它会在内部执行logmax以提高效率。不要使用softmax的输出调用此op,因为它会产生不正确的结果。

  • 事实上,因为你有两个课程,你应该使用softmax使用tf.nn.softmax_cross_entropy_with_logits

  • 使用tf.argmax(pred, 1)时,只在轴1上应用argmax,这是输出图像的高度。您应该在最后一个轴(大小为2)上使用tf.argmax(pred, 3)

    • 这可以解释为什么你得到0.99准确度
    • 在输出图像上,argmax将超过图像的高度,默认为0(因为每个通道的所有值都相等)

错误的模型

最大的缺点是您的模型通常会非常难以进行优化。

  • 你有超过40,000个类的softmax,这是巨大的。
  • 您不想利用想要输出图像的事实(预测前景/背景)。
    • 例如预测2,345与预测2,346和预测2,545高度相关但你不考虑这一点

我建议先阅读一些关于语义分割的内容:

  • this paper:用于语义分割的完全卷积网络
  • 来自CS231n(斯坦福大学)的
  • these slides:特别是关于上采样和反卷积的部分

推荐

如果您想使用TensorFlow,则需要从小处开始。首先尝试一个非常简单的网络,可能有1个隐藏层。

您需要绘制张量的所有形状,以确保它们符合您的想法。例如,如果您绘制了tf.argmax(y, 1),那么您就会意识到形状为[batch_size, 200, 2]而不是预期的[batch_size, 200, 200]

TensorBoard是你的朋友,你应该尝试在这里绘制输入图像,以及你的预测,看看它们是什么样的。

尝试使用10个图像的非常小的数据集,然后查看是否可以过度拟合并预测几乎所有的响应。

总而言之,我不确定我的所有建议,但他们值得尝试,我希望这会帮助你走向成功之路!