如何解决在 python 中为 scikit-learn 高斯内核使用两个输入X 和 Y
我正在尝试使用 python 中的 sklearn 为内核岭回归构建高斯内核。
例如,这是我使用 RBF 内核的示例。
from sklearn.datasets import load_iris
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
X,y = load_iris(return_X_y=True)
kernel = 1.0 * RBF(1.0)
gpc = GaussianProcessClassifier(kernel=kernel,random_state=0).fit(X,y)
gpc.predict(X)
但是,在内核的__call__
函数中,似乎不能只取X作为输入,所以作为额外的输入Y(默认为None):__call__(X,Y=None,eval_gradient=False)
。
我发现的所有例子都只是将 X 作为执行内核的参数。
是否有使用所有两个参数 X 和 Y 来构建内核的示例,以及在这种情况下拟合和预测函数的外观?
这是我正在尝试构建的内核类
class KrrInteractKernel2(GenericKernelMixin,Kernel):
def __init__(self,z=None):
self.z = z # this does nothing,_init_ function is required
def __call__(self,X,eval_gradient=False):
"""Return the kernel k(X,Y) and optionally its gradient.
Parameters
----------
X : array-like of shape (n_samples_X,n_features) or list of object
Left argument of the returned kernel k(X,Y)
Y : array-like of shape (n_samples_X,n_features) or list of object,\
default=None
Right argument of the returned kernel k(X,Y). If None,k(X,X)
is evaluated instead.
eval_gradient : bool,default=False
Determines whether the gradient with respect to the log of
the kernel hyperparameter is computed.
Only supported when Y is None.
Returns
-------
K : ndarray of shape (n_samples_X,n_samples_Y)
Kernel k(X,Y)
K_gradient : ndarray of shape (n_samples_X,n_samples_X,n_dims),\
optional
The gradient of the kernel k(X,X) with respect to the log of the
hyperparameter of the kernel. Only returned when eval_gradient
is True.
"""
if Y is None:
Y = X
elif eval_gradient:
raise ValueError("Gradient can only be evaluated when Y is None.")
for i in np.unique(Y):
x_ = X[np.where(Y == i)]
n_ = x_.shape[0]
m_ = x_ @ x_.T / n_
if i==1:
K = m_
else:
K = block_diag(K,m_)
if eval_gradient:
if not self.hyperparameter_constant_value.fixed:
return (K,np.full((_num_samples(X),_num_samples(X),1),self.constant_value,dtype=np.array(self.constant_value).dtype))
else:
return K,np.empty((_num_samples(X),0))
else:
return K
def diag(self,X):
return np.diag(X)
def is_stationary(self):
return False
def clone_with_theta(self,theta):
cloned = clone(self)
cloned.theta = theta
return cloned
我想在 X
和 Y
函数中使用 fit
和 predict
。
我希望是这样的:
kr = KernelRidge(alpha=0.1,kernel=krrInteractKernel)
kr.fit([X,Y],yobs)
kr.predict([X,yobs)
非常感谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。