keras实现用简易的GoogleNet模型对四种天气数据集分类,并绘制图像
时间: 2024-02-06 20:11:04 浏览: 34
好的,我会尽可能详细地回答你的问题。
首先,GoogleNet是一种非常有名的卷积神经网络模型,主要用于图像分类任务。它有很多版本,其中最流行的版本是Inception-v3。但是,这个模型比较复杂,不太适合初学者。因此,我们可以使用一个简化版本的GoogleNet模型,也就是GoogLeNet-Lite。
接下来,我们需要使用Keras框架来实现这个模型。Keras是一个非常流行的深度学习框架,它可以帮助我们快速地构建和训练深度神经网络模型。
下面是实现用简易的GoogleNet模型对四种天气数据集分类的步骤:
1. 导入必要的库和模块
```python
import numpy as np
import os
from keras.layers import Input, Conv2D, MaxPooling2D, Dropout, Flatten, Dense
from keras.models import Model
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
```
2. 定义模型
```python
def GoogLeNetLite(input_shape, num_classes):
inputs = Input(shape=input_shape)
# 第一个卷积层
x = Conv2D(filters=64, kernel_size=(7, 7), strides=(2, 2), padding='same', activation='relu')(inputs)
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
# 第二个卷积层
x = Conv2D(filters=64, kernel_size=(1, 1), strides=(1, 1), padding='valid', activation='relu')(x)
x = Conv2D(filters=192, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu')(x)
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
# Inception模块1
x = inception_module(x, filters=[64, 96, 128, 16, 32, 32])
x = inception_module(x, filters=[128, 128, 192, 32, 96, 64])
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
# Inception模块2
x = inception_module(x, filters=[192, 96, 208, 16, 48, 64])
x = inception_module(x, filters=[160, 112, 224, 24, 64, 64])
x = inception_module(x, filters=[128, 128, 256, 24, 64, 64])
x = inception_module(x, filters=[112, 144, 288, 32, 64, 64])
x = inception_module(x, filters=[256, 160, 320, 32, 128, 128])
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
# Inception模块3
x = inception_module(x, filters=[256, 160, 320, 32, 128, 128])
x = inception_module(x, filters=[384, 192, 384, 48, 128, 128])
# 平坦层
x = Flatten()(x)
# 全连接层
x = Dropout(rate=0.4)(x)
x = Dense(units=num_classes, activation='softmax')(x)
model = Model(inputs=inputs, outputs=x)
return model
```
3. 定义Inception模块
```python
def inception_module(x, filters):
f1, f2, f3, f4, f5, f6 = filters
# 第一条支路
path1 = Conv2D(filters=f1, kernel_size=(1, 1), strides=(1, 1), padding='same', activation='relu')(x)
# 第二条支路
path2 = Conv2D(filters=f2, kernel_size=(1, 1), strides=(1, 1), padding='same', activation='relu')(x)
path2 = Conv2D(filters=f3, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu')(path2)
# 第三条支路
path3 = Conv2D(filters=f4, kernel_size=(1, 1), strides=(1, 1), padding='same', activation='relu')(x)
path3 = Conv2D(filters=f5, kernel_size=(5, 5), strides=(1, 1), padding='same', activation='relu')(path3)
# 第四条支路
path4 = MaxPooling2D(pool_size=(3, 3), strides=(1, 1), padding='same')(x)
path4 = Conv2D(filters=f6, kernel_size=(1, 1), strides=(1, 1), padding='same', activation='relu')(path4)
# 拼接四条支路
output = np.concatenate([path1, path2, path3, path4], axis=-1)
return output
```
4. 加载数据集并进行数据增强
```python
train_dir = 'train/'
validation_dir = 'validation/'
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(150, 150),
batch_size=20,
class_mode='categorical')
validation_generator = validation_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode='categorical')
```
5. 编译模型
```python
model = GoogLeNetLite(input_shape=(150, 150, 3), num_classes=4)
model.compile(optimizer=Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
```
6. 训练模型
```python
history = model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=100,
validation_data=validation_generator,
validation_steps=50)
```
7. 绘制训练和验证曲线
```python
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(len(acc))
plt.figure(figsize=(16, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
```
8. 使用模型进行预测
```python
test_dir = 'test/'
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(150, 150),
batch_size=1,
class_mode='categorical',
shuffle=False)
filenames = test_generator.filenames
nb_samples = len(filenames)
predictions = model.predict_generator(test_generator, steps=nb_samples)
```
9. 绘制预测结果
```python
fig, axs = plt.subplots(4, 4, figsize=(10, 10))
fig.subplots_adjust(hspace=0.4, wspace=0.4)
axs = axs.ravel()
for i in range(16):
img_path = os.path.join(test_dir, filenames[i])
img = plt.imread(img_path)
axs[i].imshow(img)
axs[i].axis('off')
max_prob = np.max(predictions[i])
label = np.argmax(predictions[i])
axs[i].set_title(f'{label} ({max_prob:.2f})')
plt.show()
```
这样,我们就完成了用简易的GoogleNet模型对四种天气数据集分类的任务,并绘制出了训练和验证曲线,以及预测结果。