最大熵实现(MEGAM)

同样是使用NLTK来实现,NLTK的安装之前博文有说过在此不再赘述。

http://www.cnblogs.com/mansiisnam/p/5301892.html

之前在网上找了很多实现最大熵+LBFGS的资料,也看了大牛自己写代码实现出来的博客。但是本人的基础薄弱难以对大牛的代码进行修改以达到自己的预期,所以就想着使用工具包实现。windows 使用NLTK的MEGAM比较麻烦,博主之前找了很多资料没有实现有兴趣的可以看这个链接(http://www.cnblogs.com/createMoMo/archive/2013/05/15/3079290.html)

博主使用的linux 实现的方法特别简单

只要在你项目中根目录加上megam.opt这个文件,如图

 

这个文件在官网有下载但是官网给出的是32位的。如果你是64位的则需要通过OCaml 将其编译成64位。然后在代码上添加

nltk.config_megam('./megam.opt')这一句即可。整个程序即可运行。附上32 和64位megam.opt 和data文件下载链接:

megam:https://files.cnblogs.com/files/mansiisnam/MEGAM.zip

上述文件经测试在unbantu 和centos 7.0 64 上可用。

data:https://files.cnblogs.com/files/mansiisnam/data.zip

代码如下:python 2.7

import sys;
import scipy;
import nltk;
from nltk.classify import MaxentClassifier
nltk.config_megam('./megam.opt')
def load_data(filename):
    for line in open(filename, mode='r'):
        sample = line.strip().split("\t"); 
        y = sample[0];        
        reason1={'outlook':sample[1],'temperature':sample[2],'humidity':sample[3],'windy':sample[4]};
        if(y=='no'):
            train.append((reason1,'x'));
        elif(y=='yes'):
            train.append((reason1,'y')) ;                                               
def print_maxent_test_header():
    print(' '*11+''.join(['      test[%s]  ' % i
                           for i in range(len(test))]))
    print(' '*11+'     p(x)  p(y)'*len(test))
    print('-'*(11+15*len(test)))
def test_maxent(algorithm):
    print "%11s" % algorithm , " "
    try:
        classifier = MaxentClassifier.train(
                         train, algorithm, trace=0, max_iter=1000) 
    except Exception as e:
        print('Error: %r' % e)
        return

    for featureset in test:
        pdist = classifier.prob_classify(featureset)
        print "%8.15f" % pdist.prob('x'), "%6.15f" %  pdist.prob('y') , 
    print " "
if __name__ == '__main__' :
    train=[];
    load_data('data.txt');
    test1={'outlook':'sunny','temperature':'hot','humidity':'high','windy':'FALSE'};
    test2={'outlook':'overcast','temperature':'hot','humidity':'high','windy':'FALSE'};
    test3={'outlook':'sunny','temperature':'cool','humidity':'high','windy':'TRUE'};
    test=[];
    test.append(test1);
    test.append(test2);
    test.append(test3);
    print_maxent_test_header(); 
    test_maxent('GIS');
    test_maxent('IIS');
    test_maxent('MEGAM');
    sys.exit(0);

 

posted @ 2016-08-23 17:17  mansiisnam  阅读(2021)  评论(1编辑  收藏  举报