使用VGG16预处理模型进行灰度图像的错误

发布于 2025-02-06 01:44:40 字数 746 浏览 3 评论 0原文

我正在使用带有灰度图像的VGG16预训练模型进行手语检测。当我尝试运行型号。FIT命令时,我会收到以下错误。

澄清

我已经有图像作为RGB表格,但我想将它们用作灰度,以检查它们是否可以与灰度一起使用。原因是,使用彩色图像,我没有得到我期望的准确性。它的测试准确性仅为最大40%,并且在数据集中被过度拟合。

“错误消息”

另外,这是我的模型命令

vgg = vgg = vgg16(input_shape = [128,128,128] + [3 ],weights ='imageNet',include_top = false)

这是我的模型

history = model.fit(
  train_x,
  train_y,
  epochs=15,
  validation_data=(test_x, test_y),
  callbacks=[early_stop, checkpoint],
  batch_size=32,shuffle=True)

。我是与预训练模型一起工作的新手。当我尝试使用3个频道的颜色图像运行代码时,我的模型正在变得过于拟合,而val_accuracy不会上升到40%以上,因此我想尝试尝试灰度图像,因为我添加了许多数据增强技术,但是准确性是准确性是不改善。当我很长一段时间以来,任何线索都受到欢迎。

I am working on sign language detection using VGG16 pre-trained model with grayscale images. When I am trying to run the model.fit command, I am getting the following error.

CLARIFICATION

I already have images as RGB form but I want to use them as grayscale to check if they would work with grayscale. The reason being, with color images, I am not getting the accuracy which I am expecting. It is having test accuracy of max 40% only and getting overfitted on dataset.

Error message

Also, this is my model command

vgg = VGG16(input_shape= [128, 128] + [3], weights='imagenet', include_top=False)

This is my model.fit command

history = model.fit(
  train_x,
  train_y,
  epochs=15,
  validation_data=(test_x, test_y),
  callbacks=[early_stop, checkpoint],
  batch_size=32,shuffle=True)

I am new to working with pre-trained models. When I am trying to run the code with color images with 3 channels, my model is getting into overfitting and val_accuracy doesn't rise above 40% so I want to give try the grayscale images as I have added many data augmentation techniques but accuracy is not improving. Any leads are welcomed as I am stuck into this for long time now.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

秋意浓 2025-02-13 01:44:40

我能想到的最简单的解决方案是将您的图像转换为RGB。您可以作为模型的一部分来执行此操作。

model = Sequential([
  tf.keras.layers.Lambda(tf.image.grayscale_to_rgb),
  vgg
])

这将解决您的VGG问题。我还看到您缺少图像的最后一个维度。灰度中的图像预计将具有形状[高度,宽度,1],但您只有[高度,宽度]。您可以使用tf.expand_dims

model = Sequential([
  tf.keras.layers.Lambda(
    lambda x: tf.image.grayscale_to_rgb(tf.expand_dims(x, -1))
  ),
  vgg,
])

请注意,该解决方案在图中中求解问题,因此它可以在线运行。意思是,在运行时,您可以按照现在的方式完全相同的方式馈送数据(在形状[128,128]中,没有通道维度),并且它仍然可以在功能上工作。如果这是您在运行时的预期维度,那么将数据扔入模型之前,这将比操作数据更快。

顺便说一句,鉴于VGG经过专门用于最佳颜色图像的培训,这都不是理想的选择。只是以为我应该加。

The simplest (and likely fastest) solution I can think of is to just convert your image to rgb. You can do this as part of your model.

model = Sequential([
  tf.keras.layers.Lambda(tf.image.grayscale_to_rgb),
  vgg
])

This will fix your issue with VGG. I also see that you're missing the last dimensionality for your images. Images in grayscale are expected to be of shape [height, width, 1], but you simply have [height, width]. You can fix this using tf.expand_dims:

model = Sequential([
  tf.keras.layers.Lambda(
    lambda x: tf.image.grayscale_to_rgb(tf.expand_dims(x, -1))
  ),
  vgg,
])

Note that this solution solves the problem in the graph, so it runs online. Meaning, at runtime, you can feed data exactly the same way you have it now (in the shape [128, 128], without a channels dimension) and it will still functionally work. If this is your expected dimensionality during runtime, this will be faster than manipulating your data before throwing it into the model.

By the way, none of this is ideal, given that VGG was trained specifically to work best with color images. Just thought I should add that.

吃素的狼 2025-02-13 01:44:40

您为什么要过度拟合?

也许是出于不同的原因:

  1. 您的图像和标签在火车,val,测试中都不存在。 (也许您在火车上有图像,并且没有测试。)或者您的火车,val,测试数据不能正确分层,而是在数据和功能中的特定区域上训练模型。
  2. 您的数据集很小,您需要更多数据。
  3. 也许您的数据集中有噪音,首先确保从数据集中删除噪音。 (如果您有噪音,则模型适合您的噪音。)

如何将灰度图像输入vgg16

用于使用vgg16,您需要输入3个通道图像。因此,您需要像下面的图像一样加入图像,以获取灰度的三个频道图像:

image = tf.concat([image, image, image], -1)

训练示例vgg16在灰度映像上来自fastion> fashion_mnist dataSet:

from tensorflow.keras.applications.vgg16 import VGG16
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

train, val, test = tfds.load(
    'fashion_mnist',
    shuffle_files=True, 
    as_supervised=True, 
    split = ['train[:85%]', 'train[85%:]', 'test']
)

def resize_preprocess(image, label):
    image = tf.image.resize(image, (32, 32))
    image = tf.concat([image, image, image], -1)
    image = tf.keras.applications.densenet.preprocess_input(image)
    return image, label
    

train = train.map(resize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)
test  = test.map(resize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)
val   = val.map(resize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)


train = train.repeat(15).batch(64).prefetch(tf.data.AUTOTUNE)
test = test.batch(64).prefetch(tf.data.AUTOTUNE)
val  = val.batch(64).prefetch(tf.data.AUTOTUNE)


base_model = VGG16(weights="imagenet", include_top=False, input_shape=(32,32,3))
base_model.trainable = False ## Not trainable weights


model = tf.keras.Sequential()
model.add(base_model)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1024, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=.4))    
model.add(tf.keras.layers.Dense(256, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=.4))
model.add(tf.keras.layers.Dense(10, activation='sigmoid'))        
model.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              optimizer='Adam', 
              metrics=['accuracy'])
model.summary()

fit_callbacks = [tf.keras.callbacks.EarlyStopping(
    monitor='val_accuracy', patience = 4, restore_best_weights = True)]

history = model.fit(train, steps_per_epoch=150, epochs=5, batch_size=64, validation_data=val, callbacks=fit_callbacks)
model.evaluate(test)

输出:

Model: "sequential_17"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 vgg16 (Functional)          (None, 1, 1, 512)         14714688  
                                                                 
 flatten_3 (Flatten)         (None, 512)               0         
                                                                 
 dense_9 (Dense)             (None, 1024)              525312    
                                                                 
 dropout_6 (Dropout)         (None, 1024)              0         
                                                                 
 dense_10 (Dense)            (None, 256)               262400    
                                                                 
 dropout_7 (Dropout)         (None, 256)               0         
                                                                 
 dense_11 (Dense)            (None, 10)                2570      
                                                                 
=================================================================
Total params: 15,504,970
Trainable params: 790,282
Non-trainable params: 14,714,688
_________________________________________________________________
Epoch 1/5
150/150 [==============================] - 6s 35ms/step - loss: 0.8056 - accuracy: 0.7217 - val_loss: 0.5433 - val_accuracy: 0.7967
Epoch 2/5
150/150 [==============================] - 4s 26ms/step - loss: 0.5560 - accuracy: 0.7965 - val_loss: 0.4772 - val_accuracy: 0.8224
Epoch 3/5
150/150 [==============================] - 4s 26ms/step - loss: 0.5287 - accuracy: 0.8080 - val_loss: 0.4698 - val_accuracy: 0.8234
Epoch 4/5
150/150 [==============================] - 5s 32ms/step - loss: 0.5012 - accuracy: 0.8149 - val_loss: 0.4334 - val_accuracy: 0.8329
Epoch 5/5
150/150 [==============================] - 4s 25ms/step - loss: 0.4791 - accuracy: 0.8315 - val_loss: 0.4312 - val_accuracy: 0.8398
157/157 [==============================] - 2s 15ms/step - loss: 0.4457 - accuracy: 0.8325
[0.44566288590431213, 0.8324999809265137]

Why are you getting overfitting?

Maybe for different reasons:

  1. Your images and labels don't equally exist in the train, Val, test. (maybe you have images in train and don't have them in test.) Or your train, Val, test data don't stratify correctly and you train your model on a specific area in your data and features.
  2. You Dataset is very small and you need more data.
  3. Maybe you have noise in your datase, first make sure to remove noise from the dataset. (if you have noise, model fit on your noise.)

How can you input grayscale images to VGG16?

For Using VGG16, you need to input 3 channels images. For this reason, you need to concatenate your images like below to get three channels images from grayscale:

image = tf.concat([image, image, image], -1)

Example of training VGG16 on grayscale images from fashion_mnist dataset:

from tensorflow.keras.applications.vgg16 import VGG16
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

train, val, test = tfds.load(
    'fashion_mnist',
    shuffle_files=True, 
    as_supervised=True, 
    split = ['train[:85%]', 'train[85%:]', 'test']
)

def resize_preprocess(image, label):
    image = tf.image.resize(image, (32, 32))
    image = tf.concat([image, image, image], -1)
    image = tf.keras.applications.densenet.preprocess_input(image)
    return image, label
    

train = train.map(resize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)
test  = test.map(resize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)
val   = val.map(resize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)


train = train.repeat(15).batch(64).prefetch(tf.data.AUTOTUNE)
test = test.batch(64).prefetch(tf.data.AUTOTUNE)
val  = val.batch(64).prefetch(tf.data.AUTOTUNE)


base_model = VGG16(weights="imagenet", include_top=False, input_shape=(32,32,3))
base_model.trainable = False ## Not trainable weights


model = tf.keras.Sequential()
model.add(base_model)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1024, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=.4))    
model.add(tf.keras.layers.Dense(256, activation='relu'))
model.add(tf.keras.layers.Dropout(rate=.4))
model.add(tf.keras.layers.Dense(10, activation='sigmoid'))        
model.compile(loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              optimizer='Adam', 
              metrics=['accuracy'])
model.summary()

fit_callbacks = [tf.keras.callbacks.EarlyStopping(
    monitor='val_accuracy', patience = 4, restore_best_weights = True)]

history = model.fit(train, steps_per_epoch=150, epochs=5, batch_size=64, validation_data=val, callbacks=fit_callbacks)
model.evaluate(test)

Output:

Model: "sequential_17"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 vgg16 (Functional)          (None, 1, 1, 512)         14714688  
                                                                 
 flatten_3 (Flatten)         (None, 512)               0         
                                                                 
 dense_9 (Dense)             (None, 1024)              525312    
                                                                 
 dropout_6 (Dropout)         (None, 1024)              0         
                                                                 
 dense_10 (Dense)            (None, 256)               262400    
                                                                 
 dropout_7 (Dropout)         (None, 256)               0         
                                                                 
 dense_11 (Dense)            (None, 10)                2570      
                                                                 
=================================================================
Total params: 15,504,970
Trainable params: 790,282
Non-trainable params: 14,714,688
_________________________________________________________________
Epoch 1/5
150/150 [==============================] - 6s 35ms/step - loss: 0.8056 - accuracy: 0.7217 - val_loss: 0.5433 - val_accuracy: 0.7967
Epoch 2/5
150/150 [==============================] - 4s 26ms/step - loss: 0.5560 - accuracy: 0.7965 - val_loss: 0.4772 - val_accuracy: 0.8224
Epoch 3/5
150/150 [==============================] - 4s 26ms/step - loss: 0.5287 - accuracy: 0.8080 - val_loss: 0.4698 - val_accuracy: 0.8234
Epoch 4/5
150/150 [==============================] - 5s 32ms/step - loss: 0.5012 - accuracy: 0.8149 - val_loss: 0.4334 - val_accuracy: 0.8329
Epoch 5/5
150/150 [==============================] - 4s 25ms/step - loss: 0.4791 - accuracy: 0.8315 - val_loss: 0.4312 - val_accuracy: 0.8398
157/157 [==============================] - 2s 15ms/step - loss: 0.4457 - accuracy: 0.8325
[0.44566288590431213, 0.8324999809265137]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文