r - 如何编写函数将数据转换为更高维度
问题描述
如果您熟悉 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)
解决方案
我使用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
推荐阅读
- javascript - 输入值更改后,jQuery 序列化不适用于克隆表单
- javascript - 圆形左上角
- python - 在 Python 中调用 Oracle 存储过程时出现错误“不支持 dict 类型的值”
- networking - 第一次自己配置cisco路由器 为什么上不了网?
- postgresql - WSL2 和 Docker 桌面上的 Postgres 卷挂载:PGDATA 文件夹上的权限被拒绝
- java - 创建一个接受数字和 + 作为第一个字符的正则表达式
- javascript - 错误:“无法实例化 firebase-storage - 请务必先加载 firebase-app.js”
- ssis - 如何多次运行 SSIS 包?
- javascript - 当 DOM style="display:block; 使用 selenium/js 时,有什么方法可以获取元素的文本
- crystal-reports - Crystal Report - 将页脚抑制到最后一页 - 在其他页面上创建空白区域