1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
| import torch import torch.nn as nn import torch.optim as optim import pandas as pd from collections import Counter from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
train = pd.read_csv("train.tsv", sep='\t') train['tokens'] = train['Phrase'].str.lower().str.split()
all_words = [word for tokens in train['tokens'] for word in tokens] vocab = {word: i+1 for i, (word, _) in enumerate(Counter(all_words).most_common())} vocab_size = len(vocab) + 1
def text_to_sequence(tokens, vocab): return [vocab.get(token, 0) for token in tokens]
sequences = [] lengths = [] y_list = []
for i, tokens in enumerate(train['tokens']): seq = torch.tensor(text_to_sequence(tokens, vocab), dtype=torch.long) if len(seq) > 0: sequences.append(seq) lengths.append(len(seq)) y_list.append(train['Sentiment'][i])
X_padded = pad_sequence(sequences, batch_first=True, padding_value=0) lengths = torch.tensor(lengths) y = torch.tensor(y_list)
class TextLSTM(nn.Module): def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes): super(TextLSTM, self).__init__() self.embedding = nn.Embedding(vocab_size, embed_dim) self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True) self.fc = nn.Linear(hidden_dim, num_classes)
def forward(self, x, lengths): embed = self.embedding(x)
packed = pack_padded_sequence(embed, lengths.cpu(), batch_first=True, enforce_sorted=False) packed_out, (h_n, c_n) = self.lstm(packed)
out = self.fc(h_n[-1]) return out
embed_dim = 50 hidden_dim = 100 num_classes = 5 model = TextLSTM(vocab_size, embed_dim, hidden_dim, num_classes)
criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001)
batch_size = 64 num_epochs = 30
for epoch in range(num_epochs): permutation = torch.randperm(X_padded.size(0)) epoch_loss = 0
for i in range(0, X_padded.size(0), batch_size): indices = permutation[i:i+batch_size] batch_x = X_padded[indices] batch_y = y[indices] batch_lengths = lengths[indices]
optimizer.zero_grad() outputs = model(batch_x, batch_lengths) loss = criterion(outputs, batch_y) loss.backward() optimizer.step()
epoch_loss += loss.item()
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}")
test = pd.read_csv("test.tsv", sep='\t') test['tokens'] = test['Phrase'].str.lower().str.split() test_sequences = [torch.tensor(text_to_sequence(tokens, vocab), dtype=torch.long) for tokens in test['tokens']] test_lengths = torch.tensor([len(seq) for seq in test_sequences]) X_test_padded = pad_sequence(test_sequences, batch_first=True, padding_value=0)
test_sequences = [] test_lengths = [] test_indices = []
for i, tokens in enumerate(test['tokens']): seq = torch.tensor(text_to_sequence(tokens, vocab), dtype=torch.long) if len(seq) > 0: test_sequences.append(seq) test_lengths.append(len(seq)) test_indices.append(i)
X_test_padded = pad_sequence(test_sequences, batch_first=True, padding_value=0) test_lengths = torch.tensor(test_lengths)
model.eval() with torch.no_grad(): outputs = model(X_test_padded, test_lengths) predictions = torch.argmax(outputs, dim=1)
all_predictions = torch.zeros(len(test), dtype=torch.long) for idx, pred in zip(test_indices, predictions): all_predictions[idx] = pred
submission = pd.DataFrame({ "PhraseId": test["PhraseId"], "Sentiment": all_predictions.numpy() }) submission.to_csv("submission_lstm.csv", index=False) print("结束")
|