【问题标题】:Multiply two named vectors/matrices, applying an n-gram model (stringdist::qgrams)将两个命名向量/矩阵相乘,应用 n-gram 模型 (stringdist::qgrams)
【发布时间】:2021-10-25 00:25:03
【问题描述】:

我正在尝试在字符串上应用n-gram character model 以计算其在此模型中的概率。

我用stringdist::qgram()创建了一个字符二元模型:

library(tidyverse)
library(stringdist)

ref_corpus   <- c("This is a sample sentence", "Other sentences from the reference corpus", "Many other ones")
bigram_ref   <- qgrams(ref_corpus, q = 2)       # collecting all bigrams
bigram_model <- log(bigram_ref/sum(bigram_ref)) # computing the log probabilities of each 

bigram_model
#           Th        hi        is        s         sa        se        te        th
# V1 -4.356709 -4.356709 -3.663562 -3.258097 -4.356709 -3.663562 -3.663562 -3.258097

现在,我想使用这个模型来计算模型中新字符串的概率:

bigram_string <- qgrams("This one", q = 2) 
bigram_string
#    Th hi is s  on ne  o
# V1  1  1  1  1  1  1  1

我不知道如何将这两个命名矩阵/向量相乘,以便获得bigram_string 中的计数乘以bigram_model 中的对数概率。

预期输出:

bigram_string %*% bigram_model
#            Th        hi        is         s  ...
# V1  -4.356709 -4.356709 -3.663562 -3.258097  ...

# Actual output:
# Error in bigram_string %*% bigram_model : non-conformable arguments

我在子集方面取得了一些进展:

bigram_model["V1",][bigram_string]

# But output:
#        Th        Th        Th        Th        Th        Th        Th 
# -4.356709 -4.356709 -4.356709 -4.356709 -4.356709 -4.356709 -4.356709

【问题讨论】:

    标签: r matrix-multiplication n-gram stringdist


    【解决方案1】:

    也许,我们需要对列名进行子集化

    bigram_model[, colnames(bigram_string)] * bigram_string
    

    -输出

            Th        hi        is        s         on        ne         o
    V1 -4.356709 -4.356709 -3.663562 -3.258097 -4.356709 -4.356709 -3.663562
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      相关资源
      最近更新 更多