transformer 文本二分类
时间: 2023-12-20 22:32:39 浏览: 87
Transformer是一种用于自然语言处理任务的深度学习模型,它在文本分类任务中表现出色。下面是使用Transformer进行文本二分类的示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.data import Field, TabularDataset, BucketIterator
from torch.nn import TransformerEncoder, TransformerEncoderLayer
# 定义模型
class TransformerClassifier(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, n_layers, n_heads, dropout):
super().__init__()
self.embedding = nn.Embedding(input_dim, hidden_dim)
self.encoder_layer = TransformerEncoderLayer(hidden_dim, n_heads, hidden_dim, dropout)
self.encoder = TransformerEncoder(self.encoder_layer, n_layers)
self.fc = nn.Linear(hidden_dim, output_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, text):
embedded = self.embedding(text)
embedded = embedded.permute(1, 0, 2)
output = self.encoder(embedded)
output = output.permute(1, 0, 2)
pooled = torch.mean(output, dim=1)
pooled = self.dropout(pooled)
return self.fc(pooled)
# 数据预处理
TEXT = Field(tokenize='spacy', lower=True)
LABEL = Field(sequential=False, is_target=True)
fields = [('text', TEXT), ('label', LABEL)]
train_data, test_data = TabularDataset.splits(
path='data',
train='train.csv',
test='test.csv',
format='csv',
fields=fields,
skip_header=True
)
TEXT.build_vocab(train_data, min_freq=2)
LABEL.build_vocab(train_data)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_iterator, test_iterator = BucketIterator.splits(
(train_data, test_data),
batch_size=64,
device=device
)
# 模型训练
input_dim = len(TEXT.vocab)
output_dim = 2
hidden_dim = 256
n_layers = 2
n_heads = 8
dropout = 0.2
model = TransformerClassifier(input_dim, hidden_dim, output_dim, n_layers, n_heads, dropout).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
def train(model, iterator, optimizer, criterion):
model.train()
epoch_loss = 0
epoch_acc = 0
for batch in iterator:
optimizer.zero_grad()
text = batch.text
label = batch.label
predictions = model(text).squeeze(1)
loss = criterion(predictions, label)
acc = binary_accuracy(predictions, label)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
def evaluate(model, iterator, criterion):
model.eval()
epoch_loss = 0
epoch_acc = 0
with torch.no_grad():
for batch in iterator:
text = batch.text
label = batch.label
predictions = model(text).squeeze(1)
loss = criterion(predictions, label)
acc = binary_accuracy(predictions, label)
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator)
def binary_accuracy(preds, y):
rounded_preds = torch.round(torch.sigmoid(preds))
correct = (rounded_preds == y).float()
acc = correct.sum() / len(correct)
return acc
N_EPOCHS = 10
best_valid_loss = float('inf')
for epoch in range(N_EPOCHS):
train_loss, train_acc = train(model, train_iterator, optimizer, criterion)
valid_loss, valid_acc = evaluate(model, test_iterator, criterion)
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict(), 'transformer_model.pt')
print(f'Epoch: {epoch+1:02} | Train Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}% | Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc*100:.2f}%')
# 加载模型并进行预测
model.load_state_dict(torch.load('transformer_model.pt'))
def predict_sentiment(model, sentence):
model.eval()
tokenized = [tok.text for tok in spacy_en.tokenizer(sentence)]
indexed = [TEXT.vocab.stoi[t] for t in tokenized]
tensor = torch.LongTensor(indexed).unsqueeze(1).to(device)
prediction = torch.sigmoid(model(tensor))
return prediction.item()
# 示例预测
sentence = "This movie is great!"
prediction = predict_sentiment(model, sentence)
print(f'Sentence: {sentence} | Prediction: {prediction:.4f}')
```
请注意,上述代码中的数据集是使用torchtext库加载的csv文件,其中包含两列:text和label。你需要将你的文本数据准备成类似的格式,并将其保存为train.csv和test.csv文件。
阅读全文