NLP基础:NNLM模型代码示例

作者: 三猫后端 | 来源:发表于2022-11-27 18:19 被阅读0次

原文链接:NLP基础:NNLM模型代码示例


导读:在NLP基础:NNLM模型介绍中,已经介绍了NNLM模型原理,通过对网上已发布的代码进行完善并标注,进行模型代码示例展示。

Keras实现

代码主要部分如下:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

from keras.models import Sequential

import numpy as np

import tensorflow as tf

import re

sentences = [ "我渴了", "你真好", "他的错", "对不起" , "他走了"]

# NNLM Parameter

n_step = len(sentences[0])-1 # number of steps ['我 渴', '你 真', '他 的', '对 不', '他 走']

#分字

def seg_char(sent):

    pattern = re.compile(r'([\u4e00-\u9fa5])')

    chars = pattern.split(sent)

    chars =[w for w in chars if len(w.strip()) > 0]

    return chars

#得到每个句子前n-1个词和目标词

chars=np.array([seg_char(i)for i in sentences])

chars=chars.reshape(1,-1)

word_list=np.squeeze(chars)

#['我' '渴' '了' '你' '真' '好' '他' '的' '错' '对' '不' '起' '他' '走' '了']

word_list = list(set(word_list))

word_dict = {w: i for i, w in enumerate(word_list)}

#{'渴': 0, '错': 1, '不': 2, '好': 3, '起': 4, '他': 5, '对': 6, '你': 7, '走': 8, '我': 9, '了': 10, '的': 11, '真': 12}

number_dict = {i: w for i, w in enumerate(word_list)}

#{0: '渴', 1: '错', 2: '不', 3: '好', 4: '起', 5: '他', 6: '对', 7: '你', 8: '走', 9: '我', 10: '了', 11: '的', 12: '真'}

n_class = len(word_dict) # number of Vocabulary

#这里通过one-hot进行词向量生成

#one-hot转换

def make_batch(sentences):

    input_batch = []

    target_batch = []

    for sen in sentences:

        #将每个句子中的字转化为下标表示

        word = seg_char(sen)

        input = [word_dict[n] for n in word[:-1]]

        target = word_dict[word[-1]]

        #one-hot转换

        input_batch.append(np.eye(n_class)[input])

        target_batch.append(np.eye(n_class)[target])

    return input_batch, target_batch

input_batch, target_batch=make_batch(sentences)

input_batch=np.array(input_batch)

#将输入词向量进行首尾拼接

input_batch=input_batch.reshape(-1,n_step*n_class)

target_batch=np.array(target_batch)

target_batch=target_batch.reshape(-1,n_class)

from keras.layers import Dense

import keras

#建立模型,本模型暂不包含直连边

def define_model():

    model = Sequential()

    #Dense为全连接网络

    model.add(Dense(2,activation='tanh',input_shape=(n_step*n_class,))) # 输入层

    model.add(Dense(n_class, activation='softmax'))  # 输出层

    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

    model.summary()

    return model

#训练模型

model=define_model()

model.fit(input_batch, target_batch, epochs=2000)#训练2000轮,数据少啦,一两轮没效果

#预测测试

predict=model.predict(input_batch)

predict=np.argmax(predict,1)#求取最大值索引

print('输入的是:',[seg_char(sen)[:2] for sen in sentences])

print('预测得到:',[number_dict[n] for n in predict])

得到结果如下:

点击原文:NLP基础:NNLM模型代码示例回复“NNLM”可获取全部代码

参考文章:https://blog.csdn.net/kobeyu652

相关文章

  • NLP基础:NNLM模型代码示例

    原文链接:NLP基础:NNLM模型代码示例[https://mp.weixin.qq.com/s?__biz=Mz...

  • NLP - 预训练模型

    早期NLP预训练模型 1. 神经网络语言模型(NNLM) NNLM由Begio在2003年提出发表在JMLR上。神...

  • Blocking IO

    一、阻塞IO模型 二、代码演示 示例1 示例2 三、总结

  • day5-js基础语法

    1.js基础语法 代码示例 2.变量 代码示例 3.运算符 代码示例 4.分支结构 代码示例 5.循环结构 代码示...

  • Function.prototype.bind 规范笔记

    示例代码 以上述代码为示例,boundFunc 和 targetFunc 的关系: 基础 调用 boundFunc...

  • MATLAB脚本批量设置模型运行参数

    设置模型配置参数 示例代码如下: attachConfigSet attachConfigSet为指定模型添加配置...

  • 算法(第四版)第一章

    看了半天书,看的是算法第一章内容(基础编程模型),如下所示,代码示例稍后会整理发到github

  • NLP基础

    NLP基础 NLP涉及知识 NLTK库 分词 TF-IDF 手动操作安装NLTK库 代码小练 什么是NLP 词处理...

  • css 书写规范

    css书写顺序规范定位、盒模型、颜色、文本、其他 示例代码

  • Go 语言程序设计(3)

    stacker.go 示例代码: stack.go 示例代码: 知识点: go 内置基础类型:布尔类型: bool...

网友评论

    本文标题:NLP基础:NNLM模型代码示例

    本文链接:https://www.haomeiwen.com/subject/jomcfdtx.html