多个独立标签的费用和激活功能

时间:2016-01-05 13:48:01

标签: machine-learning computer-vision tensorflow tensorboard

在完成mnist / cifar教程之后,我想我会通过制作我自己的“大”数据来试验张量流,为了简单起见,我选择了一个黑白色的椭圆形,改变了它的高度和宽度独立地以0.0-1.0的比例作为28x28像素图像(其中我有5000个训练图像,1000个测试图像)。

我的代码使用'MNIST expert'教程作为基础(缩减速度),但我切换了基于平方误差的成本函数,并根据here的建议交换了sigmoid函数对于最终激活层,假设这不是分类,而是两个张量之间的“最佳拟合”,y_和y_conv。

然而,在> 100k迭代的过程中,损耗输出迅速进入400到900之间的振荡(或者因此,在50个批次中,2个标签上的任何给定标签的平均值为0.2-0.3),所以我想象我只是在吵闹。也许我错了,但我希望使用Tensorflow来卷积图像,以推断出可能有10个或更多独立标记的变量。我错过了一些基本的东西吗?

def train(images, labels):

# Import data
oval = blender_input_data.read_data_sets(images, labels)

sess = tf.InteractiveSession()

# Establish placeholders
x = tf.placeholder("float", shape=[None, 28, 28, 1])
tf.image_summary('images', x)
y_ = tf.placeholder("float", shape=[None, 2])

# Functions for Weight Initialization.

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

# Functions for convolution and pooling

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

# First Variables

W_conv1 = weight_variable([5, 5, 1, 16])
b_conv1 = bias_variable([16])

# First Convolutional Layer.
h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
_ = tf.histogram_summary('weights 1', W_conv1)
_ = tf.histogram_summary('biases 1', b_conv1)

# Second Variables
W_conv2 = weight_variable([5, 5, 16, 32])
b_conv2 = bias_variable([32])

# Second Convolutional Layer
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
_ = tf.histogram_summary('weights 2', W_conv2)
_ = tf.histogram_summary('biases 2', b_conv2)

# Fully connected Variables
W_fc1 = weight_variable([7 * 7 * 32, 512])
b_fc1 = bias_variable([512])

# Fully connected Layer
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*32])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1)+b_fc1)
_ = tf.histogram_summary('weights 3', W_fc1)
_ = tf.histogram_summary('biases 3', b_fc1)

# Drop out to reduce overfitting
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# Readout layer with sigmoid activation function.
W_fc2 = weight_variable([512, 2])
b_fc2 = bias_variable([2])

with tf.name_scope('Wx_b'):
    y_conv=tf.sigmoid(tf.matmul(h_fc1_drop, W_fc2)+b_fc2)
    _ = tf.histogram_summary('weights 4', W_fc2)
    _ = tf.histogram_summary('biases 4', b_fc2)
    _ = tf.histogram_summary('y', y_conv)

# Loss with squared errors
with tf.name_scope('diff'):
    error = tf.reduce_sum(tf.abs(tf.sub(y_,y_conv)))
    diff = (error*error)
    _ = tf.scalar_summary('diff', diff)

# Train
with tf.name_scope('train'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(diff)

# Merge summaries and write them out.
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter('/home/user/TBlogs/oval_logs', sess.graph_def)

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Launch the session.
sess.run(tf.initialize_all_variables())

# Restore variables from disk.
saver.restore(sess, "/home/user/TBlogs/model.ckpt")


for i in range(100000):

    batch = oval.train.next_batch(50)
    t_batch = oval.test.next_batch(50)

    if i%10 == 0:
        feed = {x:t_batch[0], y_: t_batch[1], keep_prob: 1.0}
        result = sess.run([merged, diff], feed_dict=feed)
        summary_str = result[0]
        df = result[1]

        writer.add_summary(summary_str, i)
        print('Difference:%s' % (df)
    else:
        feed = {x:batch[0], y_: batch[1], keep_prob: 0.5}
        sess.run(train_step, feed_dict=feed)

    if i%1000 == 0:
        save_path = saver.save(sess, "/home/user/TBlogs/model.ckpt")

# Completion
print("Session Done")

我最担心张量板似乎表明权重几乎没有变化,即使经过数小时的训练和衰减的学习率(尽管代码中没有显示)。我对机器学习的理解是,在对图像进行卷积时,这些层实际上构成了边缘检测的层次......所以我很困惑为什么它们几乎不会改变。

我的理论目前是:
我忽视/误解了有关损失功能的事情 我误解了权重的初始化和更新方式 3.我严重低估了这个过程应该花多长时间......虽然损失似乎只是在摆动。

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

从我所看到的,您的成本函数不是通常的均方误差 您正在优化tf.reduce_sum(tf.abs(tf.sub(y_,y_conv)))平方。该函数在0中不可微分(它是l1范数的平方)。这可能会导致一些稳定性问题(特别是在反向传播步骤中,我不知道它们在这种情况下使用何种子梯度)。

通常的均方误差可写为

residual = tf.sub(y_, y_conv)
error = tf.reduce_mean(tf.reduce_sum(residual*residual, reduction_indices=[1]))

(使用均值和求和是为了避免值取决于批量大小)。这是可以区分的,应该会给你更好的行为。