doing PCA on very large data set in R

瘦欲@ 提交于 2019-12-03 00:36:13

The way I solved it was by calculating the sample covariance matrix iteratively. In this way you only need a subset of the data for any point in time. Reading in just a subset of the data can be done using readLines where you open a connection to the file and read iteratively. The algorithm looks something like (it is a two-step algorithm):

Calculate the mean values per column (assuming that are the variables)

  1. Open file connection (con = open(...))
  2. Read 1000 lines (readLines(con, n = 1000))
  3. Calculate sums of squares per column
  4. Add those sums of squares to a variable (sos_column = sos_column + new_sos)
  5. Repeat 2-4 until end of file.
  6. Divide by number of rows minus 1 to get the mean.

Calculate the covariance matrix:

  1. Open file connection (con = open(...))
  2. Read 1000 lines (readLines(con, n = 1000))
  3. Calculate all cross-products using crossprod
  4. Save those crossproducts in a variable
  5. Repeat 2-4 until end of file.
  6. divide by the number of rows minus 1 to get the covariance.

When you have the covariance matrix, just call princomp with covmat = your_covmat and princomp will skip calulating the covariance matrix himself.

In this way the datasets you can process are much, much larger than your available RAM. During the iterations, the memory usage is roughly the memory the chunk takes (e.g. 1000 rows), after that the memory usage is limited to the covariance matrix (nvar * nvar doubles).

Things to keep in mind when importing a large dataset.

  1. Memory requirement.

  2. Understand the structure of dataset being imported use the following sample code:

    initial <- read.table("datatable.csv", nrows = 100);

    classes <- sapply(initial, class);

    tabAll <- read.table("datatable.csv", colClasses = classes)

  3. If dataset is large use fread() function from data,table class.

  4. Perform Dimensionality reduction technique before applying PCA. Example, remove highly correlated variables or nearZeroVariance variables as they dont contribute to the output.

  5. Then apply PCA.

I hope it helps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!