【Pytorch】LSTM在自然语言处理中的应用

以词性标注为例

# 输入数据封装成Variable
def prepare_sequence(seq, to_ix):
	idxs = [to_ix[w] for w in seq]
	tensor = torch.LongTensor(idxs)
	return autograd.Variable(tensor)

# 输入数据格式,单个的词和对应的词性
training_data = [
	("The dog ate the apple".split(), ["DET", "NN", "V", "DET", "NN"]),
	("everybody read that book".split(), ["NN", "V", "DET", "NN"])]

word_to_ix = {}
for sent, tags in training_data:
	for word in sent:
		if word not in word_to_ix:
			word_to_ix[word] = len(word_to_ix)

tag_to_ix = {"DET":0, "NN":1, "V":2}
EMBEDDING_DIM=64
HIDDEN_DIM=6

# 模型的定义
class LSTMTagger:
	def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size):
		super(LSTMTagger, self).__init__()
		self.hidden_dim = hidden_dim
		self.word_embedding = nn.Embedding(vocab_size, embedding_dim)
		self.lstm = nn.LSTM(embedding_dim, hidden_dim)
	
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值