朴素贝叶斯分类器 Python代码 用于汽车满意度数据集的分类 数据集特征有购买价格,保养价格,门的个数,载客数,车身的大小,安全等级,汽车满意度(unacc,accc)
时间: 2024-05-29 11:11:41 浏览: 170
朴素贝叶斯分类的代码
4星 · 用户满意度95%
import pandas as pd
import numpy as np
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 读取数据集
data = pd.read_csv('car.csv')
# 将数据集中的字符串转为数字
data = data.replace('low', 1)
data = data.replace('med', 2)
data = data.replace('high', 3)
data = data.replace('vhigh', 4)
data = data.replace('5more', 5)
data = data.replace('more', 6)
data = data.replace('small', 1)
data = data.replace('med', 2)
data = data.replace('big', 3)
data = data.replace('low', 1)
data = data.replace('med', 2)
data = data.replace('high', 3)
data = data.replace('unacc', 0)
data = data.replace('acc', 1)
# 将特征和标签分离
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 构建朴素贝叶斯分类器
clf = GaussianNB()
clf.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = clf.predict(X_test)
# 计算分类器的准确率
accuracy = accuracy_score(y_test, y_pred)
print("朴素贝叶斯分类器的准确率为:{:.2f}%".format(accuracy*100))
阅读全文