gpt4 book ai didi

r - 加快查找过程

转载 作者:行者123 更新时间:2023-12-01 21:17:39 35 4
gpt4 key购买 nike

我有两个表:coc_dataDTcoc_data 表包含单词对之间的共现频率。其结构类似于:

   word1 word2 freq
1 A B 1
2 A C 2
3 A D 3
4 A E 2

第二个表,DT 包含不同年份每个单词的频率,例如:

   word year weight
1 A 1966 9
2 A 1967 3
3 A 1968 1
4 A 1969 4
5 A 1970 10
6 B 1966 9

实际上,coc_data 目前有 150.000 行,DT 大约有 450.000 行。下面是模拟这两个数据集的 R 代码。

# Prerequisites
library(data.table)
set.seed(123)
n <- 5

# Simulate co-occurrence data [coc_data]
words <- LETTERS[1:n]
# Times each word used
freq <- sample(10, n, replace = TRUE)
# Co-occurrence data.frame
coc_data <- setNames(data.frame(t(combn(words,2))),c("word1", "word2"))
coc_data$freq <- apply(combn(freq, 2), 2, function(x) sample(1:min(x), 1))

# Simulate frequency table [DT]
years <- (1965 + 1):(1965 + 5)
word <- sort(rep(LETTERS[1:n], 5))
year <- rep(years, 5)
weight <- sample(10, 25, replace = TRUE)
freq_data <- data.frame(word = word, year = year, weight = weight)
# Combine to data.table for speed
DT <- data.table(freq_data, key = c("word", "year"))

我的任务是使用以下函数根据 DT 表中的频率标准化 coc_data 表中的频率:

my_fun <- function(x, freq_data, years) {
word1 <- x[1]
word2 <- x[2]
freq12 <- as.numeric(x[3])
freq1 <- sum(DT[word == word1 & year %in% years]$weight)
freq2 <- sum(DT[word == word2 & year %in% years]$weight)
ei <- (freq12^2) / (freq1 * freq2)
return(ei)
}

然后我使用 apply() 函数将 my_fun 函数应用到 coc_data 表的每一行:

apply(X = coc_data, MARGIN = 1, FUN = my_fun, freq_data = DT, years = years)

因为DT查找表相当大,整个映射过程需要很长时间。我想知道如何改进我的代码以加快计算速度。

最佳答案

由于 years 参数在 my_fun 中对于使用 apply 的实际使用情况是恒定的,因此您可以首先计算所有单词的频率:

f<-aggregate(weight~word,data=DT,FUN=sum)

现在将其转换为哈希值,例如:

hs<-f$weight
names(hs)<-f$word

现在在 my_fun 中通过查找 hs[word] 使用预先计算的频率。这应该更快。

更好 - 您正在寻找的答案是

(coc_data$freq)^2 / (hs[coc_data$word1] * hs[coc_data$word2])
<小时/>

data.table 实现将是:

f <- DT[, sum(weight), word]
vec <- setNames(f$V1, f$word)

setDT(coc_data)[, freq_new := freq^2 / (vec[word1] * vec[word2])]

给出以下结果:

> coc_data
word1 word2 freq freq_new
1: A B 1 0.0014792899
2: A C 1 0.0016025641
3: A D 1 0.0010683761
4: A E 1 0.0013262599
5: B C 5 0.0434027778
6: B D 1 0.0011574074
7: B E 1 0.0014367816
8: C D 4 0.0123456790
9: C E 1 0.0009578544
10: D E 2 0.0047562426

关于r - 加快查找过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42484041/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com