原文地址:https://gist.github.com/neubig/7352832

This is a script to train conditional random fields. It is written to minimize the number of lines of code, with no regard for efficiency.

[python] view plaincopy
  1. #!/usr/bin/python
  2. # crf.py (by Graham Neubig)
  3. #  This script trains conditional random fields (CRFs)
  4. #  stdin: A corpus of WORD_POS WORD_POS WORD_POS sentences
  5. #  stdout: Feature vectors for emission and transition properties
  6. from collections import defaultdict
  7. from math import log, exp
  8. import sys
  9. import operator
  10. # The L2 regularization coefficient and learning rate for SGD
  11. l2_coeff = 1
  12. rate = 10
  13. # A dictionary to map tags to integers
  14. tagids = defaultdict(lambda: len(tagids))
  15. tagids["<S>"] = 0
  16. ############# Utility functions ###################
  17. def dot(A, B):
  18. return sum(A[k]*B[k] for k in A if k in B)
  19. def add(A, B):
  20. C = defaultdict(A, lambda: 0)
  21. # for k, v in A.items(): C[k] += v
  22. for k, v in B.items(): C[k] += v
  23. return C
  24. def logsumexp(A):
  25. k = max(A)
  26. return log(sum( exp(i-k) for i in A ))+k
  27. ############# Functions for memoized probability
  28. def calc_feat(x, i, l, r):
  29. return { ("T", l, r): 1, ("E", r, x[i]): 1 }
  30. def calc_e(x, i, l, r, w, e_prob):
  31. if (i, l, r) not in e_prob:
  32. e_prob[i,l,r] = dot(calc_feat(x, i, l, r), w)
  33. return e_prob[i,l,r]
  34. def calc_f(x, i, l, w, e, f):
  35. if (i, l) not in f:
  36. if i == 0:
  37. f[i,0] = 0
  38. else:
  39. prev_states = (range(1, len(tagids)) if i != 1 else [0])
  40. f[i,l] = logsumexp([
  41. calc_f(x, i-1, k, w, e, f) + calc_e(x, i, k, l, w, e)
  42. for k in prev_states])
  43. return f[i,l]
  44. def calc_b(x, i, r, w, e, b):
  45. if (i, r) not in b:
  46. if i == len(x)-1:
  47. b[i,0] = 0
  48. else:
  49. prev_states = (range(1, len(tagids)) if i != len(x)-2 else [0])
  50. b[i,r] = logsumexp([
  51. calc_b(x, i+1, k, w, e, b) + calc_e(x, i, r, k, w, e)
  52. for k in prev_states])
  53. return b[i,r]
  54. ############# Function to calculate gradient ######
  55. def calc_gradient(x, y, w):
  56. f_prob = {(0,0): 0}
  57. b_prob = {(len(x)-1,0): 0}
  58. e_prob = {}
  59. grad = defaultdict(lambda: 0)
  60. # Add the features for the numerator
  61. for i in range(1, len(x)):
  62. for k, v in calc_feat(x, i, y[i-1], y[i]).items(): grad[k] += v
  63. # Calculate the likelihood and normalizing constant
  64. norm = calc_b(x, 0, 0, w, e_prob, b_prob)
  65. lik = dot(grad, w) - norm
  66. # Subtract the features for the denominator
  67. for i in range(1, len(x)):
  68. for l in (range(1, len(tagids)) if i != 1 else [0]):
  69. for r in (range(1, len(tagids)) if i != len(x)-1 else [0]):
  70. # Find the probability of using this path
  71. p = exp(calc_e(x, i, l, r, w, e_prob)
  72. + calc_b(x, i,   r, w, e_prob, b_prob)
  73. + calc_f(x, i-1, l, w, e_prob, f_prob)
  74. - norm)
  75. # Subtract the expectation of the features
  76. for k, v in calc_feat(x, i, l, r).items(): grad[k] -= v * p
  77. # print grad
  78. # Return the gradient and likelihood
  79. return (grad, lik)
  80. ############### Main training loop
  81. if __name__ == '__main__':
  82. # load in the corpus
  83. corpus = []
  84. for line in sys.stdin:
  85. words = [ "<S>" ]
  86. tags  = [   0   ]
  87. line = line.strip()
  88. for w_t in line.split(" "):
  89. w, t = w_t.split("_")
  90. words.append(w)
  91. tags.append(tagids[t])
  92. words.append("<S>")
  93. tags.append(0)
  94. corpus.append( (words, tags) )
  95. # for 50 iterations
  96. w = defaultdict(lambda: 0)
  97. for iternum in range(1, 50+1):
  98. grad = defaultdict(lambda: 0)
  99. # Perform regularization
  100. reg_lik = 0;
  101. for k, v in w.items():
  102. grad[k] -= 2*v*l2_coeff
  103. reg_lik -= v*v*l2_coeff
  104. # Get the gradients and likelihoods
  105. lik = 0
  106. for x, y in corpus:
  107. my_grad, my_lik = calc_gradient(x, y, w)
  108. for k, v in my_grad.items(): grad[k] += v
  109. lik += my_lik
  110. l1 = sum( [abs(k) for k in grad.values()] )
  111. print >> sys.stderr, "Iter %r likelihood: lik=%r, reg=%r, reg+lik=%r gradL1=%r" % (iternum, lik, reg_lik, lik+reg_lik, l1)
  112. # Here we are updating the weights with SGD, but a better optimization
  113. # algorithm is necessary if you want to use this in practice.
  114. for k, v in grad.items(): w[k] += v/l1*rate
  115. # Reverse the tag strings
  116. strs = range(0, len(tagids))
  117. for k, v in tagids.items(): strs[v] = k
  118. # Print the features
  119. for k, v in sorted(w.iteritems(), key=operator.itemgetter(1)):
  120. if k[0] == "E": print "%s %s %s\t%r" % (k[0], strs[k[1]], k[2], v)
  121. else:           print "%s %s %s\t%r" % (k[0], strs[k[1]], strs[k[2]], v)

python写的crf训练代码相关推荐

  1. python写一个游戏多少代码-使用Python写一个贪吃蛇游戏实例代码

    我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中. 特殊食物: 1.绿色:普通,吃了增加体型 2.红色:吃了减少体型 3.金色:吃了回到 ...

  2. 女神相册密码忘记了,我只用Python写了20行代码

    ​视频地址 我用20行代码,帮女神破解相册密码 一.事情是这样的 今早上班,公司女神小姐姐说,她去年去三亚旅游的照片打不开了 好奇问了一下才知道. 原来是,她把照片压缩了,而且还加了密码. 但是密码不 ...

  3. python扫雷游戏实验分析_用python写扫雷游戏实例代码分享

    扫雷是一个非常经典的WIN游戏,我们教给大家用python语言来写出这个游戏,以下是全部实例代码: #!/usr/bin/python #coding:utf-8 #python 写的扫雷游戏 imp ...

  4. 用python写一段表白代码

    您好!以下是用 Python 写的表白代码: print("亲爱的,我一直在想念你.") print("你是我生命中最重要的人,你是我一直以来的支持者,我的朋友,我的爱人 ...

  5. 女神相册密码忘记了,我只用Python写了20行代码就破解了!

    一.事情是这样的 今早上班,公司女神小姐姐说,她去年去三亚旅游的照片打不开了 好奇问了一下才知道. 原来是,她把照片压缩了,而且还加了密码. 但是密码不记得了,只记得是一串6位数字. 话说照片压缩率也 ...

  6. python写一个游戏多少代码-使用50行Python代码从零开始实现一个AI平衡小游戏

    集智导读: 本文会为大家展示机器学习专家 Mike Shi 如何用 50 行 Python 代码创建一个 AI,使用增强学习技术,玩耍一个保持杆子平衡的小游戏.所用环境为标准的 OpenAI Gym, ...

  7. python爬虫代码-学Python=写爬虫?不用代码也能爬下95%网站的数据!

    你好,这里是BIMBOX,我是老孙. 前些天BOX群里一位小伙伴问我们,现在市面上有一千多块钱的Python网络课程,两个月学完,能入门网络爬虫,大部分网站的数据都可以爬下来,这个学费值不值得? 我们 ...

  8. 用python写父亲节祝福代码_父亲节,程序员几条代码硬核示爱

    摘要:祝所有的父亲,节日快乐! 父亲节要送什么? 对老爸的爱在心口难开怎么办? 都说父爱如山,山也需要偶尔的温情问候,与其在网上遍寻各种攻略,不如敲起手中的键盘,码出几行代码,用你最熟悉的方式表达对父 ...

  9. python量化投资必背代码-重磅!我把自己耗费两年用Python写的量化投资代码开源了!...

    原文地址:https://mp.weixin.qq.com/s?__biz=MzU4ODcyMTI1Nw==&mid=2247483842&idx=1&sn=024de1af0 ...

  10. python写一个游戏多少代码-Python项目实战之猜数字游戏(含实现代码)

    猜数字游戏,旨在提高初学者对 Python 变量类型以及循环结构的使用. 此游戏的游戏规则如下:程序随机内置一个位于一定范围内的数字作为猜测的结果,由用户猜测此数字.用户每猜测一次,由系统提示猜测结果 ...

最新文章

  1. Python爬虫小偏方:如何用robots.txt快速抓取网站?
  2. MaxCompute助力ofo实现精细化运营:日订单超3200万、整体运行效率提升76%
  3. cocos2dx - Lua 语言
  4. python3.7 6如何安装-centos安装python3.7
  5. 什么是脱离文档流?什么是文档流?
  6. Windows平台下安装PhoenixSuit要点
  7. WIN7 IE8的桌面图标解决了(简单有效)
  8. Vue项目代码改进(三)—— Cookie、LocalStorage和SessionStorage的使用
  9. 蒙特卡洛方法_基本理论-蒙特卡洛方法与定积分
  10. 怎么在前台取的ViewBag中的值
  11. Python基础学习----异常
  12. 结合ENVI与ArcMAP的NC数据处理(均值、最大最小值等)心得记录
  13. java数组验证哥德巴赫猜想_验证哥德巴赫猜想的JAVA代码
  14. 最新酷盒工具箱iApp源码9.5版+功能很多
  15. Visual Studio Coded的安装以及中文化
  16. FLOPS-定义每秒浮点运算次数
  17. 心理学效应:阿基米德与酝酿效应
  18. Google Drive—谷歌云盘大文件下载
  19. 俄罗斯最大的盗版资源网站,解封了!
  20. 多变量微积分笔记(1)——向量和矩阵

热门文章

  1. double类型数据保留四位小数的另一种思路
  2. jquery里判断数组内是否包含了指定的值或元素的方法
  3. 关于testNG和JUnit的对比
  4. 用例设计思路 C/S测试—安装与卸载
  5. ElasticSearch5.1 基本概念和配置
  6. OpenWrt常用命令总结
  7. iOS上绘制自然的签名-b
  8. LVS+KeepAlived,RabbitMQ高可用负载均衡
  9. Data Guard Service 相关介绍
  10. SSAS中出现“对象引用未被设置到对象实例”的解决记录