【问题标题】:How to write features in nltk to a txt file?如何将 nltk 中的功能写入 txt 文件?
【发布时间】:2013-05-07 03:19:10
【问题描述】:

我用 nltk 训练了一个朴素贝叶斯分类器。函数show_most_informative_features(source code)可以将训练过程中的最高似然特征打印到python shell,但是没有返回值。

现在我想将信息量最大的功能写入 txt 文件。但是,这些功能都是 Unicode,包含中文/日文单词和一些特殊符号。我无法使用“>”将打印重定向到 txt 文件。

那么如何使用此函数将功能写入 txt 文件而不返回值?谢谢。

【问题讨论】:

    标签: python file machine-learning stdout nltk


    【解决方案1】:

    请不要更改 nltk 库的源代码! 这是非常糟糕的做法。例如,如果您更新库,或者如果您需要与没有相应修改其库的其他人共享您的代码,会发生什么?

    库的行为是标准化的!

    对于你的问题,你有等效的功能

    classifier.most_informative_features(n)
    

    它会返回你训练的分类器的 n 个信息量最大的特征列表!!!!

    【讨论】:

    • 是的,任何需要朴素贝叶斯信息最丰富的功能列表的人都应该使用这个答案。不幸的是,maxent 没有等效的方法。
    【解决方案2】:

    从源代码更改为简单。 (我没有尝试。)

    def show_most_informative_features(self, n=10):
        strlist = []
        # Determine the most relevant features, and display them.
        cpdist = self._feature_probdist
        # print('Most Informative Features')
        strlist.append('Most Informative Features')
    
        for (fname, fval) in self.most_informative_features(n):
                def labelprob(l):
                    return cpdist[l,fname].prob(fval)
                labels = sorted([l for l in self._labels
                         if fval in cpdist[l,fname].samples()],
                        key=labelprob)
                if len(labels) == 1: continue
                l0 = labels[0]
                l1 = labels[-1]
                if cpdist[l0,fname].prob(fval) == 0:
                    ratio = 'INF'
                else:
                    ratio = '%8.1f' % (cpdist[l1,fname].prob(fval) /
                              cpdist[l0,fname].prob(fval))
                # print(('%24s = %-14r %6s : %-6s = %s : 1.0' %
                #      (fname, fval, ("%s" % l1)[:6], ("%s" % l0)[:6], ratio)))
                strlist.append(('%24s = %-14r %6s : %-6s = %s : 1.0' %
                              (fname, fval, ("%s" % l1)[:6], ("%s" % l0)[:6], ratio)))
    
        return strlist
    
    # Useage
    list = show_most_informative_features(classifier, 100)
    file.writelines(list)
    

    附:

    请不要直接修改源代码!

    【讨论】:

    • 非常感谢!我只是停留在将结果“打印”到 txt 文件中,忘记更改源代码。而且这个方法效果很好!
    • 请不要更改nltk库的源代码!这是非常糟糕的做法。例如,如果您更新库,或者如果您需要与没有相应修改其库的其他人共享您的代码,会发生什么?
    • 谢谢,我的意思是从源代码复制代码并进行更改。源代码不变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多