使用三种不同的机器学习模型写一个猫狗识别系统代码
时间: 2023-06-18 14:02:34 浏览: 114
好的,下面我为你提供三种不同的机器学习模型,用于编写猫狗识别系统代码。
## 模型1:卷积神经网络(CNN)
```python
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
# 加载数据集
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'train',
target_size=(150, 150),
batch_size=32,
class_mode='binary')
# 构建模型
model = Sequential([
Conv2D(16, 3, padding='same', activation='relu', input_shape=(150, 150, 3)),
MaxPooling2D(),
Conv2D(32, 3, padding='same', activation='relu'),
MaxPooling2D(),
Conv2D(64, 3, padding='same', activation='relu'),
MaxPooling2D(),
Flatten(),
Dense(512, activation='relu'),
Dense(1, activation='sigmoid')
])
# 编译模型
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(
train_generator,
steps_per_epoch=2000,
epochs=10,
validation_data=val_generator,
validation_steps=800)
```
## 模型2:支持向量机(SVM)
```python
import numpy as np
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from PIL import Image
# 加载数据集
X = []
y = []
for i in range(1000):
img = Image.open(f"train/cat.{i}.jpg")
img = img.resize((150, 150))
X.append(np.array(img))
y.append(0)
for i in range(1000):
img = Image.open(f"train/dog.{i}.jpg")
img = img.resize((150, 150))
X.append(np.array(img))
y.append(1)
X = np.array(X)
y = np.array(y)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 将图像数据拉平
X_train = X_train.reshape(X_train.shape[0], -1)
X_test = X_test.reshape(X_test.shape[0], -1)
# 构建模型
model = SVC(kernel='linear')
# 训练模型
model.fit(X_train, y_train)
# 预测结果
y_pred = model.predict(X_test)
# 计算准确率
acc = accuracy_score(y_test, y_pred)
print(f"Accuracy: {acc}")
```
## 模型3:深度神经网络(DNN)
```python
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.callbacks import EarlyStopping
from PIL import Image
# 加载数据集
X = []
y = []
for i in range(1000):
img = Image.open(f"train/cat.{i}.jpg")
img = img.resize((150, 150))
X.append(np.array(img))
y.append(0)
for i in range(1000):
img = Image.open(f"train/dog.{i}.jpg")
img = img.resize((150, 150))
X.append(np.array(img))
y.append(1)
X = np.array(X)
y = np.array(y)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 构建模型
model = Sequential([
Flatten(input_shape=(150, 150, 3)),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])
# 编译模型
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# 训练模型
early_stopping = EarlyStopping(monitor='val_loss', patience=3)
model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test), callbacks=[early_stopping])
# 计算准确率
loss, acc = model.evaluate(X_test, y_test)
print(f"Accuracy: {acc}")
```
阅读全文