使用卷积神经网络实现猫狗分类任务代码
时间: 2023-06-30 07:14:22 浏览: 136
好的,以下是使用卷积神经网络实现猫狗分类任务的代码示例:
```python
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 设置训练集和测试集的路径
train_dir = 'path/to/training/dataset'
test_dir = 'path/to/testing/dataset'
# 设置图像的大小和批次大小
img_height, img_width = 150, 150
batch_size = 32
# 创建数据生成器
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='binary')
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='binary')
# 构建卷积神经网络模型
model = Sequential([
Conv2D(32, (3,3), activation='relu', input_shape=(img_height, img_width, 3)),
MaxPooling2D((2,2)),
Conv2D(64, (3,3), activation='relu'),
MaxPooling2D((2,2)),
Conv2D(128, (3,3), activation='relu'),
MaxPooling2D((2,2)),
Conv2D(128, (3,3), activation='relu'),
MaxPooling2D((2,2)),
Flatten(),
Dense(512, activation='relu'),
Dense(1, activation='sigmoid')
])
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(train_generator,
epochs=10,
validation_data=test_generator)
# 评估模型
test_loss, test_acc = model.evaluate(test_generator)
print('Test accuracy:', test_acc)
```
需要注意的是,这是一个简单的示例代码,实际应用中可能需要更加复杂的网络结构和更多的训练参数来提高模型的性能。
阅读全文