NLP(五):BiGRU_Attention的pytorch实现
一、预备知识
1、nn.Embedding
在pytorch里面实现word embedding
是通过一个函数来实现的:nn.Embedding.
# -*- coding: utf-8 -*- import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable word_to_ix = {'hello': 0, 'world': 1} embeds = nn.Embedding(2, 5) hello_idx = torch.LongTensor([word_to_ix['hello']]) hello_idx = Variable(hello_idx) hello_embed = embeds(hello_idx) print(hello_embed)
这就是我们输出的hello这个词的word embedding,代码会输出如下内容,接下来我们解析一下代码:
Variable containing: 0.4606 0.6847 -1.9592 0.9434 0.2316 [torch.FloatTensor of size 1x5]
首先我们需要word_to_ix = {'hello': 0, 'world': 1}
,每个单词我们需要用一个数字去表示他,这样我们需要hello的时候,就用0来表示它。
接着就是word embedding
的定义nn.Embedding(2, 5)
,这里的2表示有2个词,5表示5维度,其实也就是一个2x5的矩阵,所以如果你有1000个词,每个词希望是100维,你就可以这样建立一个word embedding
,nn.Embedding(1000, 100)
。如何访问每一个词的词向量是下面两行的代码,注意这里的词向量的建立只是初始的词向量,并没有经过任何修改优化,我们需要建立神经网络通过learning
的办法修改word embedding
里面的参数使得word embedding
每一个词向量能够表示每一个不同的词。
hello_idx = torch.LongTensor([word_to_ix['hello']]) hello_idx = Variable(hello_idx)
接着这两行代码表示得到一个Variable
,它的值是hello
这个词的index
,也就是0。这里要特别注意一下我们需要Variable,因为我们需要访问nn.Embedding
里面定义的元素,并且word embeding
算是神经网络里面的参数,所以我们需要定义Variable
。
hello_embed = embeds(hello_idx)
这一行表示得到word embedding
里面关于hello
这个词的初始词向量,最后我们就可以print出来。
2、nn.GRU()
这里,嵌入维度50是GRU的input尺寸。
默认:
-
out = [src_len, batch_size, hid_dim * num_directions]
-
hidden = [n_layers * num_directions, batch_size, hid_dim]
如果batch_first=True:
-
out = [ batch_size, src_len,hid_dim * num_directions]
-
hidden = [n_layers * num_directions, batch_size, hid_dim]
>>> import torch.nn as nn >>> gru = nn.GRU(input_size=50, hidden_size=50, batch_first=True) >>> embed = nn.Embedding(3, 50) >>> x = torch.LongTensor([[0, 1, 2]]) >>> x_embed = embed(x) >>> x.size() torch.Size([1, 3]) >>> x_embed.size() torch.Size([1, 3, 50]) >>> out, hidden = gru(x_embed) >>> out.size() torch.Size([1, 3, 50]) >>> hidden.size() torch.Size([1, 1, 50])
>>> x = torch.LongTensor([[0, 1, 2], [0, 1, 2]]) >>> x_embed = embed(x) >>> x_embed.size() torch.Size([2, 3, 50]) >>> out, hidden = gru(x_embed) >>> out.size() torch.Size([2, 3, 50]) >>> hidden.size() torch.Size([1, 2, 50])
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧