尝试调用Keras Application中提供的各种(一些)结构来训练cat-dog数据集,并测试准确率
时间: 2024-10-08 22:18:49 浏览: 82
在Python中,特别是在深度学习领域,Keras是一个流行的库,它提供了许多预训练的应用模型,如VGG16、ResNet50等,可以用于图像分类任务。例如,如果你想使用Keras应用中的VGG16来处理猫狗二分类问题(Cat-Dog classification),你可以按照以下步骤操作:
1. 首先,安装所需的库:
```bash
pip install tensorflow keras
```
2. 加载预训练的VGG16模型,并冻结除了最后一层之外的所有层,因为我们需要用新的数据集调整分类部分:
```python
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Model
vgg = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
x = Flatten()(vgg.output)
output_layer = Dense(1, activation='sigmoid')(x) # 对于二分类,输出层只有一个神经元
model = Model(inputs=vgg.input, outputs=output_layer)
for layer in model.layers[:-1]:
layer.trainable = False # 冻结所有预训练层
```
3. 准备Cat-Dog数据集,将其分为训练集和验证集,并进行数据增强(Data Augmentation)以增加样本多样性:
```python
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input,
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(preprocess_input, rescale=1./255)
train_generator = train_datagen.flow_from_directory(directory="path_to_train_data",
target_size=(224, 224),
batch_size=32,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(directory="path_to_val_data",
target_size=(224, 224),
batch_size=32,
class_mode='binary')
```
4. 编译并训练模型:
```python
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history = model.fit(train_generator, epochs=10, validation_data=validation_generator)
```
5. 测试模型的准确率:
```python
test_loss, test_accuracy = model.evaluate(validation_generator)
print(f"Test accuracy: {test_accuracy * 100:.2f}%")
```
阅读全文