【问题标题】:Training loss does not decrease训练损失没有减少
【发布时间】:2019-08-18 08:20:18
【问题描述】:

我正在尝试在 tensorflow 中使用 CNN 实现自动编码器。首先,我在 MNIST 数据集上训练了我的模型,一切运行良好,我得到了较低的损失,并且当我运行推理模型时运行良好(提供了良好的输出图像)。但后来我决定在 CelebA 数据集上测试我的网络,但我的模型失败了,并且损失从未减少。模型处理速度很快,我尝试降低学习率。即使我降低了学习率,训练所需的时间也没有太大差异。

这里我会尽量放上我用到的所有代码

**注意我也设置了 GitHub 存储库,以防你更容易阅读代码there

self.batch_size = 64
self.shape = shape

self.output_height = 64
self.output_width = 64
self.gf_dim = 64
self.c_dim = 3

self.strides_size = 2
self.kernel_size = 2
self.padding = 'SAME'
def encoder_conv_net(self, input_):

    self.conv1 = Model.batch_norm(self, Model.conv_2d(self, input_, [3,3,self.c_dim,32], name = 'conv1'))

    self.conv2 = Model.batch_norm(self, Model.conv_2d(self, self.conv1, [3,3,32,64], name = 'conv2'))

    self.conv3 = Model.batch_norm(self, Model.conv_2d(self, self.conv2, [3,3,64,128], name = 'conv3'))

    self.conv4 = Model.batch_norm(self, Model.conv_2d(self, self.conv3, [3,3,128,128], name = 'conv4'))

    fc = tf.reshape(self.conv4, [ -1, 512 ])

    dropout1 = tf.nn.dropout(fc, keep_prob=0.5)

    fc1 = Model.fully_connected(self, dropout1, 512)
    return tf.nn.tanh(fc1)

def decoder_conv_net(self, 
                     input_,
                     shape):

    g_width, g_height = shape[1], shape[0]
    g_width2, g_height2 = np.ceil(shape[1]/2), np.ceil(shape[0]/2)
    g_width4, g_height4 = np.ceil(shape[1]/4), np.ceil(shape[0]/4)
    g_width8, g_height8 = np.ceil(shape[1]/8), np.ceil(shape[0]/8)

    input_ = tf.reshape(input_, [-1, 4, 4, 128])

    print(input_.shape, g_width8, self.gf_dim)
    deconv1 = Model.deconv_2d(self, input_, [self.batch_size, g_width8, g_height8, self.gf_dim * 2],
                              [5,5],
                              name = 'deconv_1')

    deconv2 = Model.deconv_2d(self, deconv1, [self.batch_size, g_width4, g_height4, self.gf_dim * 2],
                              [5,5],
                              name = 'deconv_2')

    deconv3 = Model.deconv_2d(self, deconv2, [self.batch_size, g_width2, g_height2, self.gf_dim],
                              [5,5],
                              name = 'deconv_3')

    deconv4 = Model.deconv_2d(self, deconv3, [self.batch_size, g_width, g_height, self.c_dim],
                              [5,5],
                              name = 'deconv_4',
                              relu = False)

    return tf.nn.tanh(deconv4)

这些是模型编码器和解码器的功能。

main函数长这样

dataset = tf.data.Dataset.from_tensor_slices(filenames)
dataset = dataset.shuffle(len(filenames))
dataset = dataset.map(parse_function, num_parallel_calls=4)
#dataset = dataset.map(train_preprocess, num_parallel_calls=4)
dataset = dataset.repeat().batch(batch_size)
#dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(batch_size))
dataset = dataset.prefetch(1)

iterator = tf.data.Iterator.from_structure(dataset.output_types,
                                           dataset.output_shapes)

next_element = iterator.get_next()
init_op = iterator.make_initializer(dataset)

#print(next_element)
x = next_element
#plt.imshow(x)
#x = tf.reshape(x, [64, 64, 64, 3])

ENC = Encoder(shape)
DEC = Decoder(shape)

encoding = ENC.encoder_conv_net(x)

print("Encoding output shape " + str(encoding.shape))    

output = DEC.decoder_conv_net(encoding, [64,64])

print(output.shape)
loss = tf.reduce_mean(tf.squared_difference(x, output))

opt = tf.train.AdamOptimizer(learning_rate=0.1e-5)
train = opt.minimize(loss)
saver = tf.train.Saver()
init = tf.global_variables_initializer()

我以正常方式调用这个训练课

with tf.Session(graph=graph) as sess:
  #saver.restore(sess, '')

  sess.run(init) 
  sess.run(init_op)

  a = sess.run(next_element)

  for ind in tqdm(range(nb_epoch)):    
      loss_acc, outputs, _ = sess.run([loss, output, train])
      print(loss_acc)

      if ind % 40 == 0:
          print(loss_acc)
          saver.save(sess, save_path = "./checkpoints/" \
                       "/model_face.ckpt", global_step = ind) 

在所有这些训练开始后没有错误,但我的损失并没有减少。

这里还有实用函数

def parse_function(filename):
  image_string = tf.read_file(filename)
  image = tf.image.decode_jpeg(image_string, channels=3)
  image = tf.image.convert_image_dtype(image, tf.float32)
  image = tf.image.resize_images(image, [64, 64])
  return image

def train_preprocess(image):
  image = tf.image.random_flip_left_right(image)
  image = tf.image.random_brightness(image, max_delta=32.0 / 255.0)
  image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
  image = tf.clip_by_value(image, 0.0, 1.0)
  return image

【问题讨论】:

  • 我同意代码太大,但我已经提供了一个解释,可能会提供有关在哪里寻找问题的线索。正如我所提到的,我的训练损失没有改变。它被困在某个值 +- 0.1 之间,因此,我既没有提供训练也没有提供验证损失图。如果有人有任何问题,如果我遗漏了什么,我很乐意提供更多信息,如下所示。
  • 从关于输出的评论中挑选。输出中的哪些值不在 0..1 范围内?
  • 值在-1和1之间
  • 您的损失函数可能没有采用绝对差值,并且由于您可能有正负误差,因此总和趋于收敛到 0。您是否尝试将它们映射到范围 0..1?
  • 您的训练图像的值介于 0.0 和 1.0 之间,不是吗? image = tf.clip_by_value(image, 0.0, 1.0)。例如,为什么不将这个激活更改为 softmax?

标签: python tensorflow


【解决方案1】:

通过将激活函数改为softmax,更适合你的图像编码:

image = tf.clip_by_value(image, 0.0, 1.0)

损失从0.14066154开始。

增加训练 epoch 的数量,损失似乎低至 ~0.08216808,这是合理的,因为我只在单个 Titan Xp 上训练了模型几分钟。

【讨论】:

  • 你把 tf.nn.tanh(deconv4) 改成了 tf.nn.softmax(deconv4) 对吧?
  • 是的。和tf.nn.tanh(fc1)tf.nn.softmax(fc1)
【解决方案2】:

你能打印 x 、输出和梯度的值吗? 我对不变损失的第一个想法是: 1.如果 x 始终为零,则输出保持不变。损失保持不变 2.如果x不为零,但每一步都保持不变,如果梯度总是为零(权重不更新),那么输出保持不变,损失保持不变 但是因为你可以在mnist上成功运行模型,所以这个show模型是可以的,所以我怀疑问题可能更多是关于数据。

【讨论】:

  • 我确实尝试检查 x 和输出,但 x 工作正常,当我尝试运行 plt.imshow(a[0,:,:,:]) 时,我得到了图像。但是,当我运行plt.imshow(outputs[0,:,:,:]) 时,我收到错误Floating point image RGB values must be in the 0..1 range. 这可能是个问题吗?一开始我以为是训练不足的问题。
  • 这应该是一条评论。 你能打印 x 、输出和梯度的值吗 这些是你给 OP 的建议,以便改进问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 2018-12-15
  • 2017-08-14
  • 2019-09-28
相关资源
最近更新 更多