首页 > 解决方案 > 如何编写函数将数据转换为更高维度

问题描述

如果您熟悉 SVM,我们可以将数据移动到更高维度以处理非线性。

我想这样做。我有 19 个功能,我想这样做:

对于任何一对特征 x_i 和 x_j 我必须找到:

     sqrt(2)*x_i*x_j

以及每个特征的平方

       ( x_i)^2

所以新功能将是:

    (x_1)^2, (x_2)^2,...,(x_19)^2, sqrt(2)*x_1*x_2, sqrt(2)*x_1*x_3,... 

最后删除值全为零的列

例子

        col1    col2     col3    
          1      2        6

新数据框

        col1      col2     col3    col4              col5           col6     
        (1)^2    (2)^2    (6)^2    sqrt(2)*(1)*(2)   sqrt(2)*(1)*(6)   sqrt(2)*(2)*(6)

标签: rdataframesvm

解决方案


我使用data.table包来做这些操作。您还需要gtools进行功能组合。

# input data frame
df <- data.frame(x1 = 1:3, x2 = 4:6, x3 = 7:9)

library(data.table)
library(gtools)
# convert to data table to do this
dt <- as.data.table(df)
# specify the feature variables
features <- c("x1", "x2", "x3")

# squares columns
dt[, (paste0(features, "_", "squared")) := lapply(.SD, function(x) x^2),
   .SDcols = features]

# combinations columns
all_combs <- as.data.table(gtools::combinations(v=features, n=length(features), r=2))
for(i in 1:nrow(all_combs)){
  set(dt,
      j = paste0(all_combs[i, V1], "_", all_combs[i, V2]),
      value = sqrt(2) * dt[, get(all_combs[i, V1])*get(all_combs[i, V2])])
}

# convert back to data frame
df2 <- as.data.frame(dt)
df2

推荐阅读