【问题标题】:Spatial data in R: plot decision regions of multi-class SVMR中的空间数据:绘制多类SVM的决策区域
【发布时间】:2015-06-02 01:31:58
【问题描述】:

我有一个带有xy 列的data.frame,还有一个class 列,它给出了现有多类SVM 模型下每个点的分类。下面是一些示例代码:

library(rgdal)
library(rgeos)
library(e1071)  # for svm()
library(sp)
library(raster)
library(maptools)
library(plyr)

## Create a mask of the data region, as a data frame of x/y points.
covering <- function(data, xlen=150, ylen=150) {
    # Convex hulls of each class's data points:
    polys <- dlply(data, .(class), function(x) Polygon(x[chull(x[-3]), -3]))
    # Union of the hulls:
    bbs <- unionSpatialPolygons(SpatialPolygons(list(Polygons(polys, 1))), 1)

    # Pixels that are inside the union polygon:
    grid <- expand.grid(x=seq(min(data$x), max(data$x), length.out=xlen),
                        y=seq(min(data$y), max(data$y), length.out=ylen))
    grid[!is.na(over(SpatialPoints(grid), bbs)), ]
}

set.seed(123)
data <- rbind(data.frame(x=rnorm(1000, 5*runif(1)), y=rnorm(1000, 5*runif(1)), class='A'),
              data.frame(x=rnorm(1000, 5*runif(1)), y=rnorm(1000, 5*runif(1)), class='B'),
              data.frame(x=rnorm(1000, 5*runif(1)), y=rnorm(1000, 5*runif(1)), class='C'))

m <- svm(class ~ x+y, data)
grid <- covering(data)

par(mfrow=c(1,2))
plot(y ~ x, data, col=data$class)
plot(y ~ x, grid, col=predict(m, grid), pch=20)

我接下来要做的是将此结果转换为某种SpatialPolygons 对象,每个因子级别有一个Polygons 对象,以便导出到GeoJSON,以便可以在地图应用程序中使用。有什么好方法可以做到这一点?我是否需要自己编写例程来跟踪图像(作为矩阵)并找到区域之间的边界?

我查看了rasterToPolygons() 的文档,但我不知道如何将其应用于我的情况,所以我欢迎一些帮助。

最后,我的数据将是具有真实纬度/经度信息的地理空间数据,但我想先尝试这个更简单的情况。

【问题讨论】:

    标签: r polygon spatial


    【解决方案1】:

    您需要将第二张图像转换为光栅(请参阅here)。

    sp.grid <- cbind(grid, col = predict(m, grid))
    coordinates(sp.grid) <- ~ x + y
    gridded(sp.grid) <- TRUE
    sp.grid <- raster(sp.grid)
    

    那么你的尝试成功了。

    grid.pols <- rasterToPolygons(sp.grid, n = 16, dissolve = TRUE)
    plot(grid.pols)
    
    class       : SpatialPolygonsDataFrame 
    features    : 3 
    extent      : -1.842044, 7.259169, -2.298892, 5.512507  (xmin, xmax, ymin, ymax)
    coord. ref. : NA 
    variables   : 1
    names       : col 
    min values  :   1 
    max values  :   3
    

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2021-07-30
      • 2021-05-17
      • 2017-10-02
      • 2016-07-13
      • 2019-10-12
      • 2019-09-07
      • 2014-03-24
      • 1970-01-01
      相关资源
      最近更新 更多