簡體   English   中英

根據其他data.table轉換data.table的列

[英]Transforming columns of data.table based on other data.table

我有兩個很大的功能表( training_dftest_df集)。 在訓練數據中,已將列標准化為零均值且具有單位方差,並且已使用來自訓練數據的縮放比例對測試數據進行了縮放。

在縮放之前,原始特征非常稀疏,我想為建模重建該稀疏結構。 通過將訓練列的列模式添加到兩個數據表中,可以恢復稀疏結構。 我可以有效地對訓練數據執行此操作,但是我很難找到一種有效的方法來實現測試數據。 我目前的嘗試如下:

# Function to calculate mode
mode <- function(x) {
  ux <- unique(x)
  as.numeric(ux[which.max(tabulate(match(x, ux)))])
}

# VERY slow sparsification of columns in test set
for (cn in names(test_df)) { # feature names are identical in data frames
  mode_tmp <- mode(training_df[, ..cn])
  set(test_df, j = cn, value = test_df[, ..cn] - mode_tmp)
}

# Fast sparsification of training set
training_df[, colnames(training_df) := lapply(.SD, function(x) x - mode(x)), .SDcols = 1:ncol(training_df)]

該解決方案由docendo discimus在評論中給出。 test_df的計算瓶頸是模式函數。 通過簡單地用[, ..cn] [[cn]]替換[, ..cn] [[cn]] ,數據表返回了原子向量而不是data.table並且用於計算模式的總時間從數小時減少到數秒。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM