基于深度卷积神经网络和迁移学习的纹理图像识别的代码
时间: 2023-11-14 11:05:35 浏览: 83
好的,以下是一个基于深度卷积神经网络和迁移学习的纹理图像识别的代码示例,使用Python编写,并使用Keras深度学习框架:
```python
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.applications.vgg16 import VGG16
# 设置GPU设备
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
# 加载数据集
train_dir = "/path/to/texture/dataset/train"
val_dir = "/path/to/texture/dataset/val"
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(224, 224),
batch_size=32,
class_mode='categorical'
)
val_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(224, 224),
batch_size=32,
class_mode='categorical'
)
# 定义模型
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
model = Sequential()
model.add(base_model)
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))
# 冻结基础模型的权重
for layer in base_model.layers:
layer.trainable = False
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
history = model.fit_generator(
train_generator,
steps_per_epoch=train_generator.n//train_generator.batch_size,
epochs=10,
validation_data=val_generator,
validation_steps=val_generator.n//val_generator.batch_size
)
```
在上面的代码中,我们使用了预训练的VGG-16模型作为基础模型,并在其基础上构建了我们自己的分类器。我们使用了ImageDataGenerator来增加数据的多样性。我们还定义了损失函数和优化器,并在每个epoch中训练模型以最小化损失函数。最后,我们输出每个epoch的准确率和损失值,以及在测试集上的准确率和损失值。
阅读全文