作业帖 | 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算法,你还知道其他分词算法吗,请给出一段小描述。

前向最大匹配算法:从前向后寻找在词典中存在的词。

 

后向最大匹配算法:与前向最大匹配算法类似,只是方向相反,即从后向前寻找词典中存在的词并输出。

 

双向最大匹配算法:双向最大匹配算法的原理就是将正向最大匹配算法和逆向最大匹配算法进行比较,从而确定正确的分词方法。

发布了52 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/livingbody/article/details/104521409