加载中...
朴素贝叶斯
发表于:2021-11-08 | 分类: 机器学习课程(魏)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from scipy.io import loadmat
import numpy as np
from sklearn.naive_bayes import BernoulliNB #伯努利分布,适用于离散型数据
from sklearn.naive_bayes import GaussianNB #高斯分布,适用于连续型数据
from sklearn.naive_bayes import MultinomialNB #多项式分布
from sklearn.model_selection import train_test_split

mnist=loadmat('mnist-original.mat')
x,y=mnist["data"],mnist["label"]
x=x.T
y=y[0]
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=5)
nb=BernoulliNB()
nb.fit(x_train,y_train)
a=nb.score(x_test,y_test)
print(a)


0.828
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import matplotlib.pyplot as plt
import numpy as np
from sklearn.naive_bayes import BernoulliNB #伯努利分布,适用于离散型数据
from sklearn.naive_bayes import GaussianNB #高斯分布,适用于连续型数据
from sklearn.naive_bayes import MultinomialNB #多项式分布,
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_blobs

x, y= make_blobs(n_samples = 1000, #生成300条数据
centers =5, #5类数据
cluster_std = 0.7, #方差一致
random_state = 8) #随机数种子
nb=GaussianNB()
nb.fit(x,y)
z=nb.predict(x)
a=nb.score(x,y)
print(a)

plt.figure()
plt.scatter(x[:,0], x[:,1],c=y)
plt.figure()
plt.scatter(x[:,0], x[:,1],c=z)
plt.show()

0.982

png

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import numpy as np
import pandas as pd
from sklearn.datasets import make_moons
import matplotlib.pyplot as plt
from sklearn.naive_bayes import BernoulliNB #伯努利分布,适用于离散型数据
from sklearn.naive_bayes import GaussianNB #高斯分布,适用于连续型数据
from sklearn.naive_bayes import MultinomialNB #多项式分布

from sklearn.model_selection import cross_val_score as cr#调用交叉检验函数
n_samples = 600
x,y=make_moons(n_samples=n_samples, noise=0.1,random_state=8)
x=x+2;
#clf= MultinomialNB()
clf= GaussianNB()
clf.fit(x,y)
#clf.predict([x])
xmin,xmax=x[:,0].min()-1,x[:,0].max()+1
ymin,ymax=x[:,1].min()-1,x[:,1].max()+1

xx,yy=np.meshgrid(np.arange(xmin,xmax,0.02),np.arange(ymin,ymax,0.02))

xf=np.c_[xx.ravel(),yy.ravel()];
z=clf.predict(xf)
z=z.reshape(xx.shape)
plt.pcolormesh(xx,yy,z,cmap=plt.cm.Pastel1)
plt.scatter(x[:,0],x[:,1],c=y)

print(cr(clf,x,y,cv=5,scoring="accuracy"))

plt.show()

[0.9        0.88333333 0.9        0.85833333 0.86666667]


c:\users\administrator\appdata\local\programs\python\python37\lib\site-packages\ipykernel_launcher.py:25: MatplotlibDeprecationWarning: shading='flat' when X and Y have the same dimensions as C is deprecated since 3.3.  Either specify the corners of the quadrilaterals with X and Y, or pass shading='auto', 'nearest' or 'gouraud', or set rcParams['pcolor.shading'].  This will become an error two minor releases later.

png

1

上一篇:
拟合
下一篇:
线性规划
本文目录
本文目录