我有一个矩阵tf.m
NxM 和df
N 行的数据框。
我想n
将矩阵的行分配给数据框中的列,在同一行n
。
library("tm")
ftfidf <- function(text.d) {
txt <- VectorSource(text.d);
txt.corpus <- VCorpus(txt, readerControl = list(reader = readPlain, language = "en"));
revs <- tm_map(txt.corpus, content_transformer(tolower))
dtm <- DocumentTermMatrix(revs, control = list(weighting = function(x) weightTfIdf(x, normalize = T),stopwords = TRUE))
}
df<-data.frame(id=c("doc1", "doc2", "doc3"), text=c("hello world", "people people", "happy people"))
#id text
#1 doc1 hello world
#2 doc2 people people
#3 doc3 happy people
tf <- ftfidf(df$text) # a function that gets a DocumentTermMatrix
tf.m <- as.matrix(tf)
#Terms
#Docs happy hello people world
#1 0.0000000 0.7924813 0.0000000 0.7924813
#2 0.0000000 0.0000000 0.5849625 0.0000000
#3 0.7924813 0.0000000 0.2924813 0.0000000
如果我运行它,我会在数据框中再获得 4 列
df$tf<-tf.m
#id text tf.happy tf.hello tf.people tf.world
#1 doc1 hello world 0.0000000 0.7924813 0.0000000 0.7924813
#2 doc2 people people 0.0000000 0.0000000 0.5849625 0.0000000
#3 doc3 happy people 0.7924813 0.0000000 0.2924813 0.0000000
我想要这个:
#id text tf
#1 doc1 hello world happy hello people world
# 0.0000000 0.7924813 0.0000000 0.7924813
#2 doc2 people people happy hello people world
# 0.0000000 0.0000000 0.5849625 0.0000000
#2 doc3 happy people happy hello people world
# 0.7924813 0.0000000 0.2924813 0.0000000
尝试根据词频训练 knn df$tf
(如果可能)
knn_model <- knn(train = df$tf[1,], cl = df$id, k=3)
查询 a 的最近邻居df$id
。
我的目标是在 R 中运行这个“喜欢”的 python graphlab 函数:
knn_model = graphlab.nearest_neighbors.create(df,features=['tf'],label='id')