5

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

我的代码使用“MNIST 专家”教程作为基础(按比例缩小以提高速度),但我切换了基于平方误差的成本函数,并根据此处的建议,将 sigmoid 函数换成了最终激活层,因为这不是分类,而是两个张量 y_ 和 y_conv 之间的“最佳拟合”。

然而,在超过 100k 次迭代的过程中,损失输出迅速稳定在 400 到 900 之间的振荡(或者,因此,任何给定标签的 0.2-0.3 平均超过 50 个批次中的 2 个标签)所以我想我只是得到噪音。也许我错了,但我希望使用 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")

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

我目前的理论是:
1. 我忽略/误解了有关损失函数的一些内容。
2. 我误解了权重是如何初始化/更新的
3. 我严重低估了这个过程需要多长时间......尽管再一次,损失似乎只是在振荡。

任何帮助将不胜感激,谢谢!

4

1 回答 1

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

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

于 2016-03-11T00:18:22.290 回答