Iris_GaussianNB:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn.preprocessing import StandardScaler, MinMaxScaler, PolynomialFeatures
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
def iris_type(s):
it = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}
return it[s]
if __name__ == "__main__":
data = pd.read_csv('..\\8.Regression\\iris.data', header=None)
x, y = data[np.arange(4)], data[4]
y = pd.Categorical(values=y).codes
feature_names = u'花萼长度', u'花萼宽度', u'花瓣长度', u'花瓣宽度'
features = [0,1]
x = x[features]
x, x_test, y, y_test = train_test_split(x, y, train_size=0.7, random_state=0)
priors = np.array((1,2,4), dtype=float)
priors /= priors.sum()
gnb = Pipeline([
('sc', StandardScaler()),
('poly', PolynomialFeatures(degree=1)),
('clf', GaussianNB(priors=priors))]) # 由于鸢尾花数据是样本均衡的,其实不需要设置先验值
# gnb = KNeighborsClassifier(n_neighbors=3).fit(x, y.ravel())
gnb.fit(x, y.ravel())
y_hat = gnb.predict(x)
print '训练集准确度: %.2f%%' % (100 * accuracy_score(y, y_hat))
y_test_hat = gnb.predict(x_test)
print '测试集准确度:%.2f%%' % (100 * accuracy_score(y_test, y_test_hat)) # 画图
N, M = 500, 500 # 横纵各采样多少个值
x1_min, x2_min = x.min()
x1_max, x2_max = x.max()
t1 = np.linspace(x1_min, x1_max, N)
t2 = np.linspace(x2_min, x2_max, M)
x1, x2 = np.meshgrid(t1, t2) # 生成网格采样点
x_grid = np.stack((x1.flat, x2.flat), axis=1) # 测试点
mpl.rcParams['font.sans-serif'] = [u'simHei']
mpl.rcParams['axes.unicode_minus'] = False
cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
y_grid_hat = gnb.predict(x_grid) # 预测值
y_grid_hat = y_grid_hat.reshape(x1.shape)
plt.figure(facecolor='w')
plt.pcolormesh(x1, x2, y_grid_hat, cmap=cm_light) # 预测值的显示
plt.scatter(x[features[0]], x[features[1]], c=y, edgecolors='k', s=50, cmap=cm_dark)
plt.scatter(x_test[features[0]], x_test[features[1]], c=y_test, marker='^', edgecolors='k', s=120, cmap=cm_dark)
plt.xlabel(feature_names[features[0]], fontsize=13)
plt.ylabel(feature_names[features[1]], fontsize=13)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.title(u'GaussianNB对鸢尾花数据的分类结果', fontsize=18)
plt.grid(True)
plt.show()
MarkovModel:
import numpy as np
import matplotlib.pyplot as plt
import os
from matplotlib import animation
from PIL import Image
def update(f):
global loc
if f == 0:
loc = loc_prime
next_loc = np.zeros((m, n), dtype=np.float)
for i in np.arange(m):
for j in np.arange(n):
next_loc[i, j] = calc_next_loc(np.array([i, j]), loc, directions)
loc = next_loc / np.max(next_loc)
im.set_array(loc)
# Save
if save_image:
if f % 3 == 0:
image_data = plt.cm.coolwarm(loc) * 255
image_data, _ = np.split(image_data, (-1, ), axis=2)
image_data = image_data.astype(np.uint8).clip(0, 255)
output = '.\\Pic2\\'
if not os.path.exists(output):
os.mkdir(output)
a = Image.fromarray(image_data, mode='RGB')
a.save('%s%d.png' % (output, f))
return [im]
def calc_next_loc(now, loc, directions):
near_index = np.array([(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)])
directions_index = np.array([7, 6, 5, 0, 4, 1, 2, 3])
nn = now + near_index
ii, jj = nn[:, 0], nn[:, 1]
ii[ii >= m] = 0
jj[jj >= n] = 0
return np.dot(loc[ii, jj], directions[ii, jj, directions_index])
if __name__ == '__main__':
np.set_printoptions(suppress=True, linewidth=300, edgeitems=8)
np.random.seed(0)
save_image = False
style = 'Sin' # Sin/Direct/Random
m, n = 50, 100
directions = np.random.rand(m, n, 8)
if style == 'Direct':
directions[:,:,1] = 10
elif style == 'Sin':
x = np.arange(n)
y_d = np.cos(6*np.pi*x/n)
theta = np.empty_like(x, dtype=np.int)
theta[y_d > 0.5] = 1
theta[~(y_d > 0.5) & (y_d > -0.5)] = 0
theta[~(y_d > -0.5)] = 7
directions[:, x.astype(np.int), theta] = 10
directions[:, :] /= np.sum(directions[:, :])
print directions
loc = np.zeros((m, n), dtype=np.float)
loc[m/2, n/2] = 1
loc_prime = np.empty_like(loc)
loc_prime = loc
fig = plt.figure(figsize=(8, 6), facecolor='w')
im = plt.imshow(loc/np.max(loc), cmap='coolwarm')
anim = animation.FuncAnimation(fig, update, frames=300, interval=50, blit=True)
plt.tight_layout(1.5)
plt.show()