朴素贝叶斯算法python实现
时间: 2023-09-30 09:03:43 浏览: 99
朴素贝叶斯算法是一种基于贝叶斯定理的机器学习算法,它在分类和预测问题中被广泛应用。下面是朴素贝叶斯算法的Python实现。
首先,我们需要导入必要的库:
```python
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
然后,我们加载数据集并进行预处理:
```python
# Load iris dataset
iris = datasets.load_iris()
# Convert iris dataset to pandas dataframe
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= iris['feature_names'] + ['target'])
# Split dataset into features and labels
X = df.drop('target', axis=1)
y = df['target']
# Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,我们使用GaussianNB类来训练模型:
```python
# Train the model
model = GaussianNB()
model.fit(X_train, y_train)
```
最后,我们使用测试集来评估模型的性能:
```python
# Make predictions on test set
y_pred = model.predict(X_test)
# Calculate accuracy score
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
完整的代码如下:
```python
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Load iris dataset
iris = datasets.load_iris()
# Convert iris dataset to pandas dataframe
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= iris['feature_names'] + ['target'])
# Split dataset into features and labels
X = df.drop('target', axis=1)
y = df['target']
# Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train the model
model = GaussianNB()
model.fit(X_train, y_train)
# Make predictions on test set
y_pred = model.predict(X_test)
# Calculate accuracy score
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
阅读全文