0

我是使用 CNN 的新手,但我正在尝试使用带有 CIFAR10 数据集的功能 API 来制作一个。唯一的问题是我的准确率非常低。我查看了我的教科书示例和文档,但无法弄清楚为什么它应该开始更高的时候却如此之低。这是我使用 DenseNet201 和 tf 2.7 版的设置:

#load in data 
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
X_train, X_test = X_train / 255.0, X_test / 255.0

# one hot encode target values/labels
y_train = tf.keras.utils.to_categorical(y_train)
y_test = tf.keras.utils.to_categorical(y_test)

# have to preprocess before using functional API
X_testP = tf.keras.applications.densenet.preprocess_input(X_test)
X_trainP = tf.keras.applications.densenet.preprocess_input(X_train)

# data size we start with
inputs = tf.keras.Input(shape=(32,32,3))
# densenet expects 224x224 so use lambda layer
resized_images = tf.keras.layers.Lambda(lambda image: tf.image.resize(image, (224, 224)))(inputs)

# initialize model
transfer = keras.applications.DenseNet201(include_top=False, weights='imagenet', pooling='max', input_tensor = resized_images,input_shape=(224,224,3), classes=1000)

# add your layers
x = transfer.output
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(256, activation='relu')(x)
x = tf.keras.layers.BatchNormalization() (x)
x = tf.keras.layers.Dense(200, activation='relu')(x)
x = tf.keras.layers.Dense(128, activation='relu')(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
output = tf.keras.layers.Dense(10, activation='softmax')(x)

transfer_model = keras.Model(inputs=transfer.input, outputs=output)
transfer_model.trainable = False;

# here I try SGD but I also tried Adam to no better results
optimizer = keras.optimizers.SGD(learning_rate=0.2, momentum=0.9, decay=0.01)

transfer_model.compile(optimizer=optimizer,loss='categorical_crossentropy',metrics=['accuracy'])

history_transfer = transfer_model.fit(X_trainP, y_train,epochs=20)

我觉得我见过的所有例子都开始得更高,甚至没有额外的层。我是否误解了初始化中的某些内容?

4

1 回答 1

0

您的问题是像素值被调用了两次。函数 tf.keras.applications.densenet.preprocess_input 重新缩放像素值,因此您不应重新缩放它们。在您的代码中,您有

transfer = keras.applications.DenseNet201(include_top=False, weights='imagenet', pooling='max', input_tensor = resized_images,input_shape=(224,224,3), classes=1000)

第一件事是 - 如果您设置 pooling=max 输出是一维张量,因此您不需要模型中的展平层。其次,如果包含 top=True,密集网络只需有 224 X 224 图像。因此,您不需要使用 lambda 函数调整输入的大小。设置 input_shape=(32,32,3) set classes=None 移除参数 input_tensor 你的模型可能会过拟合。向模型添加一个 dropout 层。使用 rate=.4 使用 adam 优化器效果很好。

于 2021-12-10T05:06:37.243 回答