【发布时间】:2013-06-06 22:06:05
【问题描述】:
在计算 pearsons 相关性时,下面的脚本适用于我使用相同的数据。我最近对其进行了调整,以创建一个协方差矩阵以输入到 pca 中。我在一个论坛上读到,输入预先创建的协方差矩阵可能会避免内存问题,但对我来说并非如此。运行协方差矩阵时出现以下错误:
Error: cannot allocate vector of size 1.1 Gb
In addition: Warning messages:
1: In na.omit.default(cbind(x, y)) :
Reached total allocation of 6141Mb: see help(memory.size)
2: In na.omit.default(cbind(x, y)) :
Reached total allocation of 6141Mb: see help(memory.size)
3: In na.omit.default(cbind(x, y)) :
Reached total allocation of 6141Mb: see help(memory.size)
4: In na.omit.default(cbind(x, y)) :
Reached total allocation of 6141Mb: see help(memory.size)
谁能提出一个更有效的方法来做到这一点,这样我就不会遇到内存问题?如果我在这里完全偏离基础首先计算协方差,那很好。 PCA 是我最终唯一需要的东西。我的数据是 arcGIS 栅格格式的 12 个 1 波段栅格,每个数据大小为 581.15 mb。任何帮助将不胜感激。
library(rgdal)
library(raster)
setwd("K:/Documents/SDSU/Thesis/GIS Data All/GIS Layers/Generated_Layers/GridsForCor")
# List the full path to each raster:
raster_files = c('aspectclp',
'lakedistclp',
'ocdistclp',
'popdenclp',
'roaddistclp',
'scurveclp',
'sdemclp',
'solarradclp',
'sslopeclp',
'vegcatclp',
'canopcvrclp',
'canophtclp')
cov_matrix <- matrix(NA, length(raster_files), length(raster_files))
for (outer_n in 1:length(raster_files)) {
outer_raster <- raster(raster_files[outer_n])
# Start this loop at outer_n rather than 1 so that we don't compute the
# same covariance twice. At the end of the loops cov_matrix will be upper
# triangular, with the lower triangle all NA, and the diagonal all NA
# (since the diagonal would all be 1 anyway).
for (inner_n in (outer_n):length(raster_files)) {
# Don't compute correlation of a raster with itself:
if (inner_n == outer_n) {next}
inner_raster <- raster(raster_files[inner_n])
cov_matrix[outer_n, inner_n] <- cov(outer_raster[], inner_raster[],
use='complete.obs', method = "spearman")
}
}
pca_matrix <- princomp(raster_files, cor = FALSE, covmat = cov_matrix))
# Writing to a txt file & csv file
write.table(pca_matrix, "PCA.txt", sep="\t", row.names = FALSE)
write.csv(pca_matrix, "PCA.csv") enter code here
【问题讨论】:
-
两个有点切题的问题:(1)你为什么将文件路径的向量传递给
princomp? (2) 你为什么用princomp而不是prcomp? -
我不确定是使用 princomp 还是 prcomp。我选择了 princomp,因为它提供了添加协方差矩阵的选项(我读到的东西可能使它不会耗尽内存。不过,我猜这不是真的?)。而且我不确定要为 x 输入什么,因为我的文件太大而无法读入内存。本质上,有很多问题,其中一些源于我对 R 的天真 :(.
-
我还应该提到,我尝试将所有栅格放入栅格砖中以用作 princomp 或 prcomp 的输入,但它们太大了。
-
不确定这是否有帮助,但您检查过 bigmemory 包吗?它创建文件支持的矩阵。您可能可以创建栅格矩阵,然后运行计算?以下链接中有来自 Hijmans 的工作代码,它从栅格创建大矩阵:r-sig-geo.2731867.n2.nabble.com/…
-
首先,如果您的对象的列多于行,则制作协方差矩阵不会帮助您解决内存问题。其次,制作协方差矩阵还会创建另一个(可能)大对象,它正在使用 RAM。您使用的是 32 位 R 版本吗?您可以使用 64 位版本吗?这可能会有所帮助。
标签: r covariance raster pca