keras实现用resnet18非预训练模型对四种天气分类,并打乱数据
时间: 2023-12-03 11:43:00 浏览: 97
以下是使用Keras实现对四种天气分类的代码,其中使用了ResNet18非预训练模型,并对数据进行了打乱。
```python
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Flatten
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 设置超参数
batch_size = 32
epochs = 10
num_classes = 4
input_shape = (224, 224, 3)
# 创建一个ResNet18模型(不包括头部)
resnet = ResNet50(include_top=False, input_tensor=Input(shape=input_shape))
# 添加自定义的头部
x = resnet.output
x = Flatten()(x)
x = Dense(256, activation='relu')(x)
x = Dense(num_classes, activation='softmax')(x)
# 创建一个新的模型
model = Model(inputs=resnet.input, outputs=x)
# 编译模型
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# 加载数据并进行数据增强
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
train_generator = train_datagen.flow_from_directory(
'data/train',
target_size=input_shape[:2],
batch_size=batch_size,
class_mode='categorical')
validation_datagen = ImageDataGenerator(rescale=1./255)
validation_generator = validation_datagen.flow_from_directory(
'data/validation',
target_size=input_shape[:2],
batch_size=batch_size,
class_mode='categorical')
# 训练模型
model.fit(
train_generator,
steps_per_epoch=len(train_generator),
epochs=epochs,
validation_data=validation_generator,
validation_steps=len(validation_generator))
# 评估模型
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
'data/test',
target_size=input_shape[:2],
batch_size=batch_size,
class_mode='categorical')
score = model.evaluate(test_generator, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
在上面的代码中,我们使用了`ResNet50`模型,并在其顶部添加了自定义的头部。我们还使用`ImageDataGenerator`类来进行数据增强,并对数据进行了打乱。最后,我们训练模型并评估其性能。
阅读全文