猫狗分类任务中朴素贝叶斯与循环神经网络的性能比较的代码
时间: 2024-12-15 18:17:50 浏览: 7
基于BP和朴素贝叶斯的时间序列分类模型
在猫狗分类任务中,朴素贝叶斯(Naive Bayes)模型和循环神经网络(Recurrent Neural Networks, RNNs)是两种常见的机器学习模型。朴素贝叶斯简单易懂,尤其适合处理高维特征的数据,比如图像数据,而RNN则擅长处理序列数据,例如时间序列或自然语言。
为了比较这两种模型的性能,你需要编写一些代码:
```python
# 导入所需库
from sklearn.model_selection import train_test_split
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
from keras.utils import to_categorical
from sklearn.naive_bayes import GaussianNB
# 加载数据集(例如使用Keras的ImageDataGenerator加载)
(x_train, y_train), (x_test, y_test) = ... # 假设已经预处理好的猫狗图片数据
# 数据预处理
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
y_train = to_categorical(y_train, num_classes=2)
y_test = to_categorical(y_test, num_classes=2)
# 朴素贝叶斯模型
gnb = GaussianNB()
gnb.fit(x_train, y_train)
nb_pred = gnb.predict(x_test)
# 循环神经网络模型
rnn_model = Sequential([
LSTM(128, input_shape=(img_height, img_width, 1)),
Dropout(0.2),
Dense(64, activation='relu'),
Dropout(0.2),
Dense(2, activation='softmax')
])
rnn_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
rnn_model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
# 计算性能指标
nb_accuracy = accuracy_score(y_test.argmax(axis=1), nb_pred.argmax(axis=1))
rnn_accuracy = rnn_model.evaluate(x_test, y_test)[1]
print("朴素贝叶斯模型准确率:", nb_accuracy)
print("循环神经网络模型准确率:", rnn_accuracy)
阅读全文