载入库
%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仓库。
本文通过将不同的核函数应用于一张图片,并通过3D图像的形式展现出来,实现了对几种常见核函数(如内积核、多项式核、径向基核、高斯核及正切核)作用的直观展示。
1375

被折叠的 条评论
为什么被折叠?



