随机条件场—概率计算问题、IIS/GD学习算法、维特比预测算法
这一章的算法不是很好写,整整研究了好几天,代码还是有点小问题,仅供参考。
用的是书上定义的特征函数。
import numpy as np
class CRF:
def __init__(self,y=None,x=None,y_num=None,x_num=None,N=None):
self.y = y
self.x = x
self.y_num = y_num
self.x_num = x_num
self.N = N
self.get_feature()
self.build_Marix(self.x[0])
def get_feature(self):
self.ti = [lambda y_1, y, x, i: 1 if i == 2 and y_1 == 1 and y == 2 else 0,
lambda y_1, y, x, i: 1 if i == 3 and y_1 == 1 and y == 2 else 0,
lambda y_1, y, x, i: 1 if i == 2 and y_1 == 1 and y == 1 else 0,
lambda y_1, y, x, i: 1 if i == 3 and y_1 == 2 and y == 1 else 0,
lambda y_1, y, x, i: 1 if i == 2 and y_1 == 2 and y == 1 else 0,
lambda y_1, y, x, i: 1 if i == 3 and y_1 == 2 and y == 2 else 0,
]
self.w_ti = [1,1,0.6,1,1,0.2]
self.si = [lambda y_1, y, x, i: 1 if i == 1 and y == 1 else 0,
lambda y_1, y, x, i: 1 if i == 1 and y == 2 else 0,
lambda y_1, y, x, i: 1 if i == 2 and y == 2 else 0,
lambda y_1, y, x, i: 1 if i == 2 and y == 1 else 0,
lambda y_1, y, x, i: 1 if i == 3 and y == 1 else 0,
lambda y_1, y, x, i: 1 if i == 3 and y == 2 else 0,
]
self.w_si = [1,0.5,0.5,0.8,0.8,0.5]
self.fk = self.ti+self.si
self.wk = self.w_ti+self.w_si
def build_Marix(self,x):
self.Marix = np.zeros((self.N+1,self.y_num,self.y_num))
for i in range(self.N+1):
for n in range(self.y_num):
if i == self.N:
self.Marix[i][:,0] = 1
break
for m in range(self.y_num):
for k in range(len(self.fk)):
if i == 0:
if n==0:
self.Marix[i][0][m] += self.wk[k] * (self.fk[k](0,m+1,x[i],i+