简体   繁体   English

在Sci-kit Learn中将参数解析为SVM的自定义内核功能

[英]Parse parameter to custom kernel function of SVM in Sci-kit Learn

I followed the tutorial SVM with custom kernel and tried to use custom kernel in SVM. 我在教程SVM中使用了自定义内核,并尝试在SVM中使用自定义内核。 For example, I implement the polynomial kernel function as follows: 例如,我实现多项式内核函数,如下所示:

   def poly_kernel(x, y):
       degree = 3
       return np.dot(x, y.T) ** 3

Then the result seem very similar to the original 'poly' with degree of 3. However it comes with a problem that I do not know how to parse the degree as a parameter to the kernel function. 然后结果似乎与原始的度数为3的“多边形”非常相似。但是它带来的一个问题是,我不知道如何将度数解析为内核函数的参数。

For example, I build the Support Vector Regression as follows: 例如,我按以下方法构建支持向量回归

    # X is some data
    # y is some target
    svr = SVR(kernel=poly_kernel, C=1e3, degree=4)
    y = svr.fit(X, y).predict(X)

It does not seem to parse the parameter to the kernel correctly. 似乎无法正确地将参数解析到内核。 I also tried named arguments in the kernel function 我也在内核函数中尝试了命名参数

    def poly_kernel(x, y, **kwargs):
        degree = 3
        try:
            degree = kwargs.get('degree')
        except:
            pass
        return np.dot(x, y.T) ** 3

But it does not work. 但这行不通。

So is there any way to parse the parameters correctly in this case? 那么在这种情况下有什么方法可以正确解析参数吗?

Thanks in advance. 提前致谢。

The kernel function can be dynamically constructed in this case. 在这种情况下,可以动态构造内核功能。 We can use lambda get a anonymous function as a variable. 我们可以使用lambda获取一个匿名函数作为变量。

For example: 例如:

    def linear_kernel(c = 0):
        return lambda x, y: np.dot(x, y.T) + c

When we want to use it, we just do: 当我们想使用它时,我们只需:

    lkf = linear_kernel(c=20)
    svr_linear = SVR(kernel=lkf)
    y_linear = svr_linear.fit(X, y).predict(X)

and I just ignore the parameters when I call SVR(). 当我调用SVR()时,我只是忽略了参数。

However I am not sure if it is a dirty way, but it works at least. 但是我不确定这是否是一种肮脏的方式,但是至少可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM