为了账号安全,请及时绑定邮箱和手机立即绑定

将主题模型存储在列表中也考虑了最大出现次数

将主题模型存储在列表中也考虑了最大出现次数

江户川乱折腾 2021-08-14 15:57:19
我正在执行主题建模并使用函数来获取主题模型中的顶级关键字,如下所示。def getTopKWords(self, K):    results  = []    """    returns top K discriminative words for topic t    ie words v for which p(v|t) is maximum    """    index = []    key_terms = []    pseudocounts = np.copy(self.n_vt)    normalizer = np.sum(pseudocounts, (0))    pseudocounts /= normalizer[np.newaxis, :]    for t in range(self.numTopics):        topWordIndices = pseudocounts[:, t].argsort()[-1:-(K+1):-1]        vocab = self.vectorizer.get_feature_names()        print (t, [vocab[i] for i in topWordIndices])   ## Code for storing the values in a single list   return results上面的函数给了我如图所示的代码0 ['computer', 'laptop', 'mac', 'use', 'bought', 'like', 'warranty', 'screen', 'way', 'just']1 ['laptop', 'computer', 'use', 'just', 'like', 'time', 'great', 'windows', 'macbook', 'months']2 ['computer', 'great', 'laptop', 'mac', 'buy', 'just', 'macbook', 'use', 'pro', 'windows']3 ['laptop', 'computer', 'great', 'time', 'battery', 'use', 'apple', 'love', 'just', 'work']它是循环运行 4 次并打印索引和每个词汇中的所有关键字的结果。现在,我想从返回以下输出的函数中返回一个列表。return   [keyword1, keyword2, keyword3, keyword4]其中,keyword1/2/3/4 是在输出中索引为 0、1、2、3 的词汇表中出现次数最多的单词。
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

您可以使用collection.Counter:


from collections import Counter


a = ['computer', 'laptop', 'mac', 'use', 'bought', 'like', 

     'warranty', 'screen', 'way', 'just']

b = ['laptop', 'computer', 'use', 'just', 'like', 'time', 

     'great', 'windows', 'macbook', 'months']

c = ['computer', 'great', 'laptop', 'mac', 'buy', 'just', 

     'macbook', 'use', 'pro', 'windows']

d = ['laptop', 'computer', 'great', 'time', 'battery', 'use', 

     'apple', 'love', 'just', 'work']


def get_most_common(*kwargs):

    """Accepts iterables, feeds all into Counter and returns the Counter instance"""

    c = Counter()

    for k in kwargs:

        c.update(k)

    return c


# get the most common ones 

mc = get_most_common(a,b,c,d).most_common()


# print top 4 keys

top4 = [k for k,v in mc[0:4]]

print (top4)

输出:


['computer', 'laptop', 'use', 'just']

 some_results = [] # store stuff

for t in range(self.numTopics):

    topWordIndices = pseudocounts[:, t].argsort()[-1:-(K+1):-1]

    vocab = self.vectorizer.get_feature_names()

    print (t, [vocab[i] for i in topWordIndices])

      some_results.append( [vocab[i] for i in topWordIndices] )


  mc = get_most_common(*some_results).most_common()

  return [k for k,v in mc[0:4]] 


查看完整回答
反对 回复 2021-08-14
  • 1 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号