Kernel principal component analysis (kernel PCA) is an extension of principal component analysis (PCA) using techniques of kernel methods. Using a kernel, the originally linear operations of PCA are done in a reproducing kernel Hilbert space with a non-linear mapping.

*The code presented here is also part of the Accord.NET Framework. The Accord.NET Framework is a framework for developing machine learning, computer vision, computer audition, statistics and math applications. It is based on the already excellent AForge.NET Framework. Please see the starting guide for mode details. The latest version of the framework includes the latest version of this code plus many other statistics and machine learning tools.*

## Analysis Overview

KPCA is an extension of PCA to non-linear distributions. Instead of directly doing a PCA, the original data points are mapped into a higher-dimensional (possibly infinite-dimensional) feature space defined by a (usually nonlinear) function φ through a mathematical process called the “kernel trick”.

### The Kernel trick

The kernel trick is a very interesting technique, able to transform any algorithm that solely depends on the dot product between two vectors. To apply the trick, we replace all dot products in an algorithm with a kernel function. Thus, a linear algorithm can easily be transformed into a non-linear algorithm. This non-linear algorithm is equivalent to the linear algorithm operating in the range space of φ. However, because kernels are used, the φ function is never explicitly computed. This is desirable [8], as the high-dimensional space can have an arbitrary large dimensionality, or can be even infinite-dimensional (such as in the case the chosen kernel function is a Gaussian) and thus infeasible to compute.

Interesting video by Udi Aharoni demonstrating how points that are not linearly separable in a 2D space can almost always be linearly separated in a higher dimensional (3D) space.

### Principal Components in Kernel Space

Like in PCA, the overall idea is to perform a transformation that will maximize the variance of the captured variables while minimizing the overall covariance between those variables. Using the kernel trick, the covariance matrix is substituted by the Kernel matrix and the analysis is carried analogously in feature space. An Eigen value decomposition is performed and the eigenvectors are sorted in ascending order of Eigen values, so those vectors may form a basis in feature space that explain most of the variance in the data on its first dimensions.

However, because the principal components are in feature space, we will not be directly performing dimensionality reduction. Suppose that the number of observations** m** exceeds the input dimensionality **n**. In linear PCA, we can find at most** n** nonzero Eigen values. On the other hand, using Kernel PCA we can find up to **m** nonzero Eigen values because we will be operating on a **m **x** m** kernel matrix[2].

A more detailed discussion can be seen in the works of *Mika et al.* (Kernel PCA and De-Noising in Feature Spaces) and *Scholkopf et al.* (Nonlinear Component Analysis as a Kernel Eigenvalue Problem). A more accessible explanation of the topic is also available in the work from Ian Fasel.

### The pre-image problem

In standard PCA it was possible to revert the transformation, retrieving the original data points and enabling the use of PCA for compression* and denoising. However, as the results provided by kernel PCA live in some high dimensional feature space, they need not have pre-images in input space. In fact, even if it exists, it also need be not unique.

Thus, in KPCA, it is only possible to obtain an approximate pre-image for a given set of patterns projected on the feature space. This problem can (and has) been tackled by many approaches, some of them of iterative nature, but some closed-form solutions also exists. Typically those solutions make use of the fact that distances in feature space are related to distances in input space. Thus, those solutions try to achieve an optimal transformation that can embed those feature points in input space respecting those distances relationships.

One of the first solutions of this form were proposed by *Kwok and Tsang* in their paper “The Pre-Image Problem in Kernel Methods". A better approach is also described by *Bakir* on his thesis “Extensions to Kernel Dependency Estimation”, alongside with a nice comprehensive description on various other methods for handling the pre-image problem.

Note: actually the use of KPCA for compression is a bit limited, since one needs to store the original data set to compute transformations and its approximate reversion.

## Code Overview

Below is the main code behind KPCA. This is a direct, naive implementation of the algorithm that may not scale very well for very large datasets. It is implemented on top of the previous standard PCA code and thus on top of the AForge.NET Framework.

1 |
<span>/// <summary>Computes the Kernel Principal Component Analysis algorithm.</summary></span><br /><span>public</span> <span>override</span> <span>void</span> Compute()<br />{<br /> <span>int</span> rows = Source.GetLength(0);<br /> <span>int</span> cols = Source.GetLength(1);<br /><br /> <span>// Center (adjust) the source matrix</span><br /> sourceCentered = adjust(Source);<br /><br /><br /> <span>// Create the Gram (Kernel) Matrix</span><br /> <span>double</span>[,] K = <span>new</span> <span>double</span>[rows, rows];<br /> <span>for</span> (<span>int</span> i = 0; i < rows; i++)<br /> {<br /> <span>for</span> (<span>int</span> j = i; j < rows; j++)<br /> {<br /> <span>double</span> k = kernel.Kernel(sourceCentered.GetRow(i), sourceCentered.GetRow(j));<br /> K[i, j] = k; <span>// Kernel matrix is symmetric</span><br /> K[j, i] = k;<br /> }<br /> }<br /><br /><br /> <span>// Center the Gram (Kernel) Matrix</span><br /> <span>if</span> (centerFeatureSpace)<br /> K = centerKernel(K);<br /><br /><br /> <span>// Perform the Eigen Value Decomposition (EVD) of the Kernel matrix</span><br /> EigenValueDecomposition evd = <span>new</span> EigenValueDecomposition(K);<br /><br /> <span>// Gets the eigenvalues and corresponding eigenvectors</span><br /> <span>double</span>[] evals = evd.RealEigenValues;<br /> <span>double</span>[,] eigs = evd.EigenVectors;<br /><br /> <span>// Sort eigen values and vectors in ascending order</span><br /> <span>int</span>[] indices = <span>new</span> <span>int</span>[rows];<br /> <span>for</span> (<span>int</span> i = 0; i < rows; i++) indices[i] = i;<br /> Array.Sort(evals, indices, <span>new</span> AbsoluteComparer(<span>true</span>));<br /> eigs = eigs.Submatrix(0, rows - 1, indices);<br /><br /><br /> <span>// Normalize eigenvectors</span><br /> <span>if</span> (centerFeatureSpace)<br /> {<br /> <span>for</span> (<span>int</span> j = 0; j < rows; j++)<br /> {<br /> <span>double</span> eig = System.Math.Sqrt(System.Math.Abs(evals[j]));<br /> <span>for</span> (<span>int</span> i = 0; i < rows; i++)<br /> eigs[i, j] = eigs[i, j] / eig;<br /> }<br /> }<br /><br /><br /> <span>// Set analysis properties</span><br /> <span>this</span>.SingularValues = <span>new</span> <span>double</span>[rows];<br /> <span>this</span>.EigenValues = evals;<br /> <span>this</span>.ComponentMatrix = eigs;<br /><br /><br /> <span>// Project the original data into principal component space</span><br /> <span>double</span>[,] result = <span>new</span> <span>double</span>[rows, rows];<br /> <span>for</span> (<span>int</span> i = 0; i < rows; i++)<br /> <span>for</span> (<span>int</span> j = 0; j < rows; j++)<br /> <span>for</span> (<span>int</span> k = 0; k < rows; k++)<br /> result[i, j] += K[i, k] * eigs[k, j];<br /><br /> <span>this</span>.Result = result;<br /><br /><br /> <span>// Computes additional information about the analysis and creates the</span><br /> <span>// object-oriented structure to hold the principal components found.</span><br /> createComponents();<br />}<br /><br /><br /><br /><span>/// <summary>Projects a given matrix into the principal component space.</summary></span><br /><span>/// <param name="data">The matrix to be projected. The matrix should contain</span><br /><span>/// variables as columns and observations of each variable as rows.</param></span><br /><span>public</span> <span>override</span> <span>double</span>[,] Transform(<span>double</span>[,] data, <span>int</span> components)<br />{<br /> <span>int</span> rows = data.GetLength(0);<br /> <span>int</span> cols = data.GetLength(1);<br /> <span>int</span> N = sourceCentered.GetLength(0);<br /><br /> <span>// Center the data</span><br /> data = adjust(data);<br /><br /> <span>// Create the Kernel matrix</span><br /> <span>double</span>[,] K = <span>new</span> <span>double</span>[rows, N];<br /> <span>for</span> (<span>int</span> i = 0; i < rows; i++)<br /> <span>for</span> (<span>int</span> j = 0; j < N; j++)<br /> K[i, j] = kernel.Kernel(data.GetRow(i), sourceCentered.GetRow(j));<br /><br /> <span>// Center the Gram (Kernel) Matrix</span><br /> <span>if</span> (centerFeatureSpace)<br /> K = centerKernel(K);<br /><br /> <span>// Project into the kernel principal components</span><br /> <span>double</span>[,] result = <span>new</span> <span>double</span>[rows, components];<br /> <span>for</span> (<span>int</span> i = 0; i < rows; i++)<br /> <span>for</span> (<span>int</span> j = 0; j < components; j++)<br /> <span>for</span> (<span>int</span> k = 0; k < rows; k++)<br /> result[i, j] += K[i, k] * ComponentMatrix[k, j];<br /><br /> <span>return</span> result;<br />} |

The main code behind the reversion of the projection. It is a direct, naive implementation of the closed-form solution algorithm as proposed by Kwok and Tsang. Currently it is completely **not** optimized, but it gives an better overview of the algorithm on its essential form. The source code available to download may be better optimized in the future.

1 |
<span>/// <summary></span><br /><span>/// Reverts a set of projected data into it's original form. Complete reverse</span><br /><span>/// transformation is not always possible and is not even guaranteed to exist.</span><br /><span>/// </summary></span><br /><span>/// <remarks></span><br /><span>/// This method works using a closed-form MDS approach as suggested by</span><br /><span>/// Kwok and Tsang. It is currently a direct implementation of the algorithm</span><br /><span>/// without any kind of optimization.</span><br /><span>/// </span><br /><span>/// Reference:</span><br /><span>/// - http://cmp.felk.cvut.cz/cmp/software/stprtool/manual/kernels/preimage/list/rbfpreimg3.html</span><br /><span>/// </remarks></span><br /><span>/// <param name="data">The kpca-transformed data.</param></span><br /><span>/// <param name="neighbors">The number of nearest neighbors to use while constructing the pre-image.</param></span><br /><span>public</span> <span>double</span>[,] Revert(<span>double</span>[,] data, <span>int</span> neighbors)<br />{<br /> <span>int</span> rows = data.GetLength(0);<br /> <span>int</span> cols = data.GetLength(1);<br /><br /> <span>double</span>[,] reversion = <span>new</span> <span>double</span>[rows, sourceCentered.GetLength(1)];<br /><br /> <span>// number of neighbors cannot exceed the number of training vectors.</span><br /> <span>int</span> nn = System.Math.Min(neighbors, sourceCentered.GetLength(0));<br /><br /><br /> <span>// For each point to be reversed</span><br /> <span>for</span> (<span>int</span> p = 0; p < rows; p++)<br /> {<br /> <span>// 1. Get the point in feature space</span><br /> <span>double</span>[] y = data.GetRow(p);<br /><br /> <span>// 2. Select nn nearest neighbors of the feature space</span><br /> <span>double</span>[,] X = sourceCentered;<br /> <span>double</span>[] d2 = <span>new</span> <span>double</span>[Result.GetLength(0)];<br /> <span>int</span>[] inx = <span>new</span> <span>int</span>[Result.GetLength(0)];<br /><br /> <span>// 2.1 Calculate distances</span><br /> <span>for</span> (<span>int</span> i = 0; i < X.GetLength(0); i++)<br /> {<br /> inx[i] = i;<br /> d2[i] = kernel.Distance(y, Result.GetRow(i).Submatrix(y.Length));<br /> }<br /><br /> <span>// 2.2 Order them</span><br /> Array.Sort(d2, inx);<br /><br /> <span>// 2.3 Select nn neighbors</span><br /> inx = inx.Submatrix(nn);<br /> X = X.Submatrix(inx).Transpose(); <span>// X is in input space</span><br /> d2 = d2.Submatrix(nn); <span>// distances in input space</span><br /><br /><br /> <span>// 3. Create centering matrix</span><br /> <span>// H = eye(nn, nn) - 1 / nn * ones(nn, nn);</span><br /> <span>double</span>[,] H = Matrix.Identity(nn).Subtract(Matrix.Create(nn, 1.0 / nn));<br /><br /><br /> <span>// 4. Perform SVD</span><br /> <span>// [U,L,V] = svd(X*H);</span><br /> SingularValueDecomposition svd = <span>new</span> SingularValueDecomposition(X.Multiply(H));<br /> <span>double</span>[,] U = svd.LeftSingularVectors;<br /> <span>double</span>[,] L = Matrix.Diagonal(nn, svd.Diagonal);<br /> <span>double</span>[,] V = svd.RightSingularVectors;<br /><br /><br /> <span>// 5. Compute projections</span><br /> <span>// Z = L*V';</span><br /> <span>double</span>[,] Z = L.Multiply(V.Transpose());<br /><br /><br /> <span>// 6. Calculate distances</span><br /> <span>// d02 = sum(Z.^2)';</span><br /> <span>double</span>[] d02 = Matrix.Sum(Matrix.DotPow(Z,2));<br /><br /><br /> <span>// 7. Get the pre-image using z = -0.5*inv(Z')*(d2-d02)</span><br /> <span>double</span>[,] inv = Matrix.PseudoInverse(Z.Transpose());<br /> <span>double</span>[] z = (-0.5).Multiply(inv).Multiply(d2.Subtract(d02));<br /><br /><br /> <span>// 8. Project the pre-image on the original basis</span><br /> <span>// using x = U*z + sum(X,2)/nn;</span><br /> <span>double</span>[] x = (U.Multiply(z)).Add(Matrix.Sum(X.Transpose()).Multiply(1.0 / nn));<br /><br /><br /> <span>// 9. Store the computed pre-image.</span><br /> <span>for</span> (<span>int</span> i = 0; i < reversion.GetLength(1); i++)<br /> reversion[p, i] = x[i];<br /> }<br /><br /><br /><br /> <span>// if the data has been standardized or centered,</span><br /> <span>// we need to revert those operations as well</span><br /> <span>if</span> (<span>this</span>.Method == AnalysisMethod.Correlation)<br /> {<br /> <span>// multiply by standard deviation and add the mean</span><br /> <span>for</span> (<span>int</span> i = 0; i < reversion.GetLength(0); i++)<br /> <span>for</span> (<span>int</span> j = 0; j < reversion.GetLength(1); j++)<br /> reversion[i, j] = (reversion[i, j] * StandardDeviations[j]) + Means[j];<br /> }<br /> <span>else</span><br /> {<br /> <span>// only add the mean</span><br /> <span>for</span> (<span>int</span> i = 0; i < reversion.GetLength(0); i++)<br /> <span>for</span> (<span>int</span> j = 0; j < reversion.GetLength(1); j++)<br /> reversion[i, j] = reversion[i, j] + Means[j];<br /> }<br /><br /><br /> <span>return</span> reversion;<br />} |

## Using the Code

As with PCA, code usage is simple. First, choose a kernel implementing the *IKernel* interface then pass it to the *KernelPrincipalComponentAnalysis* constructor together with the data points.

1 |
<span> // Create a Gaussian kernel with sigma = 10.0</span><br /> Gaussian kernel = <span>new</span> Gaussian(10.0);<br /><br /> <span>// Creates a new Kernel Principal Component Analysis object</span><br /> var kpca = <span>new</span> KernelPrincipalComponentAnalysis(data, kernel); |

Then, simply call *Compute()* to perform the analysis. Once done, data about the analysis will be available through the object properties and transformations on additional data can be computed by calling *Transform()*.

1 |
<span> // Compute the Kernel Principal Component Analysis</span><br /> kpca.Compute();<br /><br /><span> // Perform the transformation of the data using two components</span><br /><span> double</span>[,] result = kpca.Transform(data, 2); |

## Sample Application

To demonstrate the use of KPCA, I created a simple Windows Forms Application which performs simple statistical analysis and KPCA transformations. It can also perform projection reversion by solving the approximate pre-image problem.

On left: Scholkopf Toy Example. Middle: Kernel principal components detected by the KPCA. Right: The two first dimensions obtained by the two first Kernel principal components.

Left: Wikipedia example. Middle: Projection using a **non-centered** Gaussian kernel. Right: Reconstruction of the original data using all Kernel principal components, showing some denoising ability.

#### Linear PCA as a special case

Additionally we may check that linear PCA is indeed a special case of kernel PCA by using a linear kernel on the example by *Lindsay Smith* on his A Tutorial On Principal Component Analysis.

## See also

- Kernel Functions for Machine Learning Applications
- Kernel Support Vector Machines (kSVMs)
- Principal Component Analysis (PCA)
- Linear Discriminant Analysis (LDA)
- Non-Linear Discriminant Analysis with Kernels
- Logistic Regression Analysis in C#

## References

- [1] BAKIR, Gokhan.
*Extensions to Kernel Dependency Estimation*. Doctorate Thesis.

Available in: http://opus.kobv.de/tuberlin/volltexte/2006/1256/pdf/bakir_goekhan.pdf - [2] FASEL, Ian.
*Scholkopf, Smola and Muller: Kernel PCA*.

Available in: http://cseweb.ucsd.edu/classes/fa01/cse291/kernelPCA_article.pdf - [3] HOFFMANN, Heiko.
*Unsupervised Learning of Visuomotor Associations*. Dissertation.

Available in: http://www.heikohoffmann.de/htmlthesis/hoffmann_diss.html. - [4] KWOK, James; TSANG, Ivor.
*The Pre-Image Problem in Kernel Methods*. Proceedings of the Twentieth International Conference on Machine Learning (ICML-2003), Washington DC, 2003.

Available in: http://www.hpl.hp.com/conferences/icml2003/papers/345.pdf - [5] KWOK, James; TSANG, Ivor.
*The Pre-Image Problem in Kernel Methods*. Proceedings of the Twentieth International Conference on Machine Learning (ICML-2003), Washington DC, 2003.

Available in: http://www.cse.ust.hk/~jamesk/papers/icml03_slides.pdf - [6] MIKA, Sebastian; SCHOLKOPF, Benhard; et al.
*Kernel PCA and De-Noising in Feature Spaces*.

Available in: http://www.cs.dartmouth.edu/farid/teaching/cs88/nips99.pdf - [7] WIKIPEDIA;
*Kernel Principal Component Analysis*.

Available in: http://en.wikipedia.org/wiki/Kernel_principal_component_analysis - [8] WIKIPEDIA;
*Kernel Trick*.

Available in: http://en.wikipedia.org/wiki/Kernel_trick - [9] SMITH, Lindsay.
*A Tutorial on Principal Component Analysis*. 2002.

Available in: http://www.cs.otago.ac.nz/cosc453/student_tutorials/principal_components.pdf

I’m playing around with the code… amazing stuff! I’m impressed. BTW, do you have some C# recipe for CCA (curvilinear component analysis)? I’m trying to code it directly from the “paper” but, alas, I’m stuck. Also I wonder how all they do compare, PCA, KCA, CCA (and also CDA).

Hi Antonino,

Thanks for the feedback! Unfortunately, I don’t have any implementations of Curvilinear Component Analysis. Is it the same as Principal Curves?

This class of methods is surely in my todo list, but I can’t say for sure when I’ll have time to study and implement them. Anyway, I think they would be a nice addition for the Accord.NET Framework.

Best regards,

César

don’t know much about Principal Curves (to tell the truth I don’t know much of almost anything in this field as I’m self taught).

CCA is a very simple technique for dimensional reduction; it does that by trying to maintain the euclidean distances from the original space so that “topology” is preserved to a certain extent.

CDA is a more complex variant that uses non euclidean distances but that is able to map highly non-linear manifold structures (spirals and so on).

Today I managed to make my CCA code work (as I’ve said it’s a very simple technique) but it’s not perfect yet. I’m going to compare it versus KCA.

If you want, I can send you the code and the paper stuff I’ve collected, so to have a look.

P.S. I’m going to check your work on SVMs… very interesting stuff!

Hi Antonino,

If you could send your material, I would be very grateful! Please send me a message through the “contact” link on the top of this page, so we can talk by email.

Thanks!

César

Hi César!

I am unable to downolad your demo neither the source. Is there something wrong with the links?

thx,

Bart

Fixed!

Thanks for letting me know about the broken links. The source/samples are also available on the Accord.NET project page.

Best regards,

César

César can you please tell me if I have understood correctly…

In PCA, after the Compute() step:

– pca.Results[,] are the extracted principal components, arranged in decreasing order of importance

– pca.Components[i].EigenVector[] are the weights that express the i-th component as a linear combination of the source data[,] vectors

– pca.ComponentMatrix[,] are the weights that express the original data[,] vectors as a linear combination of principal components vectors

– if I want to “denoise” a specific input data series, all I have to do is to make a linear combination of pca.Results[,] * pca.ComponentMatrix[,], setting weights to zero if proportion is low (or something like that).

Is that correct?

Hi Antonino,

– Actually, the pca.Results[,] are the projections of the source data into principal component space. It is already a “denoised” version of the source data, obtained through a projection using the entire base of eigenvectors. It is the “result” of this full projection.

– The pca.Components[i].EigenVector[] are indeed weights that express the formation of the i-th component as a linear combination of the source data[,] vectors. It is one of the vectors defining the basis for the orthogonal projection.

– Actually, this is the entire projection basis. It is the combination of all Components[i].EigenVectors. The only difference is that the Components[i].EigenVectors are easier to analyse in a per-component fashion.

– If you would like to apply the transformation to another data set, all you have to do is to call the Transform(double[,]) method passing the data and the number of components you wish to use in the projection. You can select the number of components by observing the amount of variance explained by each of them. If you compute the Transform() of the original data, you will obtain the same projection as the one stored in pca.Result[,]. The pca.Result[,] is only a shortcut, as the Result[,] becomes readily available during the Compute() evaluation and thus doesn’t need to be computed again.

Well, I hope this made things more clear!

Best regards,

César

Ok, thanks much for the explanations, I have a better understanding now.

Anyway for my problem pca.Transform() isn’t suitable I think… let me explain:

Suppose I have 3 somewhat-correlated data series, d1[], d2[] and d3[]. I put them into columns of data[,] matrix and do pca.Compute().

Now suppose I am interested only in d3 and want to “denoise” it, that is, rewrite d3[] using only the most meaningful principal components. The problem is that PCA.Transform() needs a matrix[,] so I cant give d3[] as a parameter.

What I did was to rebuild back d3[] as weighted sum of pca.Result[t,i]*weights[i], where weights[i] is the corresponding row in pca.ComponentMatrix. I also had to sum pca.Means[i] because, I guess, means is removed during the computation of PCA.

It seems to work because the more components I add, the more d3[] gets similar to the original. And it is also working in the sense of “filtering”, by visual inspection.

So from my way of approaching the problem, d1 and d2 are seen as “hints” and d3 is the working data.

All this have sense or am I totally off-road?

Hi Antonino,

I see. What you are describing is very similar to the projection reversion. Yesterday I completely forgot the fact that denoise is tipically achieved using the Reverse transform. Sorry for that. What you can try to do is to:

– Compute the principal components of your entire data (d1;d2;d3);

– Project all your data to principal component space by calling Transform([,]) and specifying a single principal component;

– Revert your data back by calling Revert([,]) and discarding d2 and d3.

However, I am not sure if you are talking about PCA or KPCA. In PCA this should work OK, but in KPCA, the reverse transform is not that straightforward and may not even exist. There is also a lot of room for improvement in the code of the reverse KPCA transform. Currently, it is a direct implementation of one of the possible algorithms for the reverse transform without optimizations.

Another option is to use Independent Component Analysis instead. It is specially suited to separate multiple data channels which have been mixed. Please take a look on the sample application I linked, perhaps you will find it interesting.

Best regards,

César

Wow, didn’t even know there was an ICA implementation in the framework… that’s wonderful!

I’ve experimented with both PCA and ICA yesterday, just to see what is best suited for my problem (PCA seems to be more stable over time when I add new datapoints, while ICA is more “erratic”).

BTW, a small note: there is a PCA.Means[] but not a ICA.Means[] (it’s a private array) so it’s not possible to demix data and get back the exact original data.

Thanks, Antonino. The Means[] property will be available in the next release. However, if you would like to get the exact original data back, you could try using the ica.Combine[,] method as well.

Best regards,

César

Hi César,

Thank you for your implementation, it helped me a lot as I am trying right now to implement it, too,

I still have a few question:

1. I read the original article by Schoelkopf. He assumes that the observation data is centerd and only if not you could center the Kernel in Feature-space. So I guess, one of both is neccessary, not both (as you do), is that correct? Or perhaps I only need to center the training data and not the testing data?

2. In your Transform()-method your Kernel has the dimensions (rows X N).

You then center the Kernel. Both in the centerKernel()-function and later in the Transform function you assume a symmetric Kernel-matrix (thus N == rows), otherwise the index in K[i, k] would be out of Bounce.

But normally you use less training-data then test-data, don’t you?

Thus you would have to center the Testing-Kernel differently and change the ‘rows’ in the inner loop “for (int k = 0; k < rows; k++)” to the number of samples, so in your case ‘N’.

Are my considerations true?

Thank you again & best regards,

Guanta

Hi Guanta,

Your considerations are all correct. The Transform function should be performing a different centralization. I had started writing a preliminary correction but didn’t finish it yet. The correct centering should take the previous kernel matrix in account. I forgot where I did find the references for the correct centering, but the code I had written some time ago, and which I didn’t yet finish testing, was:

private static double[,] centerKernel(double[,] newK, double[,] K)

{

int testSamples = newK.GetLength(0);

int N = K.GetLength(0);

for (int t = 0; t < testSamples; t++)

{

double[] k = newK.GetRow(t);

double[] onet = Matrix.Vector(N, 1.0 / N);

double[,] oneN = Matrix.Create(N, N, 1.0 / N);

double[] onetK = onet.Multiply(K);

double[] kone = k.Multiply(oneN);

double[] oneKone = onet.Multiply(K).Multiply(oneN);

for (int i = 0; i < k.Length; i++)

newK[t, i] = k[i] – onetK[i] – kone[i] + oneKone[i];

}

return newK;

}

I hope it helps.

Best regards,

César

Hi César,

I also got to work it by using a similar approach. I just wrote it in terms of matrix-multiplication which I found more readable (btw. you could also write the last 3 foor-loops in the transform()-function as a matrix-multiplication, i.e.: Result=CenteredKernel*ComponentMatrix).

I still wonder if I need to center the source and/or trainingsdata or if I don’t need it due to the centering of the Kernel. Anyway, the results look good. Thank you again for your fast reply!

Guanta

Hi César,

Thank you for your response! I solved it similarly but in terms of matrix-multiplication. Btw you could also express your three for-loops in the transform()-function as a matrix multiplication (i.e. result = centerd_test_kernel * ComponentMatrix.transpose() ).

But I really wonder whether I need to center the source if I have centered the kernel already (or vice versa)? Do you know that perhaps? Or tested it?

In normal PCA you center the data with the mean and when you project the data you add the mean again. Do I need that here, too?

Sry, with my last assumption I am wrong, you don’t add the mean again in normal pca. You just subtract the mean.

I guess, one of both centering with the mean or centering in feature-space is sufficiant.

Thank you so much for such a nice work i have used teh sample application for both PCA and KPCA. the PCA is working but KPCA is giving me error when i do the example “”scholkopf””. Please help me becuase am also trying my dataset and getting the same error.

Error: “column names must correspond to array columns. Parameter name: colnames.

Please guide me….

Hi Kausar,

Please try to download the latest version of the Accord.NET Framework. The framework comes with the latest enhancements and bug-fixes, so if this error is indeed a bug, it is very likely it has already been fixed on the most current release.

The framework can be downloaded at the Accord.NET project site.

Best regards,

César

Thank you for the advice. i installed the latest version and then tried but now its giving an error

“

Error: The number of colors must be between 1 and 32.

Parameter name: number.

“

Please help me.i have find the PCA successfully of my dataset using your software. i have 38 features(column). i have to do feature reduction in order to give it to SVM classifier. Please do tell me about KPCA or either any other tool similar in your resource to do feature reduction n get better accuracy.

Thank again..

Hi Kausar,

This is simply a limitation of the scatterplot chart. Are you sure you have more than 32 classes in your problem? It is very hard to produce more than 32 distinguishable colors in a chart, so I would suggest trying another approach for displaying it.

Regards,

César

Thanks for such a nice implementation. I have used it to compare my result with your implementation. I appreciate it. I need one more suggestions “How can I use this for a large dimensional data set?”. As I am doing my reserach on remote sensing and working on a image size of 145x145x220. Can you help me in this regards.

I have tried this impelmentation with a 40x40x220 data set but it fail to execute that. Please consider and suggest me on a quick basis.

Thanks

hy cesar..

This project really nice and very helpful 😀

but, i have one question. when i do my researh with large image size, i got message this:

“An unhandled exception of type ‘System.OutOfMemoryException’ occurred in Accord.Math.dll”

what can i do for this? i have tried with data matrix 100×100 but it fail execute that.

Hi Rafi,

I tried to answer your question in CodeProject!

Best regards,

Cesar