高斯樸素貝葉斯算法通常用于特征變量是連續變量,符合高素分布的情況。
使用高斯樸素貝葉斯算法對鳶尾花數據集進行分類
"""
使用高斯貝葉斯堆鳶尾花進行分類
"""
#導入需要的庫
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
#導入數據
x,y = load_iris().data,load_iris().target
#劃分數據集
x_train,x_test,y_train,y_test = train_test_split(x,y,random_state=1, test_size=50)
#定義和訓練模型
model = GaussianNB()
model.fit(x_train,y_train)
#模型評估
pred = model.predict(x_test)
print("測試集數據的預測標簽為",pred)
print("測試集數據的真實標簽為",y_test)
print("測試集共有%d條數據,其中預測錯誤的數據有%d條,預測準確率為%.2f"%(x_test.shape[0],(pred!=y_test).sum(),?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?accuracy_score(y_test,pred)))
?
輸出的結果為:
測試集數據的預測標簽為 [0 1 1 0 2 2 2 0 0 2 1 0 2 1 1 0 1 1 0 0 1 1 2 0 2 1 0 0 1 2 1 2 1 2 2 0 1
?0 1 2 2 0 1 2 1 2 0 0 0 1]
測試集數據的真實標簽為 [0 1 1 0 2 1 2 0 0 2 1 0 2 1 1 0 1 1 0 0 1 1 1 0 2 1 0 0 1 2 1 2 1 2 2 0 1
?0 1 2 2 0 2 2 1 2 0 0 0 1]
測試集共有50條數據,其中預測錯誤的數據有3條,預測準確率為0.94