.构建一个神经网络模型,并使用划分好的训练集数据训练模型,使用验证集的数据验证模型,训练迭代30次,建议使用生成器。 3.获取训练过程中的训练精度、验证精度,并使用matplotlib来绘制精度变化曲线,要求模型的验证精度达到80%以上(注意不是训练精度),可以使用数据增强、预训练的卷积神经网络等方法。 4.使用训练好的模型做猫狗预测,至少预测2张图片(有猫有狗),只需要在控制台中打印输出预测的结果即可。
时间: 2024-02-12 11:07:33 浏览: 82
好的,下面是一个使用Keras框架和数据增强的猫狗分类代码示例,您可以在本地环境中运行它来完成任务:
```python
import os
import numpy as np
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
# 设置图片目录和参数
train_dir = 'train'
validation_dir = 'validation'
img_width, img_height = 150, 150
input_shape = (img_width, img_height, 3)
epochs = 30
batch_size = 20
# 数据增强
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
validation_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
# 构建模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# 训练模型
history = model.fit_generator(
train_generator,
steps_per_epoch=train_generator.n // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_generator.n // batch_size)
# 绘制精度变化曲线
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(8, 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()
# 使用模型进行预测
test_dir = 'test'
test_images = ['test/cat.jpg', 'test/dog.jpg']
for test_image in test_images:
img = plt.imread(test_image)
img = img / 255.0
plt.imshow(img)
plt.show()
x = np.expand_dims(img, axis=0)
prediction = model.predict(x)
print(prediction)
if prediction < 0.5:
print("猫")
else:
print("狗")
```
需要注意的是,这里的数据集的目录结构应该是这样的:
```
- train
- cat
- cat.0.jpg
- cat.1.jpg
- ...
- dog
- dog.0.jpg
- dog.1.jpg
- ...
- validation
- cat
- cat.1000.jpg
- cat.1001.jpg
- ...
- dog
- dog.1000.jpg
- dog.1001.jpg
- ...
- test
- cat.jpg
- dog.jpg
```
其中,train和validation目录中分别包含1000张猫和1000张狗的训练图片,500张猫和500张狗的验证图片;test目录中包含两张测试图片。如果您的数据集目录结构不同,可以根据实际情况进行修改。
阅读全文