Views
No views yet
1import torch
2from transformers import BertTokenizer, BertForSequenceClassification
3import pickle
4import os
5
6# Get the current directory of the script
7current_directory = os.path.dirname(os.path.abspath(__file__))
8# Define the relative path to the saved model
9pkl_path = os.path.join(current_directory, 'label_encoder.pkl')
10
11# Load the model using the relative path
12model = BertForSequenceClassification.from_pretrained(current_directory)
13tokenizer = BertTokenizer.from_pretrained(current_directory)
14
15# Load the label encoder
16with open(pkl_path, 'rb') as le_file:
17 le = pickle.load(le_file)
18
19def predict_phase(query_description):
20 # Tokenize the input description
21 inputs = tokenizer(query_description, return_tensors='pt', truncation=True, padding=True)
22
23 # Get the model's predictions
24 with torch.no_grad():
25 logits = model(**inputs).logits
26
27 # Convert logits to probabilities
28 probs = logits.softmax(dim=1)
29
30 # Get the predicted label and confidence
31 predicted_class = torch.argmax(probs, dim=1).item()
32 confidence = probs[0][predicted_class].item()
33 round_confidence = round(float(confidence),2)
34 label = le.inverse_transform([predicted_class])[0]
35
36 return label, round_confidence, "Bert-2023-10"
37