我的 randomForest 和栅格包有问题。首先,我创建分类器:

library(raster)
library(randomForest)

# Set some user variables
fn = "image.pix"
outraster = "classified.pix"
training_band = 2
validation_band = 1
original_classes = c(125,126,136,137,151,152,159,170)
reclassd_classes = c(122,122,136,137,150,150,150,170)

# Get the training data
myraster = stack(fn)
training_class = subset(myraster, training_band)

# Reclass the training data classes as required
training_class = subs(training_class, data.frame(original_classes,reclassd_classes))

# Find pixels that have training data and prepare the data used to create the classifier
is_training = Which(training_class != 0, cells=TRUE)
training_predictors = extract(myraster, is_training)[,3:nlayers(myraster)]
training_response = as.factor(extract(training_class, is_training))
remove(is_training)

# Create and save the forest, use odd number of trees to avoid breaking ties at random
r_tree = randomForest(training_predictors, y=training_response, ntree = 201, keep.forest=TRUE) # Runs out of memory, does not allow more trees than this...
remove(training_predictors, training_response)

到目前为止,一切都很好。通过查看错误率、混淆矩阵等,我可以看到森林已正确创建。然而,当我尝试对某些数据进行分类时,我遇到了以下问题,它返回了所有 NA predictions:

# Classify the whole image
predictor_data = subset(myraster, 3:nlayers(myraster))
layerNames(predictor_data) = layerNames(myraster)[3:nlayers(myraster)]
predictions = predict(predictor_data, r_tree, type='response', progress='text')

并给出这个警告:

Warning messages:
1: In `[<-.factor`(`*tmp*`, , value = c(1, 1, 1, 1, 1, 1,  ... :
  invalid factor level, NAs generated
(keeps going like this)...

但是,直接调用 Predict.randomForest 可以正常工作并返回预期的结果 predictions (这对我来说不是一个好的选择,因为图像很大,而且我无法将整个矩阵存储在内存中):

# Classify the whole image and write it to file
predictor_data = subset(myraster, 3:nlayers(myraster))
layerNames(predictor_data) = layerNames(myraster)[3:nlayers(myraster)]
predictor_data = extract(predictor_data, extent(predictor_data))
predictions = predict(r_tree, newdata=predictor_data)

如何让它直接与“光栅”版本一起工作? 我知道这是可能的,如示例所示 预测{栅格}.

有帮助吗?

解决方案

您可以尝试在 writeRaster 函数中嵌套 Predict.randomForest ,并根据栅格包中包含的 pdf 将矩阵写入块中的栅格。在此之前,在光栅函数中调用预测时尝试参数“na.rm=TRUE”。您还可以将虚拟值分配给预测栅格中的 NA,然后使用栅格包中的函数将它们重写为 NA。

至于调用 RF 时的内存问题,我在处理 BRT 时遇到过很多内存问题。它们在磁盘和内存中都非常巨大!(模型应该比数据更复杂吗?)我还没有让它们在 32 位机器(WinXp 或 Linux)上可靠地运行。有时调整 Windows 内存分配给应用程序会有所帮助,而迁移到 Linux 会更有帮助,但我从 64 位 Windows 或 Linux 机器中获得了最大的好处,因为它们对应用程序可以占用的内存量施加了更高(或没有)的限制。 。通过这样做,您也许可以增加可以使用的树木数量。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top