您的位置:首页 > 编程语言 > Python开发

通过图像对核函数进行直观理解

2017-03-16 14:25 609 查看

载入库

%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import numpy.linalg as la


几个比较著名的核函数

内积

def linear():
return lambda x, y: np.inner(x, y)


多项式

def polykernel(dimension, offset):
return lambda x, y: (offset + np.inner(x, y)) ** dimension


径向基

def radial_basis(gamma=10):
return lambda x, y: np.exp(-gamma*la.norm(np.subtract(x, y)))


高斯

def gaussian(sigma):
return lambda x, y: \
np.exp(-np.sqrt(la.norm(x-y) ** 2 / (2 * sigma ** 2)))


正切

def hyperbolic_tangent(kappa, c):
return lambda x, y: np.tanh(kappa * np.dot(x, y) + c)


通过图像来直观地展示核函数的作用

选定图像



读入图像

img=plt.imread("./example.jpg")


图像通道合并

img=img.max(axis=2)


图像显示

plt.imshow(img)
plt.show()




核函数效果展示

准备画布

X = np.arange(-1.5, 1.5, 0.01)
Y = np.arange(-1.5, 1.5, 0.01)
X, Y = np.meshgrid(X, Y)

fig = plt.figure()
ax = Axes3D(fig)


初始图像

ax.plot_surface(X,Y, img)




内积核函数

数据填充

img4kernel=np.zeros((300,300))
for i,x_i in enumerate(img[:,:]):
for j,x_j in enumerate(img[:,:]):
img4kernel[i,j]=linear()(x_i,x_j)


转换后的图像展示

ax.plot_surface(X,Y, img4kernel)




plt.imshow(img4kernel)




多项式核函数

数据填充

img4kernel=np.zeros((300,300))
for i,x_i in enumerate(img[:,:]):
for j,x_j in enumerate(img[:,:]):
img4kernel[i,j]=polykernel(2,0)(x_i,x_j)


转换后的图像展示

ax.plot_surface(X,Y, img4kernel)




plt.imshow(img4kernel)




径向基核函数

数据填充

img4kernel=np.zeros((300,300))
for i,x_i in enumerate(img[:,:]):
for j,x_j in enumerate(img[:,:]):
img4kernel[i,j]=radial_basis()(x_i,x_j)


转换后的图像展示

ax.plot_surface(X,Y, img4kernel)




plt.imshow(img4kernel)




高斯核函数

数据填充

img4kernel=np.zeros((300,300))
for i,x_i in enumerate(img[:,:]):
for j,x_j in enumerate(img[:,:]):
img4kernel[i,j]=gaussian(0.5)(x_i,x_j)


转换后的图像展示

ax.plot_surface(X,Y, img4kernel)




plt.imshow(img4kernel)




正切核函数

数据填充

img4kernel=np.zeros((300,300))
for i,x_i in enumerate(img[:,:]):
for j,x_j in enumerate(img[:,:]):
img4kernel[i,j]=hyperbolic_tangent(2,2)(x_i,x_j)


转换后的图像展示

ax.plot_surface(X,Y, img4kernel)




plt.imshow(img4kernel)




总结

更多关于核函数的内容可以参考该github仓库
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息