我需要通过自举执行knn回归,并针对不同的K值进行迭代
说我有2个数据框,训练和测试
train <- read.csv("train.csv")
test <- read.csv("test.csv")
还有一个函数knn
如下:
knn <- function(train_data, train_label, test_data, K){
len_train <- nrow(train_data)
len_test <- nrow(test_data)
test_label <- rep(0, len_test)
k_means <- function(training_pt){
distances <- as.matrix(dist(rbind(training_pt, train_data)))[1, (1+1):(1+len_train)]
data.frame(y = train_label) %>%
# train_label %>%
mutate(pt_dist = distances) %>%
arrange(pt_dist) %>%
select(y) %>%
slice(1:K) %>% pull() %>% mean()
}
predictions <- apply(test_data, 1, k_means)
return(predictions)
}
其中train_data采用带有预测变量列的数据帧, train_label是火车值的向量, 而test_data是一个数据列,其列与train_data相似
此函数返回test_data
每行的预测测试标签
现在,我编写了一个函数来生成引导受限样本:
gen_boot_sample <- function(df, sample_size = 25){
df %>% sample_n(sample_size, replace = T)
}
我设法写了一些东西,将knn
函数应用于固定值K的生成的自举样本。
但是我一直在努力遍历K
想法是生成一个数据帧,其中包含每个K值的每个引导捆绑样本(例如20个样本)的误差值
test_label <- test_data %>%
select_at(.vars = vars(contains("y"))) %>%
pull()
rerun(5, gen_boot_sample(train_data)) %>%
map( ~ knn(
train_data = .x %>%
select_at(.vars = vars(contains("x"))),
train_label = .x %>%
select_at(.vars = vars(contains("y"))) %>%
pull(),
test_data = test_data %>%
select_at(.vars = vars(contains("x"))),
K = 5
)
) %>%
map(~sum(. - test_label)^2)
我检查了答案
purrr map equivalent of nested for loop
但由于我的knn
函数如何接受参数而感到困惑
编辑:添加部分数据
train_data <- structure(list(x1 = c(1973.5, 1967.5, 1970.5, 1978, 1964, 1962,
1980, 1961.5, 1976.5, 1979.5), y = c(6.57, 1.83, 3.69, 11.88,
0.92, 0.72, 16.2, 0.92, 8.28, 14.85)), row.names = c(28L, 16L,
22L, 37L, 9L, 5L, 41L, 4L, 34L, 40L), class = "data.frame")
test_data <- structure(list(x1 = c(1978.75, 1962.75, 1974.25, 1975.75, 1963.75,
1972.75, 1968.25, 1980.75, 1979.25, 1970.75), y = c(8.91, 0.6,
6.39, 6.12, 0.77, 4.41, 2.07, 11.61, 12.96, 3.6)), row.names = c(38L,
6L, 29L, 32L, 8L, 26L, 17L, 42L, 39L, 22L), class = "data.frame")
答案 0 :(得分:1)
我们可以使用嵌套在map
中的另一个循环来运行不同的“ K”值
library(tidyverse)
rerun(5, gen_boot_sample(train_data)) %>%
map(~ {
# create the subset datasets
train_data <- .x %>%
select_at(vars(contains('x')))
train_label <- .x %>%
select_at(.vars = vars(contains("y"))) %>%
pull()
test_data <- test_data %>%
select_at(.vars = vars(contains("x")))
# loop over different values for 'K'
map_dbl(1:10, ~ {
#apply the knn function
out <- knn(train_data, train_label, test_data, K = .x)
sum(out - test_label)^2}
)
})