Spaces:
Running
Running
Commit
·
379ec43
1
Parent(s):
2971e95
started coding the transcript analysis and survey prediction code
Browse filesWe are using BERT a pre trained transformer model and a regression layer to predict the survey responses as a numerical value for each question in the survey set.
- transcriptanalysis.py +103 -0
transcriptanalysis.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch.utils.data import Dataset, DataLoader
|
3 |
+
from transformers import BertTokenizer, BertForSequenceClassification, AdamW, get_linear_schedule_with_warmup
|
4 |
+
from sklearn.model_selection import train_test_split
|
5 |
+
from sklearn.metrics import mean_squared_error, r2_score
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
# Load the dataset
|
9 |
+
chat_transcripts = ["chat transcript 1", "chat transcript 2", ...]
|
10 |
+
survey_responses = [3.5, 4.2, ...] # Numerical survey responses
|
11 |
+
|
12 |
+
# Split the data into training, validation, and testing sets
|
13 |
+
train_texts, temp_texts, train_labels, temp_labels = train_test_split(chat_transcripts, survey_responses, test_size=0.3, random_state=42)
|
14 |
+
val_texts, test_texts, val_labels, test_labels = train_test_split(temp_texts, temp_labels, test_size=0.5, random_state=42)
|
15 |
+
|
16 |
+
# Pre-process the data using BERT tokenizer
|
17 |
+
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
|
18 |
+
train_encodings = tokenizer(train_texts, truncation=True, padding=True)
|
19 |
+
val_encodings = tokenizer(val_texts, truncation=True, padding=True)
|
20 |
+
test_encodings = tokenizer(test_texts, truncation=True, padding=True)
|
21 |
+
|
22 |
+
class SurveyDataset(Dataset):
|
23 |
+
def __init__(self, encodings, labels):
|
24 |
+
self.encodings = encodings
|
25 |
+
self.labels = labels
|
26 |
+
|
27 |
+
def __getitem__(self, idx):
|
28 |
+
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
|
29 |
+
item['labels'] = torch.tensor(self.labels[idx], dtype=torch.float)
|
30 |
+
return item
|
31 |
+
|
32 |
+
def __len__(self):
|
33 |
+
return len(self.labels)
|
34 |
+
|
35 |
+
train_dataset = SurveyDataset(train_encodings, train_labels)
|
36 |
+
val_dataset = SurveyDataset(val_encodings, val_labels)
|
37 |
+
test_dataset = SurveyDataset(test_encodings, test_labels)
|
38 |
+
|
39 |
+
# Fine-tune the BERT model
|
40 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
41 |
+
model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=1).to(device)
|
42 |
+
|
43 |
+
train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True)
|
44 |
+
val_loader = DataLoader(val_dataset, batch_size=8, shuffle=False)
|
45 |
+
test_loader = DataLoader(test_dataset, batch_size=8, shuffle=False)
|
46 |
+
|
47 |
+
optim = AdamW(model.parameters(), lr=2e-5)
|
48 |
+
num_epochs = 3
|
49 |
+
num_training_steps = num_epochs * len(train_loader)
|
50 |
+
lr_scheduler = get_linear_schedule_with_warmup(optim, num_warmup_steps=0, num_training_steps=num_training_steps)
|
51 |
+
|
52 |
+
for epoch in range(num_epochs):
|
53 |
+
model.train()
|
54 |
+
for batch in train_loader:
|
55 |
+
optim.zero_grad()
|
56 |
+
input_ids = batch["input_ids"].to(device)
|
57 |
+
attention_mask = batch["attention_mask"].to(device)
|
58 |
+
labels = batch["labels"].unsqueeze(1).to(device)
|
59 |
+
outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
|
60 |
+
loss = outputs.loss
|
61 |
+
loss.backward()
|
62 |
+
optim.step()
|
63 |
+
lr_scheduler.step()
|
64 |
+
|
65 |
+
# Evaluate the model
|
66 |
+
model.eval()
|
67 |
+
preds = []
|
68 |
+
with torch.no_grad():
|
69 |
+
for batch in test_loader:
|
70 |
+
input_ids = batch["input_ids"].to(device)
|
71 |
+
attention_mask = batch["attention_mask"].to(device)
|
72 |
+
outputs = model(input_ids, attention_mask=attention_mask)
|
73 |
+
logits = outputs.logits
|
74 |
+
preds.extend(logits.squeeze().tolist())
|
75 |
+
|
76 |
+
mse = mean_squared_error(test_labels, preds)
|
77 |
+
r2 = r2_score(test_labels, preds)
|
78 |
+
|
79 |
+
print("Mean Squared Error:", mse)
|
80 |
+
print("R-squared Score:", r2)
|
81 |
+
|
82 |
+
def predict_survey_response(chat_transcript, model, tokenizer, device):
|
83 |
+
# Preprocess the chat transcript
|
84 |
+
encoding = tokenizer(chat_transcript, truncation=True, padding=True, return_tensors="pt")
|
85 |
+
|
86 |
+
# Move tensors to the device
|
87 |
+
input_ids = encoding["input_ids"].to(device)
|
88 |
+
attention_mask = encoding["attention_mask"].to(device)
|
89 |
+
|
90 |
+
# Predict the survey response using the fine-tuned model
|
91 |
+
model.eval()
|
92 |
+
with torch.no_grad():
|
93 |
+
outputs = model(input_ids, attention_mask=attention_mask)
|
94 |
+
logits = outputs.logits
|
95 |
+
predicted_response = logits.squeeze().item()
|
96 |
+
|
97 |
+
return predicted_response
|
98 |
+
|
99 |
+
# Example usage
|
100 |
+
new_chat_transcript = "A new chat transcript"
|
101 |
+
predicted_response = predict_survey_response(new_chat_transcript, model, tokenizer, device)
|
102 |
+
print("Predicted survey response:", predicted_response)
|
103 |
+
|