如何更改 DocumentTermMatrix 矩阵的值?

How to change the values of a DocumentTermMatrix matrix?

重复:

假设我有 dtm:

library(topicmodels)
data(AssociatedPress)

我正在尝试将 .001 的值分配给所有 0

的值

用例:

当我在我的矩阵运行 LDA

上出现这个错误

Error in LDA(notSparse, k, method = "Gibbs", control = list(nstart = nstart, : Each row of the input matrix needs to contain at least one non-zero entry

我想看看如果我将零变成小值以减少稀疏性而不是使用专用函数会发生什么。

将矩阵值从 0 更改为 0.001 不适用于 topicmodels::LDA。 代码中有一个检查期望所有值都是整数值。这意味着不允许使用 0.001 的值。请参见下面的示例:

m_replaced_zero <- matrix(c(1, 1, 0.001, 0), nrow = 2)
LDA(m_replaced_zero)
Error in !all.equal(x$v, as.integer(x$v)) : invalid argument type

奇怪的是,你得到的错误意味着你的矩阵中有一行只包含 0。除非你从你的 documenttermmatrix 中删除了一些导致没有值 1 的行或更多的。请参阅下面的示例。

m_zero_row <- matrix(c(1, 0, 1, 0), nrow = 2)
     [,1] [,2]
[1,]    1    1
[2,]    0    0
LDA(m_zero_row)
Error in LDA(m_zero_row) : 
  Each row of the input matrix needs to contain at least one non-zero entry

但是如果您打算替换文档术语矩阵中的稀疏条目,则首先需要将其转换为矩阵,然后替换 0。

data("AssociatedPress")
m <- as.matrix(AssociatedPress)
m[m==0] <- 0.001