Lui*_*rzi 13 python machine-learning gaussian svm scikit-learn
我想用Python实现我自己的高斯内核,只是为了锻炼.我正在使用:
sklearn.svm.SVC(kernel=my_kernel)
但我真的不明白发生了什么.
我期待的功能my_kernel与的列被称为X
矩阵作为参数,而不是我得到了它一个名为X
,X
作为参数.看一下这些例子,事情并不清楚.
我错过了什么?
这是我的代码:
'''
Created on 15 Nov 2014
@author: Luigi
'''
import scipy.io
import numpy as np
from sklearn import svm
import matplotlib.pyplot as plt
def svm_class(fileName):
data = scipy.io.loadmat(fileName)
X = data['X']
y = data['y']
f = svm.SVC(kernel = 'rbf', gamma=50, C=1.0)
f.fit(X,y.flatten())
plotData(np.hstack((X,y)), X, f)
return
def plotData(arr, X, f):
ax = plt.subplot(111)
ax.scatter(arr[arr[:,2]==0][:,0], arr[arr[:,2]==0][:,1], c='r', marker='o', label='Zero')
ax.scatter(arr[arr[:,2]==1][:,0], arr[arr[:,2]==1][:,1], c='g', marker='+', label='One')
h = .02 # step size in the mesh
# create a mesh to plot in
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
Z = f.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contour(xx, yy, Z)
plt.xlim(np.min(arr[:,0]), np.max(arr[:,0]))
plt.ylim(np.min(arr[:,1]), np.max(arr[:,1]))
plt.show()
return
def gaussian_kernel(x1,x2):
sigma = 0.5
return np.exp(-np.sum((x1-x2)**2)/(2*sigma**2))
if __name__ == '__main__':
fileName = 'ex6data2.mat'
svm_class(fileName)
Run Code Online (Sandbox Code Playgroud)
art*_*omp 18
阅读了上面的答案,经过一些其他问题和站点(1,2,3,4,5),我把这个共同为高斯核svm.SVC()
.
打电话svm.SVC()
给kernel=precomputed
.
然后计算Gram Matrix aka Kernel Matrix(通常缩写为K).
然后使用此Gram Matrix作为第一个参数(即 X)svm.SVC().fit()
:
我从以下代码开始:
C=0.1
model = svmTrain(X, y, C, "gaussian")
Run Code Online (Sandbox Code Playgroud)
调用sklearn.svm.SVC()
中svmTrain()
,然后sklearn.svm.SVC().fit()
:
from sklearn import svm
if kernelFunction == "gaussian":
clf = svm.SVC(C = C, kernel="precomputed")
return clf.fit(gaussianKernelGramMatrix(X,X), y)
Run Code Online (Sandbox Code Playgroud)
Gram Matrix计算 - 用作参数sklearn.svm.SVC().fit()
- 在gaussianKernelGramMatrix()
以下位置完成:
import numpy as np
def gaussianKernelGramMatrix(X1, X2, K_function=gaussianKernel):
"""(Pre)calculates Gram Matrix K"""
gram_matrix = np.zeros((X1.shape[0], X2.shape[0]))
for i, x1 in enumerate(X1):
for j, x2 in enumerate(X2):
gram_matrix[i, j] = K_function(x1, x2)
return gram_matrix
Run Code Online (Sandbox Code Playgroud)
用于gaussianKernel()
在x1和x2之间获得径向基函数核(基于以x1为中心的高斯分布的相似性度量,sigma = 0.1):
def gaussianKernel(x1, x2, sigma=0.1):
# Ensure that x1 and x2 are column vectors
x1 = x1.flatten()
x2 = x2.flatten()
sim = np.exp(- np.sum( np.power((x1 - x2),2) ) / float( 2*(sigma**2) ) )
return sim
Run Code Online (Sandbox Code Playgroud)
然后,一旦使用此自定义内核训练模型,我们使用"测试数据和训练数据之间的[自定义]内核"进行预测:
predictions = model.predict( gaussianKernelGramMatrix(Xval, X) )
Run Code Online (Sandbox Code Playgroud)
简而言之,要使用自定义SVM高斯内核,您可以使用以下代码段:
import numpy as np
from sklearn import svm
def gaussianKernelGramMatrixFull(X1, X2, sigma=0.1):
"""(Pre)calculates Gram Matrix K"""
gram_matrix = np.zeros((X1.shape[0], X2.shape[0]))
for i, x1 in enumerate(X1):
for j, x2 in enumerate(X2):
x1 = x1.flatten()
x2 = x2.flatten()
gram_matrix[i, j] = np.exp(- np.sum( np.power((x1 - x2),2) ) / float( 2*(sigma**2) ) )
return gram_matrix
X=...
y=...
Xval=...
C=0.1
clf = svm.SVC(C = C, kernel="precomputed")
model = clf.fit( gaussianKernelGramMatrixFull(X,X), y )
p = model.predict( gaussianKernelGramMatrixFull(Xval, X) )
Run Code Online (Sandbox Code Playgroud)
出于效率原因,SVC假设您的内核是接受两个样本矩阵的函数,X
并且Y
(仅在训练期间将使用两个相同的函数)并且您应该返回一个矩阵 G
,其中:
G_ij = K(X_i, Y_j)
Run Code Online (Sandbox Code Playgroud)
并且K
是你的"点级"核函数.
因此要么实现以这种通用方式工作的高斯内核,要么添加"代理"函数,如:
def proxy_kernel(X,Y,K):
gram_matrix = np.zeros((X.shape[0], Y.shape[0]))
for i, x in enumerate(X):
for j, y in enumerate(Y):
gram_matrix[i, j] = K(x, y)
return gram_matrix
Run Code Online (Sandbox Code Playgroud)
并使用它像:
from functools import partial
correct_gaussian_kernel = partial(proxy_kernel, K=gaussian_kernel)
Run Code Online (Sandbox Code Playgroud)