深度学习之自然语言处理CBOW预测及模型的保存

news/2025/2/24 0:09:58

自然语言处理CBOW预测及模型的保存

目录

  • 自然语言处理CBOW预测及模型的保存
    • 1 自然语言处理
      • 1.1 概念
      • 1.2 词向量
        • 1.2.1 one-hot编码
        • 1.2.2 词嵌入
        • 1.2.3 常见的词嵌入模型
    • 2 CBOW预测模型搭建
      • 2.1 数据及模型确定
        • 2.1.1 数据
        • 2.1.2 CBOW模型
        • 2.1.3 词嵌入降维
      • 2.2 数据预处理
      • 2.3 模型搭建
      • 2.4 训练、测试模型
      • 2.5 模型保存及词嵌入权重查看

1 自然语言处理


1.1 概念

自然语言处理(Natural Language Processing, NLP)是人工智能和语言学的一个交叉领域,旨在使计算机能够理解、处理和生成人类语言。

1.2 词向量

词向量(Word Embeddings):是自然语言处理(NLP)中的一种技术,将单词映射到高维向量空间,捕捉语义和语法特性,用于将单词表示为实数向量。这些向量在向量空间中具有这样的性质,即语义上相似的单词在向量空间中的距离相近。常见方法包括Word2Vec、GloVe、FastText等。词向量广泛应用于各种NLP任务,如文本分类、机器翻译、情感分析等。

1.2.1 one-hot编码
  • 概念:是一种将类别变量转换为二进制向量的编码方式,其中每个向量只有一个元素为1,其余为0。每个单词表示为一个高维稀疏向量
  • 缺点:维度灾难,无法捕捉单词间的语义关系。
    例如:对于一个包含三个单词的词汇表 [“apple”, “banana”, “cherry”],独热编码可能如下所示:
    • “apple” -> [1, 0, 0]
    • “banana” -> [0, 1, 0]
    • “cherry” -> [0, 0, 1]
1.2.2 词嵌入

词嵌入(Word Embedding)是自然语言处理(NLP)中的一种技术,用于将词汇表示为密集的向量词嵌入是词向量的一种实现方式,但通常词嵌入指的是通过神经网络模型学习到的向量表示,可以将独热编码的单词表示转换为更有意义且维度更低的词嵌入向量,将高维的独热编码向量转换为低维的密集向量,同时保留单词的语义信息。

  • 主要特点:
  1. 密集表示:与one-hot编码不同,词嵌入是低维密集向量,通常维度在几十到几百之间。
  2. 语义信息:相似的单词在嵌入空间中具有相似的向量表示,可以捕捉到单词的语义信息。
  3. 分布式表示:单词的表示分布在整个向量中,每个维度可能代表某种潜在的语义特征。
1.2.3 常见的词嵌入模型
  1. Word2Vec
    • CBOW(Continuous Bag of Words):通过上下文预测中心词。
    • Skip-Gram:通过中心词预测上下文。
  2. GloVe(Global Vectors for Word Representation)
    • 结合了全局矩阵分解和局部上下文窗口的方法,利用共现矩阵来训练词向量。
  3. FastText
    • 扩展了Word2Vec模型,将每个单词表示为组成它的字符n-gram的向量之和。
  4. ELMo(Embeddings from Language Models)
    • 基于预训练的语言模型,为每个单词生成动态的词向量表示。

2 CBOW预测模型搭建


2.1 数据及模型确定

2.1.1 数据

语料库:
We are about to study the idea of a computational process.
Computational processes are abstract beings that inhabit computers.
As they evolve, processes manipulate other abstract things called data.
The evolution of a process is directed by a pattern of rules
called a program. People create programs to direct processes. In effect,
we conjure the spirits of the computer with our spells.

2.1.2 CBOW模型

根据上文2个词汇、下文2个词汇预测中间1个词

2.1.3 词嵌入降维

由于语料库内容较少,所以将独热编码通过词嵌入降维至10维。

2.2 数据预处理

代码展示:

import torch
CONTEXT_SIZE = 2
# 语料库切分为单个词汇
raw_text = """We are about to study the idea of a computational process.
Computational processes are abstract beings that inhabit computers.
As they evolve, processes manipulate other abstract things called data.
The evolution of a process is directed by a pattern of rules
called a program. People create programs to direct processes. In effect,
we conjure the spirits of the computer with our spells.""".split()
# 集合去除重复词汇
vocab = set(raw_text)
# 所有词汇长度
vocab_size = len(vocab)
# 字典,可以根据字典便于后续处理
word_to_idx = {word:i for i,word in enumerate(vocab)}
idx_to_word = {i:word for i,word in enumerate(vocab)}
# 上下文内容和可预测内容,每个元素是一个元组 (context, target)
data = []
for i in range(CONTEXT_SIZE,len(raw_text)-CONTEXT_SIZE):
    context = (
        [raw_text[i - (2- j)] for j in range(CONTEXT_SIZE)]
        + [raw_text[(i+ j + 1)] for j in range(CONTEXT_SIZE)]
    )

    target = raw_text[i]
    data.append((context,target))
# 将上下文中的单词转换为对应的索引,并转为张量返回
def make_context_vector(context,word_to_ix):
    idxs = [word_to_ix[w] for w in context]
    return torch.tensor(idxs,dtype=torch.long)

2.3 模型搭建

class CBOW(nn.Module):
    def __init__(self, vocab_size, embedding_dim):
        super(CBOW, self).__init__()
        # 词嵌入低维密向量
        self.embeddings = nn.Embedding(vocab_size, embedding_dim)
        # 中间隐藏层
        self.proj = nn.Linear(embedding_dim, 128)
        # 输出层
        self.output = nn.Linear(128, vocab_size)
		# 前向传播过程
    def forward(self, inputs):
        embeds = sum(self.embeddings(inputs)).view(1, -1)
        out = F.relu(self.proj(embeds))
        out = self.output(out)
        nll_prob = F.log_softmax(out, -1)
        return nll_prob

2.4 训练、测试模型

代码展示:

import torch
from torch import nn
import torch.nn.functional as F
from tqdm import tqdm

CONTEXT_SIZE = 2
raw_text = """We are about to study the idea of a computational process.
Computational processes are abstract beings that inhabit computers.
As they evolve, processes manipulate other abstract things called data.
The evolution of a process is directed by a pattern of rules
called a program. People create programs to direct processes. In effect,
we conjure the spirits of the computer with our spells.""".split()

vocab = set(raw_text)
vocab_size = len(vocab)
word_to_idx = {word:i for i,word in enumerate(vocab)}
idx_to_word = {i:word for i,word in enumerate(vocab)}

data = []
for i in range(CONTEXT_SIZE,len(raw_text)-CONTEXT_SIZE):
    context = (
        [raw_text[i - (2- j)] for j in range(CONTEXT_SIZE)]
        + [raw_text[(i+ j + 1)] for j in range(CONTEXT_SIZE)]
    )

    target = raw_text[i]
    data.append((context,target))

def make_context_vector(context,word_to_ix):
    idxs = [word_to_ix[w] for w in context]
    return torch.tensor(idxs,dtype=torch.long)

print(make_context_vector(data[0][0],word_to_idx))

class CBOW((nn.Module)):
    def __init__(self,vocab_size,embedding_dim):
        super(CBOW,self).__init__()
        self.embeddings = nn.Embedding(vocab_size,embedding_dim)
        self.proj = nn.Linear(embedding_dim,128)
        self.output = nn.Linear(128,vocab_size)

    def forward(self,inputs):
        embeds = sum(self.embeddings(inputs)).view(1,-1)
        out = F.relu(self.proj(embeds))
        out = self.output(out)
        nll_prob = F.log_softmax(out,-1)
        return nll_prob

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
print(f'Using {device} device')

model = CBOW(vocab_size,10).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

losses = []
loss_function = nn.NLLLoss()
##  进入训练模式
model.train()
for epoch in tqdm(range(200)):
    totall_loss = 0
    for context,target in data:
        context_vector = make_context_vector(context,word_to_idx).to(device)
        target = torch.tensor([word_to_idx[target]]).to(device)
        train_pre = model(context_vector)
        loss = loss_function(train_pre,target)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        totall_loss +=loss.item()
    losses.append(totall_loss)
    # print(losses)

context = ['People','create','to','direct']
context_vector = make_context_vector(context,word_to_idx).to(device)
model.eval()
pre = model(context_vector)
#获取预测结果中概率最大的索引。
max_idx = pre.argmax(1)
print(f'根据上文:{context[0],context[1]}和下文:{context[2],context[3]}预测中间内容:{max_idx}:{idx_to_word[max_idx.item()]}')

运行结果:
在这里插入图片描述
模型预测:上文(‘People’, ‘create’)和下文:(‘to’, ‘direct’)预测中间内容:tensor([28]):programs
实际语料库内容:People create programs to direct

2.5 模型保存及词嵌入权重查看

由于相较于torch,numpy应用范围更广泛,所以将模型保存为numpy的npz格式

# 保存词嵌入权重并转numpy
w = model.embeddings.weight.cpu().detach().numpy()
word2_vec = {}
for word in word_to_idx.keys():
    word2_vec[word] = w[word_to_idx[word],:]
print('结束')
import numpy as np
np.savez('word2vec实现.npz',file_1=w)
data = np.load('word2vec实现.npz')
print(data.files)
print(data[data.files[0]])

调试查看词嵌入权重:
在这里插入图片描述
在这里插入图片描述
运行结果:

在这里插入图片描述


http://www.niftyadmin.cn/n/5863876.html

相关文章

《CentOS 7 镜像源失效终极解决方案(2024年更新)》——生命周期终止后的镜像修复与替代方案

错误信息提示: yum install -y yum-utils \ > device-mapper-persistent-data \ > lvm2 --skip-broken 已加载插件:fastestmirror, langpacks Loading mirror speeds from cached hostfile Could not retrieve mirrorlist http://mirrorlist.cento…

GIS地图、轨道交通与智能驾驶UI设计:未来交通的智能化探索

随着科技的飞速发展,我们正迎来一个高度智能化的未来。在这个时代背景下,GIS(地理信息系统)、轨道交通以及智能驾驶UI设计正逐步成为推动交通行业变革的重要力量。本文将深入探讨这三者之间的内在联系及其在未来交通系统中的应用前…

idea添加web工程

1.idea添加web工程 web工程表示里面既可以写java代码也可以放置页面资源 创建一个项目点击项目,右键——>添加框架支持——>web 1.1 web工程部署到本地的tomcat服务器中 添加配置——>tomcat server[本地]部署启动服务器 localhost本地服务器的地址 80…

【用deepseek和chatgpt做算法竞赛】——还得DeepSeek来 -Minimum Cost Trees_5

往期 【用deepseek和chatgpt做算法竞赛】——华为算法精英实战营第十九期-Minimum Cost Trees_0:介绍了题目和背景【用deepseek和chatgpt做算法竞赛】——华为算法精英实战营第十九期-Minimum Cost Trees_1:题目输入的格式说明,选择了邻接表…

智能自动化新纪元:AI与UiPath RPA的协同应用场景与技术实践

智能自动化新纪元:AI与UiPath RPA的协同应用场景与技术实践 引言 在数字化转型的浪潮中,企业对于自动化技术的需求已从简单的任务执行转向更复杂的智能决策。传统RPA(Robotic Process Automation)通过模拟人类操作处理重复性任务…

Spring的过滤器获取请求体中JSON参数,同时解决Controller获取不到请求体参数的问题。

Spring的过滤器获取请求体中JSON参数,同时解决Controller获取不到请求体参数的问题。 文章目录 前言一、需求场景描述二、原因解析三、自定义 HttpServletRequestWrapper 来保存数据解决Controller获取不到的问题。四、案例(要注意的点) 前言 Spring的过滤器获取请…

STM32的HAL库开发---多通道ADC采集(DMA读取)实验

一、实验介绍 1、功能描述 通过DMA读取数据 通过ADC1通道0/1/2/3/4/5(PA0/1/2/3/4/5)采集测试电压,并显示ADC转换的数字量及换算后的电压值 2、确定最小刻度 VREF 3.3V ---> 0V ≤ VIN ≤ 3.3V --->最小刻度 3.3 / 4096 &#x…

火语言RPA--Excel清空数据

【组件功能】:清空Excel内指定位置的内容 配置预览 配置说明 清空位置 单元格:清空指定单元格内容。 行:清空指定行内容。 列:清空指定列内容。 区域:清空一个区域内容。 行号 支持T或# 行号从1开始。 列名支持T或# 列名从…