utils.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. from torchtext.vocab import build_vocab_from_iterator
  2. import torch
  3. from torch.nn.utils.rnn import pad_sequence
  4. #实现build_vocab函数,基于dataset,建立词汇表
  5. def build_vocab(dataset):
  6. #unk表示未知词,pad表示填充词
  7. special=['<unk>','<pad>']
  8. text_iter=map(lambda x:x[0] , dataset)#文本序列
  9. #建立文本词汇表text_vocab
  10. #将min_freq设置为2,也就是至少出现两次的单词,才会添加到词表中
  11. text_vocab = build_vocab_from_iterator(text_iter,min_freq=2,specials=special)
  12. #将unk对应的索引,设置为默认索引
  13. text_vocab.set_default_index(text_vocab['<unk>'])
  14. return text_vocab
  15. #整个collate_batch函数是批量读取文本数据时的回调函数
  16. def collate_batch(batch,text_vocab):
  17. text_list=list()
  18. labels=list()
  19. #每次读取一组数据
  20. for text,label in batch:
  21. text_tokens = [text_vocab[token] for token in text]
  22. text_tensor=torch.tensor(text_tokens,dtype=torch.long)
  23. text_list.append(text_tensor)
  24. labels.append(torch.tensor(label - 1,dtype=torch.long))
  25. padding_idx = text_vocab["<pad>"]
  26. #将batch填充为相同长度文本
  27. text_padded = pad_sequence(text_list,batch_first=True,padding_value=padding_idx)
  28. #一次性堆叠成批次 形状: (N, 3)
  29. labels_tensor=torch.stack(labels)
  30. #返回文本和标签的张量形式,用于后续的模型训练
  31. return text_padded,labels_tensor