machine-learning - 多个独立标签的成本和激活函数

标签 machine-learning computer-vision tensorflow tensorboard

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

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

然而,在超过 10 万次迭代的过程中,损失输出很快就稳定在 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. 我严重低估了这个过程需要多长时间……尽管损失似乎只是在波动。

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

最佳答案

据我所知,您的成本函数不是通常的均方误差。
您正在优化 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]))

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

关于machine-learning - 多个独立标签的成本和激活函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34613261/

相关文章:

machine-learning - 使用朴素贝叶斯分类

algorithm - 我们可以识别照片中的照片吗?

image-processing - 如何将图像输入到神经网络?

python - 对 keras 输出感到困惑

python - "TypeError: Input ' global_step ' of ' ResourceApplyAdagradDA ' Op has type int32 that does not match expected type of int64."这是什么错误?

python - 使用经过训练的神经网络来显示更广泛的周围环境的图像

machine-learning - tensorflow 加载模型给出了不同的预测

machine-learning - 使用机器学习进行人脸识别的灰色还是 RGB?

matlab - 从2D图像获取深度图像

TensorFlow 无法编译