keras实现用resnet18非预训练模型对四种天气分类,能够自己定义归一化方法,并绘制图像
时间: 2023-07-31 07:09:45 浏览: 115
好的,以下是使用Keras实现用ResNet18非预训练模型对四种天气分类的代码。在这个例子中,我们将使用Tensorflow 2.0版本:
首先,导入需要的库和模块:
```python
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Input, BatchNormalization, Activation, Add
from tensorflow.keras.models import Model
```
接下来,我们定义一个自己的归一化方法,这里我们使用min-max标准化方法,将像素点的值映射到0-1之间:
```python
def my_normalize(img):
img = img.astype(np.float32)
img_min = np.min(img)
img_max = np.max(img)
img = (img - img_min) / (img_max - img_min)
return img
```
然后,我们准备训练数据和测试数据。这里我们使用Keras内置的ImageDataGenerator来进行数据增强,同时使用自定义的归一化方法。数据集中有四个类别:cloudy、rain、shine、sunrise。
```python
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
preprocessing_function=my_normalize)
test_datagen = ImageDataGenerator(
rescale=1./255,
preprocessing_function=my_normalize)
train_generator = train_datagen.flow_from_directory(
'weather_train/',
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
test_generator = test_datagen.flow_from_directory(
'weather_test/',
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
```
下一步,我们定义ResNet18模型。这里我们使用函数式API来构建模型:
```python
def conv_block(inputs, filters, kernel_size, strides):
x = Conv2D(filters, kernel_size, strides=strides, padding='same')(inputs)
x = BatchNormalization()(x)
x = Activation('relu')(x)
return x
def identity_block(inputs, filters, kernel_size):
x = Conv2D(filters, kernel_size, padding='same')(inputs)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv2D(filters, kernel_size, padding='same')(x)
x = BatchNormalization()(x)
x = Add()([x, inputs])
x = Activation('relu')(x)
return x
def ResNet18(input_shape, num_classes):
inputs = Input(shape=input_shape)
x = conv_block(inputs, 64, 7, 2)
x = MaxPooling2D(3, strides=2, padding='same')(x)
for i in range(2):
x = identity_block(x, 64, 3)
x = conv_block(x, 128, 3, strides=2)
for i in range(2):
x = identity_block(x, 128, 3)
x = conv_block(x, 256, 3, strides=2)
for i in range(2):
x = identity_block(x, 256, 3)
x = conv_block(x, 512, 3, strides=2)
for i in range(2):
x = identity_block(x, 512, 3)
x = Flatten()(x)
x = Dense(num_classes, activation='softmax')(x)
model = Model(inputs=inputs, outputs=x)
return model
```
最后,我们编译并训练模型:
```python
model = ResNet18((224, 224, 3), 4)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(train_generator, epochs=10, validation_data=test_generator)
```
训练完成后,我们可以使用matplotlib来绘制训练过程中的准确率和损失值曲线:
```python
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
```
这样就完成了用ResNet18非预训练模型对四种天气分类的任务。
阅读全文