*This article was written by Sergul Aydore, Ph.D., and Syed Ashrafulla, Ph.D.*

*Sergul and Syed received their Ph.D.s in Electrical Engineering in 2014 from the University of Southern California, applying signal processing to neuroimaging data. They continue to use machine learning on brain imaging data as a pastime and sharing their knowledge with the community. They constantly challenge each other as good buddies and like to call themselves “signal learners.”*

*The views expressed in this article are of the authors and not of their employers or Domino Data Lab.*

# Principal Component Analysis in Neuroimaging Data Using PySpark

In this post we will describe how we used PySpark, through Domino’s data science platform, to analyze dominant components in high-dimensional neuroimaging data. We will demonstrate how to perform Principal Components Analysis (PCA) on a dataset large enough that standard single-computer techniques will not work.

PCA is a widely used tool in machine learning, data analysis, and statistics. The goal of PCA is to represent the data in a lower dimensional space. PCA is useful for denoising, as well as for data exploration of dominant linear trends in the data. As part of the setup, PCA ensures that the dimensions returned are orthonormal and capture the largest directions of variance in the data.^{[2]}

## 1- What is PCA?

To describe PCA, we will start with a data set that has features and observations, represented as a matrix with rows and columns. Let’s also assume we’ve subtracted a constant from each feature so that the resulting features all have mean .

Our goal is to find the vectors that best capture the variation in the dataset across observations, represented as a matrix with uncorrelated rows and columns. There are two ways to find this summarization of the data: Using the sample covariance matrix, and using Singular Value Decomposition (SVD).

### 1.1 – PCA Using the Covariance Matrix

Specifically, we will use the eigenvalue decomposition of the sample covariance matrix. The sample covariance matrix is where entry is the covariance between -th feature with -th feature. Our goal is to find a matrix that projects onto a lower-dimensional subspace

(1)

where the covariance matrix of , , is diagonal (equivalently, the rows of are orthogonal to each other):

(2)

and for .

Since is a symmetric matrix the eigenvalue decomposition can be represented by:

(3)

where is an orthogonal matrix, each column an eigenvector of . Plugging into 2, we can see that setting satisfies the conditions on . Hence we get our principal components by setting .

### 1.2 – PCA Using Singular Value Decomposition

We don’t need to use the sample covariance matrix to get the largest principal components. Define ; as a result, each column of has zero mean. From linear algebra we can decompose into three matrices

(4)

where is , and is and is , for some . is called the rank of the matrix. If we carefully look at the product :

(5)

the columns of are not only the eigenvectors of ; they are also the eigenvectors of . Therefore, can be the projection matrix used to compute : .

Singular value decomposition is often preferred over eigendecomposition of the covariance matrix because the calculation of the covariance matrix is a source of error. In singular value decomposition, with such a large dataset, we are much more robust to errors due to dynamic range of numbers or computational error.

## 2 – Toy Example

### 2.1 – Covariance matrix

Let’s start with a toy example

where each column is another observation of five dimensional random variable. Let’s compute the sample covariance matrix of :

(6)

where five-dimensional vector is the mean across all observations. Hence the covariance matrix is:

(7)

and eigen value decomposition is:

(8)

where and .

There are 2 eigenvectors because the rank of is 2 and each column of represents an eigenvector which are ordered by the magnitude of eigen values represented in diagonal elements of matrix . If we want to represent in 2-dimensional space, all we need to do is to multiply by :

(9)

If you want your output to be zero mean across columns, you can multiply by :

(10)

### 2.2 – Singular Value Decomposition (SVD)

Following our notation in section 1.2, the matrix is:

(11)

Computing SVD results:

(12)

where , and .

Note that matrices and are equivalent, as discussed in section 1.2.

## 3 – Implementing PCA

### 3.1 – Using scikit-learn

The diagram in Figure 1 demonstrates PCA using scikit-learn. The results are consistent with theoretical results we showed in section 2 except the sign of the components. This is not an issue because sign does not affect the direction of the components.

Figure 1: Demonstration of PCA in sklearn.### 3.2 – Using PySpark

As discussed before, we are using large datasets. Scikit-learn will crash on single computers trying to compute PCA on datasets such as these. As a result, we look to PySpark to distribute the computation of PCA.

#### 3.2.1 – Method 1: Spark’s ML Package

Figure 2 shows PCA in PySpark using Spark’s ML package. The transformed matrix looks different than sklearn’s result. This is because sklearn subtracts the mean of the input to make sure that the output is zero mean. However, the PCA module in PySpark applies transformation to the original input. Basically, sklearn computes (equation 10) and PySpark computes (equation 9).

Figure 2: Demonstration of PCA in PySpark using PCA module in ML.You might have noticed that an identity matrix was necessary to pull out the features. Spark’s PCA module had limited outputs, so to be able to see the components we had to use a dummy transformation on the features.

#### 3.2.2 – Method 2: SVD through Wrapping Java/Scala

In Spark 1.6.0 we can compute SVD using some modules from Spark’s mllib package. However, SVD in Spark was implemented in Scala and Java. We resorted to making PySpark wrappers to those SVD classes using the functions written by Elias Abou Haydar.^{[1]}

from pyspark.mllib.common import callMLlibFunc, JavaModelWrapper from pyspark.mllib.linalg.distributed import RowMatrix from pyspark.mllib.linalg import _convert_to_vector, Matrix, DenseMatrix from pyspark.ml.feature import StandardScaler class RowMatrix_new(RowMatrix): def multiply(self, matrix): &amp;quot;&amp;quot;&amp;quot; Multiplies the given RowMatrix with another matrix. :param matrix: Matrix to multiply with. :returns: RowMatrix &amp;gt;&amp;gt;&amp;gt; rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]])) &amp;gt;&amp;gt;&amp;gt; rm.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect() [DenseVector([2.0, 3.0]), DenseVector([6.0, 11.0])] &amp;quot;&amp;quot;&amp;quot; if not isinstance(matrix, DenseMatrix): raise ValueError(&amp;quot;Only multiplication with DenseMatrix &amp;quot; &amp;quot;is supported.&amp;quot;) j_model = self._java_matrix_wrapper.call(&amp;quot;multiply&amp;quot;, matrix) return RowMatrix_new(j_model) class SVD(JavaModelWrapper): &amp;quot;&amp;quot;&amp;quot;Wrapper around the SVD scala case class&amp;quot;&amp;quot;&amp;quot; @property def U(self): &amp;quot;&amp;quot;&amp;quot; Returns a RowMatrix whose columns are the left singular vectors of the SVD if computeU was set to be True.&amp;quot;&amp;quot;&amp;quot; u = self.call(&amp;quot;U&amp;quot;) if u is not None: return RowMatrix(u) @property def s(self): &amp;quot;&amp;quot;&amp;quot;Returns a DenseVector with singular values in descending order.&amp;quot;&amp;quot;&amp;quot; return self.call(&amp;quot;s&amp;quot;) @property def V(self): &amp;quot;&amp;quot;&amp;quot; Returns a DenseMatrix whose columns are the right singular vectors of the SVD.&amp;quot;&amp;quot;&amp;quot; return self.call(&amp;quot;V&amp;quot;) def computeSVD(row_matrix, k, computeU=False, rCond=1e-9): &amp;quot;&amp;quot;&amp;quot; Computes the singular value decomposition of the RowMatrix. The given row matrix A of dimension (m X n) is decomposed into U * s * V'T where * s: DenseVector consisting of square root of the eigenvalues (singular values) in descending order. * U: (m X k) (left singular vectors) is a RowMatrix whose columns are the eigenvectors of (A X A') * v: (n X k) (right singular vectors) is a Matrix whose columns are the eigenvectors of (A' X A) :param k: number of singular values to keep. We might return less than k if there are numerically zero singular values. :param computeU: Whether of not to compute U. If set to be True, then U is computed by A * V * sigma^-1 :param rCond: the reciprocal condition number. All singular values smaller than rCond * sigma(0) are treated as zero, where sigma(0) is the largest singular value. :returns: SVD object &amp;quot;&amp;quot;&amp;quot; java_model = row_matrix._java_matrix_wrapper.call(&amp;quot;computeSVD&amp;quot;, int(k), computeU, float(rCond)) return SVD(java_model) def computePCA_sergul(input, numReducedDim): &amp;quot;&amp;quot;&amp;quot; Computer PCA for a given input using SVD :param input: A matrix of dimension num_of_observation x num_of_features :param numReducedDim: Dimension of reduced space :return: components, projection and singular values &amp;quot;&amp;quot;&amp;quot; df = sqlContext.createDataFrame(input,[&amp;quot;features&amp;quot;]) standardizer = StandardScaler(withMean=True, withStd=False, inputCol='features', outputCol='std_features') model_normalizer = standardizer.fit(df) df_normalized = model_normalizer.transform(df) pca_features = df_normalized.select(&amp;quot;std_features&amp;quot;).rdd.map(lambda row : row[0]) mat = RowMatrix_new(pca_features) svd = computeSVD(mat,numReducedDim,True) components = svd.call(&amp;quot;V&amp;quot;).toArray() # dim_of_data x reduced dim projection = RowMatrix_new((pca_features)).multiply(svd.call(&amp;quot;V&amp;quot;)) singularValues = svd.call(&amp;quot;s&amp;quot;).toArray() return components, projection, singularValues \end{lstlisting}

We can apply this framework to the same input from the toy example as shown in Figure 3.

Figure 3: Demonstration of PCA in PySpark using PySpark wrappers for SVD implementation.The results are consistent with the theoretical results in section 2.

## 4 – Application: Functional Magnetic Resonance Imaging

We applied PCA to a neuroimaging data set to explore neuronal signatures in the human brain. We used resting state functional magnetic resonance imaging data (fMRI) for 900 subjects, collected as part of the Human Connectome Project (HCP).^{[3]}

The preprocessing of this data set is beyond the scope of this article, but you can see the dimensions involed in creating the dataset in Figure 4.

The number of time points for each subject is 1,200 and the number of voxels is 13,000. Since there are 900 subjects, we need to compute SVD on matrix of size (matrix in our notation).

Figure 4: Concatenation of 900 subjects for PCA computation.Computing SVD on a matrix of size is computationally expensive. Therefore, we backed PySpark with commodity hardware provided by Amazon Web Services and accessed through the Domino data science platform.

PCA on the entire dataset took 27 hours using hardware with 16 cores and 30GB RAM. Figure 5 shows the top four components from four different views.

While interpreting such images is hard, two conclusions are of note:

1. The maps are roughly symmetric, in line with what is expected for resting state networks of the brain.

2. The third component has hotspots at the dorsal medial prefrontal cortex and the precuneus, two key components of the default mode network.

## References

- Elias Abou Haydar. http://stackoverflow.com/a/33500704/4544800. 2015.
- Jonathon Shlens. A tutorial on principal component analysis.
*arXiv preprint*, 2014.

arXiv:1404.1100 - Stephen M Smith, Christian F Beckmann, Jesper Andersson, Edward J Auerbach, Janine Bijsterbosch, Gwenaëlle Douaud, Eugene Duff, David A Feinberg, Ludovica Griffanti, Michael P Harms, et al. Resting-state fmri in the human connectome project.
*Neuroimage*, 80:144–168, 2013.

Banner image titled “DSC_2236” by Edward Blake. Licensed under CC BY 2.0

LaTeX rendering by QuickLaTeX.