作業帖 | NLP+推薦-深度學習集訓營 【第一次作業】

AI Studio用戶名:javaroom

作業1-1

1paddlepaddle安裝

pip3 install paddlepaddle -i https://pypi.tuna.tsinghua.edu.cn/simple

 

2)學習使用PaddleNLP下面的LAC模型或Jieba分詞

 

3)對人民日報語料完成切詞,並通過統計每個詞出現的概率,計算信息熵

# -*- coding: utf-8 -*-
"""
__title__ =
__author__ = javaroom
__date__ = 2020/2/26 15:32
"""

import os
import math
import jieba
from collections import Counter


def word_count(filepath):
    word_list = []
    file_list = os.listdir(filepath)
    for file in file_list:
        path = os.path.join(filepath, file)
        text = open(path, encoding='utf-8').read()
        text = text.strip().replace(' ', '').replace('\n', '').replace('“', '') \
            .replace('”', '').replace('、', '') \
            .replace(',', '').replace('。', '').replace('。', '') \
            .replace('(', '').replace(')', '').replace('-', '')
        seg_list = jieba.cut(text)
        word_list += seg_list
    word_count = Counter(word_list)
    # 計算信息熵
    entropy = 0
    for word in word_count:
        word_count[word] /= len(word_list)
        percent = word_count[word]
        entropy += percent * math.log(percent, 2)
    entropy = -entropy
    print("信息熵:", entropy)


if __name__ == '__main__':
    file_dir = '194605'
    word_count(file_dir)
C:\Python37\python.exe C:/Users/Administrator/PycharmProjects/paddletest/fenci/jiebatest.py
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\ADMINI~1\AppData\Local\Temp\jieba.cache
Loading model cost 0.650 seconds.
Prefix dict has been built successfully.
信息熵: 11.762779320674147

Process finished with exit code 0

 

作業1-2

1)思考一下,假設輸入一個詞表裏面含有N個詞,輸入一個長度爲M的句子,那麼最大前向匹配的計算複雜度是多少?

從後向前,依次和詞表裏N個詞進行比較,那麼應該是N*(m(m+1)/2)

 

2)給定一個句子,如何計算裏面有多少種分詞候選,你能給出代碼實現嗎?

最多的分詞候選,那麼急於最大前向匹配算法,從後到前,每匹配上1詞,算1個。

 

 

3)除了最大前向匹配和N-gram算法,你還知道其他分詞算法嗎,請給出一段小描述。

前向最大匹配算法:從前向後尋找在詞典中存在的詞。

 

後向最大匹配算法:與前向最大匹配算法類似,只是方向相反,即從後向前尋找詞典中存在的詞並輸出。

 

雙向最大匹配算法:雙向最大匹配算法的原理就是將正向最大匹配算法和逆向最大匹配算法進行比較,從而確定正確的分詞方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章