python猫狗大战代码_猫狗大战
时间: 2023-07-03 20:15:42 浏览: 267
以下是一个简单的猫狗大战代码示例:
```python
import os
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
# 定义数据路径和图像大小
path = 'data/'
img_size = 64
# 读取图像并将其转换为灰度图像
def read_img(path):
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
return cv2.resize(img, (img_size, img_size)).flatten()
# 读取数据集
def load_data():
data = []
labels = []
# 读取猫和狗的图像
for folder in os.listdir(path):
folder_path = os.path.join(path, folder)
for img in os.listdir(folder_path):
img_path = os.path.join(folder_path, img)
data.append(read_img(img_path))
if folder == 'cat':
labels.append(0)
else:
labels.append(1)
return data, labels
# 加载数据集
data, labels = load_data()
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42)
# 将数据集转换为numpy数组
X_train = np.array(X_train)
X_test = np.array(X_test)
y_train = np.array(y_train)
y_test = np.array(y_test)
# 将像素值缩放到0和1之间
X_train = X_train / 255.0
X_test = X_test / 255.0
# 定义模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(img_size, img_size, 1)))
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(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(X_train.reshape(-1, img_size, img_size, 1), y_train, epochs=20, batch_size=32, validation_data=(X_test.reshape(-1, img_size, img_size, 1), y_test))
# 评估模型
loss, accuracy = model.evaluate(X_test.reshape(-1, img_size, img_size, 1), y_test)
print('Test loss:', loss)
print('Test accuracy:', accuracy)
```
这个代码示例使用了一个简单的卷积神经网络来训练猫狗大战数据集。首先,它读取图像,并将其转换为灰度图像。然后,它将数据集分为训练集和测试集,并将像素值缩放到0和1之间。接下来,它定义了一个卷积神经网络模型,并使用Adam优化器和二元交叉熵损失函数对其进行编译。最后,它训练模型,并评估其性能。
阅读全文