SKLearner Home | About | Contact | Examples

Scikit-Learn KernelCenterer for Data Preprocessing

KernelCenterer is a scikit-learn transformer used to center a kernel matrix. It ensures that the mean of each column in the kernel matrix is zero. KernelCenterer does not require any hyperparameters.

It is appropriate for preprocessing kernel matrices in algorithms like kernel PCA, kernel SVMs, or any other kernel methods.

from sklearn.preprocessing import KernelCenterer
import numpy as np

# create a synthetic kernel matrix
K = np.array([[1, 2, 3],
              [2, 4, 6],
              [3, 6, 9]])

# create KernelCenterer instance
transformer = KernelCenterer()

# fit and transform the kernel matrix
K_centered = transformer.fit_transform(K)

print("Original Kernel Matrix:\n", K)
print("Centered Kernel Matrix:\n", K_centered)

Running the example gives an output like:

Original Kernel Matrix:
 [[1 2 3]
 [2 4 6]
 [3 6 9]]
Centered Kernel Matrix:
 [[ 1.  0. -1.]
 [ 0.  0.  0.]
 [-1.  0.  1.]]

The steps are as follows:

  1. First, a synthetic kernel matrix is generated using numpy.array(). This creates a 3x3 matrix to simulate a kernel matrix.

  2. Next, a KernelCenterer instance is instantiated without any parameters.

  3. The kernel matrix is then centered using the fit_transform() method, which fits the KernelCenterer to the data and transforms it.

  4. The original and centered kernel matrices are displayed to compare the transformation.

This example demonstrates how to use KernelCenterer for preprocessing kernel matrices, ensuring they are centered for further machine learning applications.



See Also