keras实现用resnet18非预训练模型对四种天气分类,能自己定义归一化方法,并绘制图像
时间: 2023-08-06 18:09:31 浏览: 87
带深度学习的字母识别:Keras的深度神经网络模型
好的,我们可以按照以下步骤来实现:
1. 导入必要的库和模块
```python
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
```
2. 定义数据路径和超参数
```python
data_dir = 'path/to/data'
img_height = 224
img_width = 224
batch_size = 32
num_epochs = 10
```
3. 定义归一化方法
```python
# 自定义归一化方法
def normalize_img(img):
img = tf.cast(img, dtype=tf.float32) / 255.
return (img - 0.5) / 0.5
```
4. 加载数据并进行预处理
```python
# 使用 ImageDataGenerator 加载数据
datagen = ImageDataGenerator(
preprocessing_function=normalize_img
)
train_data = datagen.flow_from_directory(
directory=data_dir + '/train',
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
)
val_data = datagen.flow_from_directory(
directory=data_dir + '/val',
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='categorical',
)
```
5. 构建模型
```python
def resnet_block(inputs, filters, kernel_size, strides, activation='relu'):
x = layers.Conv2D(filters, kernel_size=kernel_size, strides=strides, padding='same')(inputs)
x = layers.BatchNormalization()(x)
if activation:
x = layers.Activation(activation)(x)
return x
def resnet18(input_shape, num_classes):
inputs = layers.Input(shape=input_shape)
# 第一层卷积
x = resnet_block(inputs, filters=64, kernel_size=7, strides=2)
# 残差块
x = layers.MaxPooling2D(pool_size=3, strides=2, padding='same')(x)
for _ in range(2):
x = resnet_block(x, filters=64, kernel_size=3, strides=1)
x = layers.MaxPooling2D(pool_size=3, strides=2, padding='same')(x)
for _ in range(2):
x = resnet_block(x, filters=128, kernel_size=3, strides=1)
x = layers.MaxPooling2D(pool_size=3, strides=2, padding='same')(x)
for _ in range(2):
x = resnet_block(x, filters=256, kernel_size=3, strides=1)
x = layers.MaxPooling2D(pool_size=3, strides=2, padding='same')(x)
for _ in range(2):
x = resnet_block(x, filters=512, kernel_size=3, strides=1)
# 全局平均池化
x = layers.GlobalAveragePooling2D()(x)
# 输出层
outputs = layers.Dense(num_classes, activation='softmax')(x)
# 模型实例化
model = keras.Model(inputs, outputs, name='resnet18')
return model
# 实例化模型
model = resnet18(input_shape=(img_height, img_width, 3), num_classes=4)
```
6. 编译模型
```python
model.compile(
optimizer=keras.optimizers.Adam(),
loss=keras.losses.CategoricalCrossentropy(),
metrics=[keras.metrics.CategoricalAccuracy()],
)
```
7. 训练模型
```python
history = model.fit(
train_data,
epochs=num_epochs,
validation_data=val_data,
)
```
8. 绘制准确率和损失函数变化图
```python
plt.plot(history.history['categorical_accuracy'], label='train')
plt.plot(history.history['val_categorical_accuracy'], label='val')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['val_loss'], label='val')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
```
这样就完成了用resnet18非预训练模型对四种天气分类的实现,并绘制了准确率和损失函数变化图。
阅读全文