用python写一个寻找好瓜的朴素贝叶斯代码
时间: 2023-12-17 17:20:44 浏览: 79
python朴素贝叶斯代码
朴素贝叶斯是一种常用的分类算法,在数据挖掘和机器学习领域得到了广泛应用。下面是一个用 Python 实现朴素贝叶斯算法来判断西瓜好坏的示例代码:
```python
import pandas as pd
import numpy as np
class NaiveBayes:
def __init__(self):
self.prior = {} # 存储先验概率
self.conditional_probability = {} # 存储条件概率
def fit(self, X, y):
self.X = X
self.y = y
self.classes = np.unique(y) # 获取类别
self.feature_names = X.columns.tolist() # 获取特征名
for c in self.classes:
self.prior[c] = len(y[y == c]) / len(y) # 计算先验概率
self.conditional_probability[c] = {} # 初始化条件概率字典
for feature in self.feature_names:
feature_values = np.unique(X[feature]) # 获取特征值
for value in feature_values:
# 计算条件概率
self.conditional_probability[c][(feature, value)] = \
len(X[(y == c) & (X[feature] == value)]) / len(X[y == c])
def predict(self, X):
y_pred = []
for index, row in X.iterrows():
max_prob = -1
max_class = None
for c in self.classes:
# 计算后验概率
p = self.prior[c]
for feature in self.feature_names:
value = row[feature]
p *= self.conditional_probability[c][(feature, value)]
if p > max_prob:
max_prob = p
max_class = c
y_pred.append(max_class)
return y_pred
# 加载西瓜数据集
watermelon = pd.read_csv('watermelon.csv')
X = watermelon.drop(columns=['编号', '好瓜'])
y = watermelon['好瓜']
# 划分训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# 训练模型
nb = NaiveBayes()
nb.fit(X_train, y_train)
# 预测测试集
y_pred = nb.predict(X_test)
print('测试集准确率:', sum(y_pred == y_test) / len(y_test))
```
参考资料:
- [使用 Python 实现朴素贝叶斯算法](https://zhuanlan.zhihu.com/p/33544836)
阅读全文