import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
import matplotlib
%matplotlib inline #一个魔法函数,能让代码嵌入notebook中。
def make_meshgrid(x, y, h=.02):
x_min, x_max = x.min() - 1, x.max() + 1
y_min, y_max = y.min() - 1, y.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
return xx, yy
x=[1,2,3] , y=[4,5] ;
xx, yy = np.meshgrid(x,y) ;
xx = 1 2 3
1 2 3
yy = 4 4 4
5 5 5
x=[1,2] , y=[3,4,5] ;
xx, yy = np.meshgrid(x,y) ;
xx = 1 2
1 2
1 2
yy = 3 3
4 4
5 5
#x成行,行数等于y的长度。
#y成列,列数等于x的长度。
iris = datasets.load_iris()
X = iris.data[:, :2] #只读取前面两个属性
y = iris.target #读取标签值
& Sepal.Length(花萼长度),单位是cm;
& Sepal.Width(花萼宽度),单位是cm;
& Petal.Length(花瓣长度),单位是cm;
& Petal.Width(花瓣宽度),单位是cm;
种类:Iris Setosa(山鸢尾)、Iris Versicolour(杂色鸢尾),以及Iris Virginica(维吉尼亚鸢尾)。
clf = GaussianNB()
clf.fit(X,y)
title = ('GaussianBayesClassifier')
fig, ax = plt.subplots(figsize = (5, 5))
plt.subplots_adjust(wspace=0.4, hspace=0.4)
X0, X1 = X[:, 0], X[:, 1] #取样本的第一个属性,第二个属性
def plot_test_results(ax, clf, xx, yy, **params):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
ax.contourf(xx, yy, Z, **params)
xx, yy = make_meshgrid(X0, X1)
plot_test_results(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors='k')
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)
plt.show()