如何将列表变成 "textmodel_wordscores" 或 "textmodel"?

How to turn a list into a "textmodel_wordscores" or "textmodel"?

我运行字数。输出是一个对象,其格式为 "textmodel_wordscores"\"textmodel"\"list"(通过在其上应用 class)。然后我 运行 预测 这个对象,我得到了结果。

此处代码仅供参考:

train_ref <- textmodel_wordscores(dfm, y = docvars(df1, "Ref_score"), smooth=0.1)
word_score <- predict(train_ref, se.fit = TRUE, newdata = dfm2, rescaling = "mv")

class(train_ref) #"textmodel_wordscores" "textmodel"            "list"   
class(train_ref$wordscores) #numeric

我尝试做的基本上是将 train_ref$wordscores 替换为与替换对象具有相同结构的数字对象。见下文:

missing_train <- train_ref[-c(1)] #removing train_ref$wordscores

train_ref2 <- c(missing_train, coef_train_list)

#note that class(train_ref2) is now just a list object

# train_ref2 is just a list whereas train_ref is a texmodel object. The former doesn't go throught the function *predict*, while the latter does so

问题是,当我尝试使用 train_ref2 进行预测时,出现以下错误:UseMethod("predict") : 没有适用于 'predict' 的方法应用于 class "list".

的对象

我的问题是:有没有办法将列表转换为 textmodel 对象?

我没有将数据放入 运行 模型中,因为它与此处的 运行 wordscore 相当复杂。如果您需要更多信息,我会编辑问题。

非常感谢!

最好直接操作列表的 wordscores 元素,而不是尝试替换它。 coef() 有一个访问器方法,但这不允许替换。所以你可以这样做:

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

tmod <- textmodel_wordscores(data_dfm_lbgexample, y = c(seq(-1.5, 1.5, .75), NA))
head(coef(tmod), 10)
##         A         B         C         D         E         F         G         H 
## -1.500000 -1.500000 -1.500000 -1.500000 -1.500000 -1.481250 -1.480932 -1.451923 
##         I         J 
## -1.408333 -1.323298
predict(tmod)
##            R1            R2            R3            R4            R5 
## -1.317931e+00 -7.395598e-01 -8.673617e-18  7.395598e-01  1.317931e+00 
##            V1 
## -4.480591e-01

# replace some wordscores with 10
tmod$wordscores[c("F", "G")] <- 10
head(coef(tmod), 10)
##         A         B         C         D         E         F         G         H 
## -1.500000 -1.500000 -1.500000 -1.500000 -1.500000 10.000000 10.000000 -1.451923 
##         I         J 
## -1.408333 -1.323298
predict(tmod)
##            R1            R2            R3            R4            R5 
##  8.979134e-01 -6.821545e-01 -8.673617e-18  7.395598e-01  1.317931e+00 
##            V1 
## -4.480591e-01

# remove F and G some wordscores
tmod$wordscores <- tmod$wordscores[-match(c("F", "G"), names(coef(tmod)))]
head(coef(tmod), 10)
##         A         B         C         D         E         H         I         J 
## -1.500000 -1.500000 -1.500000 -1.500000 -1.500000 -1.451923 -1.408333 -1.323298 
##         K         L 
## -1.184615 -1.036990
predict(tmod)
## Warning: 2 features in newdata not used in prediction.
##            R1            R2            R3            R4            R5 
## -1.278918e+00 -7.358337e-01 -8.673617e-18  7.395598e-01  1.317931e+00 
##            V1 
## -4.480591e-01

在这里,我使用了特征名称索引来使它比数字索引更稳定,但当然你也可以使用整数索引来做到这一点。