gpt4 book ai didi

R. Quanteda 包。如何过滤 dfm_tfidf 中存在的值?

转载 作者:行者123 更新时间:2023-12-04 08:54:40 24 4
gpt4 key购买 nike

所以我有一个 dfm_tfidf 并且我想过滤掉低于某个阈值的值。
代码:

dfmat2 <-
matrix(c(1,1,2,1,0,0, 1,1,0,0,2,3),
byrow = TRUE, nrow = 2,
dimnames = list(docs = c("document1", "document2"),
features = c("this", "is", "a", "sample",
"another", "example"))) %>%
as.dfm()


#it works
dfmat2 %>% dfm_trim(min_termfreq = 3)

#it does not work
dfm_tfidf(dfmat2) %>% dfm_trim( min_termfreq = 1)
# "Warning message: In dfm_trim.dfm(., min_termfreq = 1) : dfm has been previously weighted"

问题 :如何过滤掉 dfm_tfidf 中存在的值?
谢谢

最佳答案

这是一个基于绝对最小值在稀疏矩阵空间中执行此操作的函数。但要注意,因为 tf-idf 绝对值在不同的 dfm 对象中意义不大。

library("quanteda")
## Package version: 2.1.1

dfmat2 <-
matrix(c(1, 1, 2, 1, 0, 0, 1, 1, 0, 0, 2, 3),
byrow = TRUE, nrow = 2,
dimnames = list(
docs = c("document1", "document2"),
features = c(
"this", "is", "a", "sample",
"another", "example"
)
)
) %>%
as.dfm()

# function to trim features based on absolute minimum threshold
# operating directly on sparse matrix
dfm_trimabs <- function(x, min) {
maxvals <- sapply(
split(dfmat3@x, featnames(dfmat3)[as(x, "dgTMatrix")@j + 1]),
max
)
dfm_keep(x, names(maxvals)[maxvals >= min])
}
现在将其应用到上面的示例之前和之后:
# before trimming
dfm_tfidf(dfmat2)
## Document-feature matrix of: 2 documents, 6 features (33.3% sparse).
## features
## docs this is a sample another example
## document1 0 0 0.60206 0.30103 0 0
## document2 0 0 0 0 0.60206 0.90309

# after trimming
dfm_tfidf(dfmat2) %>%
dfm_trimabs(min = 0.5)
## Document-feature matrix of: 2 documents, 3 features (50.0% sparse).
## features
## docs a another example
## document1 0.60206 0 0
## document2 0 0.60206 0.90309

关于R. Quanteda 包。如何过滤 dfm_tfidf 中存在的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63902650/

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