MCPcopy Create free account
hub / github.com/lazyprogrammer/machine_learning_examples / main

Function main

nlp_class2/pos_hmm.py:45–89  ·  view source on GitHub ↗
(smoothing=1e-1)

Source from the content-addressed store, hash-verified

43
44
45def main(smoothing=1e-1):
46 # X = words, Y = POS tags
47 Xtrain, Ytrain, Xtest, Ytest, word2idx = get_data(split_sequences=True)
48 V = len(word2idx) + 1
49
50 # find hidden state transition matrix and pi
51 M = max(max(y) for y in Ytrain) + 1 #len(set(flatten(Ytrain)))
52 A = np.ones((M, M))*smoothing # add-one smoothing
53 pi = np.zeros(M)
54 for y in Ytrain:
55 pi[y[0]] += 1
56 for i in range(len(y)-1):
57 A[y[i], y[i+1]] += 1
58 # turn it into a probability matrix
59 A /= A.sum(axis=1, keepdims=True)
60 pi /= pi.sum()
61
62 # find the observation matrix
63 B = np.ones((M, V))*smoothing # add-one smoothing
64 for x, y in zip(Xtrain, Ytrain):
65 for xi, yi in zip(x, y):
66 B[yi, xi] += 1
67 B /= B.sum(axis=1, keepdims=True)
68
69 hmm = HMM(M)
70 hmm.pi = pi
71 hmm.A = A
72 hmm.B = B
73
74 # get predictions
75 Ptrain = []
76 for x in Xtrain:
77 p = hmm.get_state_sequence(x)
78 Ptrain.append(p)
79
80 Ptest = []
81 for x in Xtest:
82 p = hmm.get_state_sequence(x)
83 Ptest.append(p)
84
85 # print results
86 print("train accuracy:", accuracy(Ytrain, Ptrain))
87 print("test accuracy:", accuracy(Ytest, Ptest))
88 print("train f1:", total_f1_score(Ytrain, Ptrain))
89 print("test f1:", total_f1_score(Ytest, Ptest))
90
91if __name__ == '__main__':
92 main()

Callers 1

pos_hmm.pyFile · 0.70

Calls 5

get_state_sequenceMethod · 0.95
get_dataFunction · 0.90
HMMClass · 0.90
accuracyFunction · 0.85
total_f1_scoreFunction · 0.85

Tested by

no test coverage detected