猫狗分类识别python
时间: 2023-10-11 20:08:01 浏览: 116
猫狗分类识别是通过构建一个图像分类网络,使用训练样本集合中的猫狗图像训练该模型,以实现对测试样本集合中动物的识别并将其分为猫类或者狗类。在图像识别研究领域,常用的数据集之一是Cat_vs_Dogs(猫狗识别数据集),该数据集包含了大量的猫和狗的照片,可以用来验证算法的效果。
以下是一个实现猫狗分类识别的Python代码示例:
```python
import tensorflow as tf
from tensorflow import keras
from keras.preprocessing.image import ImageDataGenerator
# 设置训练集和测试集的路径
train_dir = 'path_to_train_directory'
test_dir = 'path_to_test_directory'
# 数据增强
train_datagen = ImageDataGenerator(
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' # 填充像素的策略
)
test_datagen = ImageDataGenerator(rescale=1./255)
# 加载训练集和测试集数据
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary' # 二分类
)
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary'
)
# 构建模型
model = keras.models.Sequential([
keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
keras.layers.MaxPooling2D(2, 2),
keras.layers.Conv2D(64, (3, 3), activation='relu'),
keras.layers.MaxPooling2D(2, 2),
keras.layers.Conv2D(128, (3, 3), activation='relu'),
keras.layers.MaxPooling2D(2, 2),
keras.layers.Conv2D(128, (3, 3), activation='relu'),
keras.layers.MaxPooling2D(2, 2),
keras.layers.Flatten(),
keras.layers.Dense(512, activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
])
# 编译模型
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
# 训练模型
history = model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=100,
validation_data=test_generator,
validation_steps=50
)
# 保存模型
model.save('cat_dog_classifier.h5')
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)