我遇到了randomForest和raster包的问题。首先,我创建了分类器:
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)
到目前为止,一切都很好。通过查看错误率,混淆矩阵等,我可以看到森林是正确创建的。但是,当我尝试对某些数据进行分类时,我遇到了以下问题,它会返回predictions
中的所有NA:
# 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)
如何让它直接使用“光栅”版本?我知道这是可能的,如predict{raster}的示例所示。
答案 0 :(得分:0)
您可以尝试在writeRaster函数中嵌套predict.randomForest,并按照光栅包中包含的pdf将矩阵编写为块中的栅格。在此之前,在栅格函数中调用predict时尝试参数'na.rm = TRUE'。您也可以在预测栅格中为NA分配虚拟值,然后使用栅格包中的函数将它们重写为NA。
至于调用RF时的内存问题,我遇到了大量处理BRT的内存问题。它们在磁盘和内存中都是巨大的! (模型应该比数据更复杂吗?)我没有让它们在32位机器(WinXp或Linux)上可靠运行。有时将Windows内存分配调整到应用程序有所帮助,而迁移到Linux有所帮助,但我从64位Windows或Linux机器中获得了最多,因为它们对应用程序可以采用的内存量施加更高(或没有)的限制。您可以通过这样做来增加可以使用的树数。