【问题标题】:constant loss values with normal CNNs and transfer learning具有正常 CNN 和迁移学习的恒定损失值
【发布时间】:2021-03-03 21:44:17
【问题描述】:

我正在研究论文https://arxiv.org/ftp/arxiv/papers/1511/1511.02459.pdf 中给出的数据集 在本文中,图像数据集(人物肖像)由 1 到 5 之间的浮点数标记(1 丑,5 好看)。我想处理这个数据集,并在我的 RTX 3070 8gb 上使用带有 CUDA 11.1 的 Tensorflow 2.4.0-dev20201009 中的 MobileNetV2 和迁移学习(在 Imagenet 上预训练)。我并没有真正看到我的错误,但训练我的模型通常会在不断的验证损失中产生,例如:

78/78 [==============================] - ETA: 0s - loss: 52145660442.33472020-11-20 13:19:36.796481: E tensorflow/core/grappler/optimizers/meta_optimizer.cc:596] layout failed: Invalid argument: Size of values 2 does not match size of permutation 4 @ fanin shape insequential/dense/BiasAdd-0-TransposeNHWCToNCHW-LayoutOptimizer
78/78 [==============================] - 16s 70ms/step - loss: 51654522711.5709 - val_loss: 9.5415
Epoch 2/300
78/78 [==============================] - 4s 52ms/step - loss: 9.4870 - val_loss: 9.5415
Epoch 3/300
78/78 [==============================] - 4s 52ms/step - loss: 9.3986 - val_loss: 9.5415
Epoch 4/300
78/78 [==============================] - 4s 51ms/step - loss: 9.4950 - val_loss: 9.5415
Epoch 5/300
78/78 [==============================] - 4s 52ms/step - loss: 9.4076 - val_loss: 9.5415
Epoch 6/300
78/78 [==============================] - 4s 52ms/step - loss: 9.4993 - val_loss: 9.5415
Epoch 7/300
78/78 [==============================] - 4s 52ms/step - loss: 9.3758 - val_loss: 9.5415
...

验证损失将在 300 个 epoch 内保持不变。我的代码可以在下面找到。让我总结一下: 我使用了 Imagenet 的迁移学习并冻结了 MobileNetV2 的卷积基础。 我添加了一个密集层作为分类器和 1 个输出神经元。我使用的损失函数是 MSE。代码中的优化器是 SGD,我还尝试了 ADAM,它也可以在验证集上产生恒定的损失值。 不同的学习率和 ADAM 也会发生上述错误(常量 val 损失)。有时,相同的学习率产生的不是恒定的 val 损失,而是合理的损失。我认为这是由于我的分类器中密集层上的随机权重初始化方法。我什至尝试过像 10 这样的荒谬 learning_rates,但值仍然是恒定的。如果 lr 非常高,那么应该可以清楚地看到变化!不是这种情况。怎么了?

我的代码:

import os
from typing import Dict, Any
from PIL import Image
from sklearn.model_selection import GridSearchCV
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
from tensorflow.keras import layers
from tensorflow import keras
import matplotlib.pyplot as plt
import pickle
import numpy as np
import cv2
import random

#method to create the model
def create_model(IMG_SIZE, lr):
  #Limit memore usage of GPU
  gpus = tf.config.experimental.list_physical_devices('GPU')
  if gpus:
    try:
      tf.config.experimental.set_virtual_device_configuration(gpus[0], [
        tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024*7)])
    except RuntimeError as e:
      print(e)

  model = keras.Sequential()
  model.add(MobileNetV2(input_shape=(IMG_SIZE, IMG_SIZE, 3), include_top=False))
  model.layers[0].trainable = False
  model.add(layers.GlobalAveragePooling2D())
  model.add(tf.keras.layers.Dropout(0.8))
  model.add(layers.Dense(128, activation="relu"))
  model.add(layers.Dense(1, activation="relu"))
#use adam or sgd as optimizers
  adam = tf.keras.optimizers.Adam(learning_rate=lr, beta_1=0.9, beta_2=0.98,
                                       epsilon=1e-9)
  sgd = tf.keras.optimizers.SGD(lr=lr, decay=1e-6, momentum=0.5)
  model.compile(optimizer=sgd,
                loss=tf.losses.mean_squared_error,
                )

  model.summary()
  return model

#preprocessing
def loadImages(IMG_SIZE):
  path = os.path.join(os.getcwd(), 'data\\Images')
  training_data=[]
  labelMap = getLabelMap()
  for img in os.listdir(path):
    out_array = np.zeros((350,350, 3), np.float32) #original size of images in the dataset
    try:
      img_array = cv2.imread(os.path.join(path, img))
      img_array=img_array.astype('float32')   #cast to float because to prevent normalization erros
      out_array = cv2.normalize(img_array, out_array, 0, 1, cv2.NORM_MINMAX) #normalize image
      out_array = cv2.resize(out_array, (IMG_SIZE, IMG_SIZE)) #resize, bc we need 224x224 for Imagenet pretrained weights
      training_data.append([out_array, float(labelMap[img])])
    except Exception as e:
      pass
  return training_data

#preprocessing, the txt file All_labels.txt has lines of the form 'filename.jpg 3.2' and 3.2 is the label
def getLabelMap():
  map = {}
  path = os.getcwd()
  path = os.path.join(path, "data\\train_test_files\\All_labels.txt")
  f = open(path, "r")
  for line in f:
    line = line.split()
    map[line[0]] = line[1]
  f.close()
  return map

#not important, in case you want to see the images after preprocessing
def showimg(image):
  image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  plt.imshow(image)
  plt.show()

#pickle the preprocessed data
def pickle_it(training_set, IMG_SIZE):
  X = []
  Y = []
  for features, label in training_set:
    X.append(features)
    Y.append(label)
  X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 3)
  Y = np.array(Y)

  pickle_out = open("X.pickle", "wb")
  pickle.dump(X, pickle_out)
  pickle_out.close()

  pickle_out = open("Y.pickle", "wb")
  pickle.dump(Y, pickle_out)
  pickle_out.close()

#for prediction after training the model
def betterThan(y, Y):
  Z=np.sort(Y)
  cnt = 0
  for z in Z:
    if z>y:
      break
    else:
      cnt = cnt+1
  return float(cnt/len(Y))

#for prediction after training the model
def predictImage(image, model, Y):
  img_array = cv2.imread(image)
  img_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
  img_array = np.array(img_array).reshape(-1, IMG_SIZE, IMG_SIZE, 3)
  y = model.predict(img_array)
  per = betterThan(y, Y)
  print('You look better than ' + str(per) + '% of the dataset')

#Main/Driver function
#Preprocessing
IMG_SIZE = 224
training_set=[]
training_set = loadImages(IMG_SIZE)
random.shuffle(training_set)
pickle_it(training_set, IMG_SIZE) #I pickle my data, so that I don't always have to go through the preprocessing

#Load preprocessed data
X = pickle.load(open("X.pickle", "rb"))
Y = pickle.load(open("Y.pickle", "rb"))

#Just to check that the images look correct
showimg(X[0])

# define the grid search parameters, feel free to edit the grids
batch_size = [64]
epochsGrid = [300]
learning_rate = [0.1]

#save models and best parameters found in grid search
size_histories = {}
min_val_loss = 10
best_para = {}

#ignore this, used for bugs on my gpu... You possibly don't need this
config = tf.compat.v1.ConfigProto(gpu_options=tf.compat.v1.GPUOptions(allow_growth=True))
sess = tf.compat.v1.Session(config=config)


#grid search, training the model
for epochs in epochsGrid:
  for batch in batch_size:
    for lr in learning_rate:
      model = create_model(IMG_SIZE, lr)
      model_name = str(epochs) + '_' + str(batch) + '_' + str(lr)
      #train the model with the given hyperparameters
      size_histories[model_name] = model.fit(X, Y, batch_size=batch, epochs=epochs, validation_split=0.1)
      
      # save model with the best loss value
      if min(size_histories[model_name].history['val_loss']) < min_val_loss:
        min_val_loss = min(size_histories[model_name].history['val_loss'])
        best_para['epoch'] = epochs
        best_para['batch'] = batch
        best_para['lr'] = lr
        model.save('savedModel')



#If you want to make prediction
model = tf.keras.models.load_model("savedModel")
image = os.path.join(os.getcwd(), 'data\\otherImages\\beautifulWomen.jpg')
predictImage(image, model, Y)

编辑: 我发现了这个问题。它是输出神经元中的“relu”。当我将损失从 RMSE 更改为 MAPE 时,我会看到验证时出现 100% 的错误。我假设这是因为我所有的验证数据都输出为 0。这只有在“relu”之前的输出神经元中的值为负时才有可能。我不知道为什么会这样。但是删除“relu”会产生更好的训练。

有人知道为什么“relu”会导致回归问题吗?

【问题讨论】:

  • 你试过CategoricalCrossentropy吗?
  • 这不是单热编码向量吗?我的标签是区间 [1,5] 中的真实值。
  • 是的,你是对的。我在阅读时错过了is labeled by a floating number between 1 and 5 部分。

标签: tensorflow machine-learning conv-neural-network transfer-learning


【解决方案1】:

如果这是你的最后一层

model.add(layers.Dense(1, activation="relu"))

那么你的模型最终输出是y if y &gt; 0 else 0。在您未经训练的状态下,您的模型很可能以相当均等的机会将 y 固定到 -17 或 17 之类的值。在 -17 的情况下,relu 会将其转换为 0,并将梯度设置为 0,这意味着网络不学习。是的,网络不会从网络的任何部分学习任何东西,其中 relu 单元输出 0。对于之前的层

model.add(layers.Dense(128, activation="relu"))

很有可能大约一半的单位会以正值开火,因此他们会学习,所以这一层很好。

在初始化错误的情况下或在训练最后一层的输出被推低到 0 以下的不良状态后,可以做什么?好吧,如果我们不使用 relu 会怎样。使用什么激活?没有!让我们看看会是什么

1: model = keras.Sequential()
2: model.add(MobileNetV2(input_shape=(IMG_SIZE, IMG_SIZE, 3), include_top=False))
3: model.layers[0].trainable = False
4: model.add(layers.GlobalAveragePooling2D())
5: model.add(tf.keras.layers.Dropout(0.8))
6: model.add(layers.Dense(128, activation="relu"))
7: model.add(layers.Dense(1))

第 1-6 行都是一样的。需要注意的是,第 6 行的输出通过了非线性 relu 激活,因此具有学习非线性的能力。第 7 行,没有激活函数将是第 6 行的线性组合,具有在正输出区域和负输出区域产生梯度的完全能力。当应用反向传播学习1到5的目标值时,如果网络输出-17,它可以学习输出更​​大的数字。对!

如果您想要 2 层非线性,我建议如下

1: model = keras.Sequential()
2: model.add(MobileNetV2(input_shape=(IMG_SIZE, IMG_SIZE, 3), include_top=False))
3: model.layers[0].trainable = False
4: model.add(layers.GlobalAveragePooling2D())
5: model.add(layers.Dense(128, activation="tanh"))
6: model.add(layers.Dense(64, activation="tanh"))
7: model.add(layers.Dense(1))

放弃 dropout,除非你有实际证据证明它在这个非常特定的网络中有帮助(现在我怀疑你没有)。试试 tanh 作为你的隐藏层激活函数。它有一些很好的特性,比如正负,即使是大和/或负数的梯度,并且在某种程度上自动调整权重。但是,重要的是,最后一个输出要么没有激活函数。

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 2019-03-07
    • 2019-08-24
    • 2018-05-11
    • 2020-07-17
    • 1970-01-01
    • 2016-07-18
    • 2020-07-25
    相关资源
    最近更新 更多