用python实现朴素贝叶斯算法
时间: 2023-08-04 14:36:55 浏览: 121
Python实现的朴素贝叶斯算法经典示例【测试可用】
可以使用Python的scikit-learn库来实现朴素贝叶斯算法。
首先,需要导入库和数据集:
```python
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
```
接着,实例化高斯朴素贝叶斯分类器:
```python
# 实例化高斯朴素贝叶斯分类器
clf = GaussianNB()
```
然后,训练模型并进行预测:
```python
# 训练模型
clf.fit(X_train, y_train)
# 进行预测
y_pred = clf.predict(X_test)
```
最后,可以使用模型评估指标来评估模型的性能:
```python
from sklearn.metrics import accuracy_score, confusion_matrix
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# 计算混淆矩阵
confusion_mat = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:\n", confusion_mat)
```
完整的代码如下:
```python
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
# 实例化高斯朴素贝叶斯分类器
clf = GaussianNB()
# 训练模型
clf.fit(X_train, y_train)
# 进行预测
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# 计算混淆矩阵
confusion_mat = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:\n", confusion_mat)
```
阅读全文