我使用 MobileNetV2 模型作为基础模型,但我添加了 5 个新的可训练层,并且在两个新类别上重新训练它:猴痘阳性和猴痘阴性。猴痘阴性图像文件夹包含不同的皮肤感染,看起来与猴痘相似,但实际上是类似水痘的感染。我有一个包含彩色图像的数据集,但我将它们转换为灰度(下面的代码)。
当我尝试运行模型时,我遇到了问题
Input 0 of layer "Conv1" is incompatible with the layer: expected axis -1 of input shape to
have value 3, but received input with shape (None, 200, 200, 1)
我知道我必须欺骗模型,让它认为 1 的值为 3,但我不确定如何做。我使用 imagenet 来计算权重。
from tensorflow.keras.preprocessing import image as IMAGE
import numpy as np
import cv2
import os
os.environ["CUDA DEVICE ORDER"]="PCI BUS ID"
os.environ["CUDA VISIBLE DEVICES"]="0"
from tensorflow.keras import Model
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
import tensorflow as tf
from PIL import Image
from google.colab.patches import cv2_imshow
!pip3 install tensorflowjs
import tensorflowjs as tfjs
train = ImageDataGenerator(rescale = 1/255)
test = ImageDataGenerator(rescale = 1/255)
val = ImageDataGenerator(rescale = 1/255)
training_set = train.flow_from_directory("/content/drive/MyDrive/mpox_data/Train",
target_size=(200,200),
batch_size = 15,
class_mode = "categorical",
color_mode='rgb'
)
testing_set = test.flow_from_directory("/content/drive/MyDrive/mpox_data/Test",
target_size=(200,200),
batch_size = 15,
class_mode = "categorical",
color_mode='rgb'
)
validation_set = val.flow_from_directory("/content/drive/MyDrive/mpox_data/Val",
target_size=(200,200),
batch_size=15,
class_mode = "categorical",
color_mode='rgb'
)
x, y = training_set[0]
a, b = testing_set[0]
d, c = validation_set[0]
base_model = MobileNetV2(weights = "imagenet", include_top = False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(42, activation="relu")(x)
x = Dense(64, activation = "relu")(x)
x = Dense(32, activation="relu")(x)
preds = Dense(2, activation = "sigmoid")(x)
model = Model(inputs = base_model.input, outputs = preds)
epochs = 5
optimizer = Adam(learning_rate = 0.0003)
model.compile(loss = "binary_crossentropy", optimizer = optimizer, metrics = ["Accuracy"])
model.fit(training_set, validation_data = validation_set, epochs = epochs, shuffle=True)
我尝试在模型中使用灰度图像,希望它能够成功运行,但它给了我上面提到的错误。
为什么我的程序无法运行?如何修复它,让模型继续在灰度图像上进行自我训练?
您的输入需要三个通道。也就是说,图像必须是
RGB/BGR
格式,无论实际内容是否是灰度的。灰度内容仅是单通道,因此您需要将灰度通道额外复制两次,并使用该图像数组作为网络的输入。
实现此目的的方法不止一种,我更喜欢使用
OpenCV
进行此操作,但请记住此转换不会成为张量流图的一部分,因为它使用外部库并在 CPU 上运行。不过,它可能位于生成器函数内部。转换将是这样的,假设您的输入是 BGR
图像:
# To Grayscale (1-channel):
inputImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)
# Back to BGR (3-channels):
inputImage = cv2.cvtColor(inputImage , cv2.COLOR_GRAY2BGR)
接下来是通常使用
[0.0, 1.0]
缩放到 rescale
。