高斯核函数(numpy和torch)
高斯核函数数学公式
torch
# """gaussian_kernel"""
Xmul,Ymul=torch.mul(X,X),torch.mul(Y,Y)
D2 = torch.sum(Xmul,dim=1,keepdim=True) \
+ torch.sum(Ymul,dim=1,keepdim=True).t() \
- 2 * torch.mm(X, Y.T)
W=torch.exp(-D2 / (2 * sigma ** 2))
return (W+W.T)/2
numpy
X,Y=X.cpu(),Y.cpu()
X = np.array(X)
Y = np.array(Y)
D2 = np.sum(X * X, axis=1, keepdims=True) \
+ np.sum(Y * Y, axis=1, keepdims=True).T \
- 2 * np.dot(X, Y.T)
W = np.exp(-D2 / (2 * sigma ** 2))
return (W + W.T) / 2