首页 > 解决方案 > 如何将列表变成“textmodel_wordscores”或“textmodel”?

问题描述

我跑了wordcore。输出是一个对象,其格式为“textmodel_wordscores”\“textmodel”\“list”(通过对其应用)。然后我对这个对象运行预测并得到了结果。

这里的代码仅供参考:

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' 的方法应用于类 "list" 的对象

我的问题是:有没有办法将列表转换为文本模型对象?

我没有输入数据来运行模型,因为在这里运行 wordcore 非常复杂。如果您需要更多信息,我将编辑问题。

非常感谢!

标签: rlistdataframequanteda

解决方案


最好直接操作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

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


推荐阅读