task03:Faster 情感分析
一、数据预处理:
-
FastText分类模型:
-
其他文本分类模型最大的不同之处在于其计算了输入句子的n-gram
- n-gram: 将文本里面的内容按照字节进行大小为n的滑动窗口操作,形成了长度是n的字节片段序列,其中每一个字节片段称为gram
-
将n-gram作为一种附加特征来获取局部词序特征信息添加至标记化列表的末尾
-
TorchText ‘Field’ 中有一个
preprocessing
参数TEXT = data.Field(tokenize = 'spacy', tokenizer_language = 'en_core_web_sm', preprocessing = generate_bigrams)
-
构建vocab并加载预训练好的此嵌入:
MAX_VOCAB_SIZE = 25_000 TEXT.build_vocab(train_data, max_size = MAX_VOCAB_SIZE, vectors = "glove.6B.100d", unk_init = torch.Tensor.normal_) LABEL.build_vocab(train_data)
-
创建迭代器:
BATCH_SIZE = 64 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits( (train_data, valid_data, test_data), batch_size = BATCH_SIZE, device = device)
-
二、构建模型:
-
FastText:
- 通过将Embedding层单词映射到稠密空间,然后将句子中所有单词在Embedding空间中进行平均,进而完成分类。所以这个模型参数量相较于上一章中的模型会减少很多。
-
创建FastText类实例:
-
查看模型中的参数数量:
def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print(f'The model has {count_parameters(model):,} trainable parameters')
-
预训练好的向量复制到嵌入层:
pretrained_embeddings = TEXT.vocab.vectors model.embedding.weight.data.copy_(pretrained_embeddings)
-
将未知tokens和填充tokens的初始权重归零:
UNK_IDX = TEXT.vocab.stoi[TEXT.unk_token] model.embedding.weight.data[UNK_IDX] = torch.zeros(EMBEDDING_DIM) model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM)
三、训练模型:
四、验证模型:
import spacy
nlp = spacy.load('en_core_web_sm')
def predict_sentiment(model, sentence):
model.eval()
tokenized = generate_bigrams([tok.text for tok in nlp.tokenizer(sentence)])
indexed = [TEXT.vocab.stoi[t] for t in tokenized]
tensor = torch.LongTensor(indexed).to(device)
tensor = tensor.unsqueeze(1)
prediction = torch.sigmoid(model(tensor))
return prediction.item()
predict_sentiment(model, "This film is terrible")
predict_sentiment(model, "This film is great")