r - 如何将列表变成“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 非常复杂。如果您需要更多信息,我将编辑问题。
非常感谢!
解决方案
最好直接操作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
在这里,我使用特征名称索引来使其比数字索引更稳定,但当然你也可以使用整数索引来做到这一点。
推荐阅读
- python - 为什么我的 for 在 remove 之后会跳转一些术语?[Python]
- java - javax.ejb.EJBException:使用实体管理器将记录插入 Derby db 表时事务中止
- angular - 在 kendo-maskedTextbox、kendo-numericTextbox 和其他类似文本框的控件上添加前缀图标
- r - 有效地从向量中删除 n 个随机条目,其中 n 可能为 0
- sql - 在 SQL Server 中使用带有 XML 的两个表中的公共字段
- symfony - symfony querybuilder 用于按集合中的关系进行搜索
- terraform - Terraform 错误创建 Lambda 函数:ResourceConflictException 与刚刚由 Terraform 创建的资源应用
- api - Discord API 只返回一个成员
- python - 用格式变量声明变量的目的是什么:类类型=在python中?
- visual-studio - Visual Studio NUnit 测试未运行