Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUGFIX] Chapter-3 Fixes bugs for word segmentation model in HMM #39

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified chapter-3/data/hmm_model.pkl
Binary file not shown.
25 changes: 17 additions & 8 deletions chapter-3/分词.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,8 @@
" self.Pi_dic[v] += 1 # 每个句子的第一个字的状态,用于计算初始状态概率\n",
" else:\n",
" self.A_dic[line_state[k - 1]][v] += 1 # 计算转移概率\n",
" self.B_dic[line_state[k]][word_list[k]] = \\\n",
" self.B_dic[line_state[k]].get(word_list[k], 0) + 1.0 # 计算发射概率\n",
" self.B_dic[line_state[k]][word_list[k]] = \\\n",
" self.B_dic[line_state[k]].get(word_list[k], 0) + 1.0 # 计算发射概率\n",
" \n",
" self.Pi_dic = {k: v * 1.0 / line_num for k, v in self.Pi_dic.items()}\n",
" self.A_dic = {k: {k1: v1 / Count_dic[k] for k1, v1 in v.items()}\n",
Expand All @@ -201,6 +201,12 @@
" for y in states:\n",
" V[0][y] = start_p[y] * emit_p[y].get(text[0], 0)\n",
" path[y] = [y]\n",
" if text[0] not in emit_p['S'].keys() and \\\n",
" text[0] not in emit_p['M'].keys() and \\\n",
" text[0] not in emit_p['E'].keys() and \\\n",
" text[0] not in emit_p['B'].keys():\n",
" V[0] = {'B': 1.0, 'M': 0.0, 'E': 0.0, 'S': 0.0}\n",
" path = {'B': ['B'], 'M': ['M'], 'E': ['E'], 'S': ['S']}\n",
" for t in range(1, len(text)):\n",
" V.append({})\n",
" newpath = {}\n",
Expand All @@ -220,10 +226,7 @@
" newpath[y] = path[state] + [y]\n",
" path = newpath\n",
" \n",
" if emit_p['M'].get(text[-1], 0)> emit_p['S'].get(text[-1], 0):\n",
" (prob, state) = max([(V[len(text) - 1][y], y) for y in ('E','M')])\n",
" else:\n",
" (prob, state) = max([(V[len(text) - 1][y], y) for y in states])\n",
" (prob, state) = max((V[len(text) - 1][y], y) for y in ('E', 'S'))\n",
" \n",
" return (prob, path[state])\n",
"\n",
Expand Down Expand Up @@ -269,9 +272,15 @@
"hmm.train('./data/trainCorpus.txt_utf8')\n",
"\n",
"text = '这是一个非常棒的方案!'\n",
"res = hmm.cut(text)\n",
"res = []\n",
"split_text = text.split(\",\")\n",
"for i in range(1,len(split_text)):\n",
" split_text[i] = \",\" + split_text[i]\n",
"for fragment in split_text:\n",
" for segment in list(hmm.cut(fragment)):\n",
" res.append(segment)\n",
"print(text)\n",
"print(str(list(res)))"
"print(str(res))"
]
},
{
Expand Down