原文链接:http://www.one2know.cn/nlp23/

  • N元模型

    预测要输入的连续词,比如



    如果抽取两个连续的词汇,则称之为二元模型
  • 准备工作

    数据集使用 Alice in Wonderland

    将初始数据提取N-grams
import nltk
import string with open('alice_in_wonderland.txt', 'r') as content_file:
content = content_file.read()
content2 = " ".join("".join([" " if ch in string.punctuation else ch for ch in content]).split())
tokens = nltk.word_tokenize(content2)
tokens = [word.lower() for word in tokens if len(word)>=2] N = 3
quads = list(nltk.ngrams(tokens,N))
"""
Return the ngrams generated from a sequence of items, as an iterator.
For example:
>>> from nltk.util import ngrams
>>> list(ngrams([1,2,3,4,5], 3))
[(1, 2, 3), (2, 3, 4), (3, 4, 5)]
"""
newl_app = []
for ln in quads:
new1 = ' '.join(ln)
newl_app.append(new1)
print(newl_app[:3])

输出:

['alice adventures in', 'adventures in wonderland', 'in wonderland alice']
  • 如何实现

    1.预处理:词转换为词向量

    2.创建模型和验证:将输入映射到输出的收敛-发散模型(convergent-divergent)

    3.预测:最优词预测
  • 代码
from __future__ import print_function

from sklearn.model_selection import train_test_split
import nltk
import numpy as np
import string with open('alice_in_wonderland.txt', 'r') as content_file:
content = content_file.read()
content2 = " ".join("".join([" " if ch in string.punctuation else ch for ch in content]).split())
tokens = nltk.word_tokenize(content2)
tokens = [word.lower() for word in tokens if len(word)>=2] N = 3
quads = list(nltk.ngrams(tokens,N))
"""
Return the ngrams generated from a sequence of items, as an iterator.
For example:
>>> from nltk.util import ngrams
>>> list(ngrams([1,2,3,4,5], 3))
[(1, 2, 3), (2, 3, 4), (3, 4, 5)]
"""
newl_app = []
for ln in quads:
new1 = ' '.join(ln)
newl_app.append(new1)
# print(newl_app[:3]) # 将单词向量化
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer() # 词=>词向量
"""
>>> corpus = [
... 'This is the first document.',
... 'This document is the second document.',
... 'And this is the third one.',
... 'Is this the first document?',
... ]
>>> vectorizer = CountVectorizer()
>>> X = vectorizer.fit_transform(corpus)
>>> print(vectorizer.get_feature_names())
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
>>> print(X.toarray()) # doctest: +NORMALIZE_WHITESPACE
[[0 1 1 1 0 0 1 0 1]
[0 2 0 1 0 1 1 0 1]
[1 0 0 1 1 0 1 1 1]
[0 1 1 1 0 0 1 0 1]]
""" x_trigm = []
y_trigm = [] for l in newl_app:
x_str = " ".join(l.split()[0:N-1])
y_str = l.split()[N-1]
x_trigm.append(x_str)
y_trigm.append(y_str) x_trigm_check = vectorizer.fit_transform(x_trigm).todense()
y_trigm_check = vectorizer.fit_transform(y_trigm).todense() # Dictionaries from word to integer and integer to word
dictnry = vectorizer.vocabulary_
rev_dictnry = {v:k for k,v in dictnry.items()} X = np.array(x_trigm_check)
Y = np.array(y_trigm_check) Xtrain, Xtest, Ytrain, Ytest,xtrain_tg,xtest_tg = train_test_split(X, Y,x_trigm, test_size=0.3,random_state=1) print("X Train shape",Xtrain.shape, "Y Train shape" , Ytrain.shape)
print("X Test shape",Xtest.shape, "Y Test shape" , Ytest.shape) # Model Building
from keras.layers import Input,Dense,Dropout
from keras.models import Model np.random.seed(1) BATCH_SIZE = 128
NUM_EPOCHS = 20 input_layer = Input(shape = (Xtrain.shape[1],),name="input")
first_layer = Dense(1000,activation='relu',name = "first")(input_layer)
first_dropout = Dropout(0.5,name="firstdout")(first_layer) second_layer = Dense(800,activation='relu',name="second")(first_dropout) third_layer = Dense(1000,activation='relu',name="third")(second_layer)
third_dropout = Dropout(0.5,name="thirdout")(third_layer) fourth_layer = Dense(Ytrain.shape[1],activation='softmax',name = "fourth")(third_dropout) history = Model(input_layer,fourth_layer)
history.compile(optimizer = "adam",loss="categorical_crossentropy",metrics=["accuracy"]) print (history.summary()) # Model Training
history.fit(Xtrain, Ytrain, batch_size=BATCH_SIZE,epochs=NUM_EPOCHS, verbose=1,validation_split = 0.2) # Model Prediction
Y_pred = history.predict(Xtest) # 测试
print ("Prior bigram words","|Actual","|Predicted","\n")
import random
NUM_DISPLAY = 10
for i in random.sample(range(len(xtest_tg)),NUM_DISPLAY):
print (i,xtest_tg[i],"|",rev_dictnry[np.argmax(Ytest[i])],"|",rev_dictnry[np.argmax(Y_pred[i])])

输出:

X Train shape (17947, 2559) Y Train shape (17947, 2559)
X Test shape (7692, 2559) Y Test shape (7692, 2559) _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input (InputLayer) (None, 2559) 0
_________________________________________________________________
first (Dense) (None, 1000) 2560000
_________________________________________________________________
firstdout (Dropout) (None, 1000) 0
_________________________________________________________________
second (Dense) (None, 800) 800800
_________________________________________________________________
third (Dense) (None, 1000) 801000
_________________________________________________________________
thirdout (Dropout) (None, 1000) 0
_________________________________________________________________
fourth (Dense) (None, 2559) 2561559
=================================================================
Total params: 6,723,359
Trainable params: 6,723,359
Non-trainable params: 0
_________________________________________________________________
None Prior bigram words |Actual |Predicted
595 words don | fit | know
3816 in tone | of | of
5792 queen had | only | been
2757 who seemed | to | to
5393 her and | she | she
4197 heard of | one | its
2464 sneeze were | the | of
1590 done with | said | whiting
3039 and most | things | of
4226 the queen | of | said

训练结果不好,因为单词向量维度太大,为2559,相对而言总数据集的单词太少;除了单词预测,还可以字符预测,每碰到一个空格算一个单词

NLP(二十三)使用LSTM进行语言建模以预测最优词的更多相关文章

  1. NLP(二十二)使用LSTM进行语言建模以预测最优词

    预处理 数据集使用Facebook上的BABI数据集 将文件提取成可训练的数据集,包括:文章 问题 答案 def get_data(infile): stories,questions,answers ...

  2. C++学习(二十三)(C语言部分)之 指针4

    指针 指针 存放地址 只能存放地址 使用 &取地址运算符 *取值 解引用运算符 malloc 申请堆内存 free释放堆内存 1.1 指针 存放的地址(变量地址 常量区的地址 堆区内存首地址 ...

  3. 一起talk C栗子吧(第一百二十三回:C语言实例--显示变量和函数的地址)

    各位看官们,大家好,上一回中咱们说的是多线程的样例.这一回咱们说的样例是:显示变量和函数的地址. 闲话休提,言归正转.让我们一起talk C栗子吧! 在编敲代码时,有时候须要获取程序中变量和函数的地址 ...

  4. 利用UML语言建模--以图书馆管理系统为例

    一.基本信息 标题:利用UML语言建模--以图书馆管理系统为例 时间:2016 出版源:内蒙古科技与经济 领域分类:UML:RFID:图书馆:模型: 二.研究背景 问题定义:建立图书馆管理系统 难点: ...

  5. 二十三、并发编程之深入解析Condition源码

    二十三.并发编程之深入解析Condition源码   一.Condition简介 1.Object的wait和notify/notifyAll方法与Condition区别 任何一个java对象都继承于 ...

  6. 网络流量预测入门(二)之LSTM介绍

    目录 网络流量预测入门(二)之LSTM介绍 LSTM简介 Simple RNN的弊端 LSTM的结构 细胞状态(Cell State) 门(Gate) 遗忘门(Forget Gate) 输入门(Inp ...

  7. WPF入门教程系列二十三——DataGrid示例(三)

    DataGrid的选择模式 默认情况下,DataGrid 的选择模式为“全行选择”,并且可以同时选择多行(如下图所示),我们可以通过SelectionMode 和SelectionUnit 属性来修改 ...

  8. Bootstrap <基础二十三>页面标题(Page Header)

    页面标题(Page Header)是个不错的功能,它会在网页标题四周添加适当的间距.当一个网页中有多个标题且每个标题之间需要添加一定的间距时,页面标题这个功能就显得特别有用.如需使用页面标题(Page ...

  9. Web 前端开发精华文章推荐(HTML5、CSS3、jQuery)【系列二十三】

    <Web 前端开发精华文章推荐>2014年第2期(总第23期)和大家见面了.梦想天空博客关注 前端开发 技术,分享各类能够提升网站用户体验的优秀 jQuery 插件,展示前沿的 HTML5 ...

随机推荐

  1. CSS布局定位基础-盒模型和定位机制

    1. 盒模型 2. 外边距合并 3. 定位机制 4. Float 5. Position:属性有哪些取值,它们的行为是什么? 无依赖绝对定位? 6. Display:常见属性值有哪些取值? 7. 对B ...

  2. web设计_4_可扩展的行

    不要指定横向页面组件的高度,要让它们能够在纵向自由扩展. 常见的包含文章正文或大段文字的区域,应该适应任何篇幅和大小的文字. 但是例如文章标题.登陆信息栏等也要考虑文字内容数量及高度的变化. 例如:下 ...

  3. WPF 动态添加按钮以及样式字典的引用(Style introduction)

    我们想要达到的结果是,绑定多个Checkbox然后我们还可以获取它是否被选中,其实很简单,我们只要找到那几个关键的对象就可以了. 下面是Ui,其中定义了一个WrapPanel来存放CheckBox,还 ...

  4. VS、C#配置R语言开发环境

    R语言学习笔记(一)——在Vs.C#中配置R语言开发环境. 最近在学习小众的R语言,所以将遇到的问题记录下来供大家参考,不足之处欢迎大家交流指正. 至于R语言的介绍就不多说了,它集成了复杂的数学算法, ...

  5. 【iOS】Error: Error Domain=PBErrorDomain Code=7 "Cannot connect to pasteboard server

    这几天在用 Swift 开发一个简单的键盘扩展,真机调试时遇到了这个问题,详细信息如下: ***[:] Could not save pasteboard named com.apple.UIKit. ...

  6. unimrcp-voice-activity语音检测

    研究 unimrcp有一段时间了,其中unimrcp voice acitve的算法,是遭到大家频繁吐槽.今天我们简单的介绍一下unimrcp voice activity 的这个简单粗暴的算法: u ...

  7. jQuery插件之路(二)——轮播

    还记得以前刚接触前端的时候,浏览各大网站,很多都少不了的有个轮播的效果,那个时候自己是一个彻彻底底的小白,想着这些图片滚动起来还真是有意思,是什么让这些图片在一个方向上连续的滚动呢.后来慢慢的接触多了 ...

  8. CSS3:pointer-events | a标签禁用

    用纯css就能实现取消事件响应的方法,pointer-events,使用起来更加简单,它可以: pointer-events: auto | none | visiblePainted | visib ...

  9. Vue创建项目配置

    前言 安装VS Code,开始vue的学习及编程,但是总是遇到各种各样的错误,控制台语法错误,格式错误.一股脑的袭来,感觉创建个项目怎么这个麻烦.这里就讲一下vue的安装及创建. 安装环境 当然第一步 ...

  10. Zabbix-绘制动态拓扑图基础篇

    一.实验环境 1.1 zabbix 4.0.2 二.实验需求介绍 公司希望网络拓扑能够动态反应物理接口的状态或者业务的状态,希望将网络拓扑显示到大屏上 三.Zabbix在绘制拓扑的优缺点 3.1 优点 ...