【问题标题】:Naive Bayes Multinomial朴素贝叶斯多项式
【发布时间】:2015-06-05 05:32:45
【问题描述】:

我正在使用朴素贝叶斯多项式模型。我应该使用 train 方法中看到的伪代码。所以这些是我的问题:

1)我已经放入了大部分代码,但我遇到了一些问题,主要是在提取词汇、计算类中的文档数量以及连接类中所有文档的文本方面。

2)我还注意到我需要的 train 方法只需要文档(又名 train_doc)。所以我不知道如何调整以获得 C 类。

def train(self, documents):
    # TRAINMULTINOMIALNB(C,D)
    # 1 V <-- EXTRACTVOCABULARY(D)
    # 2 N <-- COUNTDOCS(D)
    # 3 for each c in C
        # 4 do Nc <-- COUNTDOCSINCLASS(D, c)
            # 5 prior[c] <-- Nc/N
            # 6 textc <-- CONCATENATETEXTOFALLDOCSINCLASS(D, c)
            # 7 for each t in V
            # 8 do Tct <-- COUNTTOKENSOFTERM(textc, t)
            # 9 for each t in V
            # 10 do condprob[t][c] <-- Tct+1
    # 11 return V, prior, condprob
    """
    prior={}
    N = len(documents)

    #Vocab
    V = Counter()
    for d in documents:
        V.update(doc[***])

    #COUNTDOCSINCLASS(C,D)
    cdic = Counter(C)
    for d2 in documents:
    for label in C:
            cdic.update({label:int(math.ceil(float(doc[***])))})

    #CONCATENATETEXTOFALLDOCSINCLASS(documents,C)
    ctoadic = defaultdict(Counter)
    for d3 in document:
        for label2 in C:
            if(float(***)>0):
                ctoadic[label].update(doc[***]) 

    #used to get term by class it is in
    tii = defaultdict(Counter)
    for label,word in ctoadic.iteritems():
        for w in word:
            tii[w].update({l:word[w]})

    #getCondProb(tii,ctofadic,C)
    gcp = defaultdict(lambda: defaultdict(float))
    tnw ={} #total number of words in that label
    for l,v inctofadic.iteritems():
        tnwl[l] = sum(v.values())
    for w,count in tii.iteritems():

    #for 0 occurences
    z = [zeroo for zeroo in C if zeroo not in count.keys()]
    for ling in z:
        gcp[w[ling]=1.0/(len(ctofadic[ling])+tnw[ling])
    for ling,val in count.iteritems():
        gcp[w][ling]=float(val+1)/(len(ctofadic[ling])+tnw[ling])

    #Prior    
    for c in C:
        prior[c] = cdic[c] / float(N)
    return V,prior,gcp

【问题讨论】:

  • 为了不被关闭,您需要提供一个实际问题,一个带有可量化答案的问题。

标签: python naivebayes


【解决方案1】:

第一个问题

  • 对于词汇,当您将数据发送到分类器时,还会将您遇到的所有单词发送到某个通用标签下。例如,如果您有这样的模型:

    l=label1,W=word1 计数

    l=label1,W=word2 计数

    .

    l=label2,W=word3 计数

    .

    l=label3,W=word1 计数

等等 还要添加类似的内容:-

Vocab,word1 count

Vocab,word2 count

Vocab,word3 count

这里的words1,word2,word3是训练文档中遇到的所有单词,但都是唯一的。将它们存储在 hashmap 中并清除。

然后在分类器中每当遇到“Vocab”时加 1。总数将是 vocab。

  • 对每个文档执行相同操作,保持不同的计数器,并在遇到新文档时递增。

对于问题 2

  • 您是考虑所有课程还是只考虑几个?

【讨论】:

    猜你喜欢
    • 2019-02-21
    • 2018-12-24
    • 2020-05-26
    • 2012-06-09
    • 2015-01-03
    • 2020-04-22
    • 2012-02-11
    • 2019-05-10
    • 2012-02-21
    相关资源
    最近更新 更多