使用Resnet50模型对桥梁裂缝数据集中裂缝图像提取特征和训练、测试、应用分类器的代码python
时间: 2023-06-26 12:04:57 浏览: 110
yolo开发使用Resnet50作为特征提取器开发YOLO模型
下面是使用Resnet50模型对桥梁裂缝数据集中裂缝图像提取特征和训练、测试、应用分类器的Python代码:
```
# 导入所需库
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.callbacks import ModelCheckpoint
from keras.optimizers import Adam
from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.utils import to_categorical
import os
# 设置数据集路径和批量大小
data_path = 'path/to/dataset'
batch_size = 32
# 定义函数:加载数据集
def load_data(data_path):
X = []
y = []
for label in os.listdir(data_path):
label_path = os.path.join(data_path, label)
for img_name in os.listdir(label_path):
img_path = os.path.join(label_path, img_name)
img = plt.imread(img_path)
X.append(img)
y.append(int(label))
X = np.array(X)
y = np.array(y)
return X, y
# 加载数据集
X, y = load_data(data_path)
# 将标签转换为one-hot编码
y = to_categorical(y)
# 划分训练集、验证集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
# 数据增强
train_datagen = ImageDataGenerator(rotation_range=20, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.1, zoom_range=0.1, horizontal_flip=True, preprocessing_function=preprocess_input)
val_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
train_generator = train_datagen.flow(X_train, y_train, batch_size=batch_size)
val_generator = val_datagen.flow(X_val, y_val, batch_size=batch_size)
# 加载Resnet50模型
base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
# 添加全局平均池化层和全连接层
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(2, activation='softmax')(x)
# 构建模型
model = Model(inputs=base_model.input, outputs=predictions)
# 冻结Resnet50的前几层
for layer in base_model.layers:
layer.trainable = False
# 编译模型
model.compile(optimizer=Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
# 定义回调函数:保存最佳模型
filepath = "best_model.h5"
checkpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
# 训练模型
history = model.fit_generator(train_generator, steps_per_epoch=len(X_train)//batch_size, epochs=50, validation_data=val_generator, validation_steps=len(X_val)//batch_size, callbacks=[checkpoint])
# 加载最佳模型
model.load_weights("best_model.h5")
# 评估模型
test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
test_generator = test_datagen.flow(X_test, y_test, shuffle=False)
test_loss, test_acc = model.evaluate_generator(test_generator)
print('Test accuracy:', test_acc)
# 应用分类器
def predict_class(image_path, model):
img = plt.imread(image_path)
img = preprocess_input(img.reshape(1,224,224,3))
pred = model.predict(img)[0]
return np.argmax(pred)
# 用例:加载图像并预测其分类
image_path = 'path/to/image'
pred_class = predict_class(image_path, model)
print('Predicted class:', pred_class)
```
注意:需要将代码中的`path/to/dataset`和`path/to/image`替换为相应的数据集路径和图像路径。另外,此代码假定数据集中有两个类别。如果数据集中的类别数不同,请相应地更改代码中的`Dense`层的输出尺寸。
阅读全文