Views
No views yet
1# import libraries
2
3import numpy as np
4import torch
5
6from transformers import (
7 AutoTokenizer,
8 BitsAndBytesConfig,
9 TrainingArguments,
10 AutoModelForSequenceClassification
11 )
12
13
14# Load model
15
16model_id = "MVesalA/peft-NER-existenceCLS-HooshvareLab"
17
18tokenizer = AutoTokenizer.from_pretrained(model_id)
19
20bnb_config = BitsAndBytesConfig(
21 load_in_4bit=True, # Enables 4-bit quantization
22 bnb_4bit_use_double_quant=True, # Use double quantization for potentially higher accuracy (optional)
23 bnb_4bit_quant_type="nf4", # Quantization type (specifics depend on hardware and library)
24 bnb_4bit_compute_dtype=torch.bfloat16 # Compute dtype for improved efficiency (optional)
25)
26
27id2label = {0: "NEGATIVE", 1: "POSITIVE"}
28label2id = {"NEGATIVE": 0, "POSITIVE": 1}
29
30model = AutoModelForSequenceClassification.from_pretrained(
31 model_id, # "MVesalA/peft-NER-existenceCLS-HooshvareLab"
32 num_labels=2, # Number of output labels (2 for binary sentiment classification)
33 id2label=id2label, # {0: "NEGATIVE", 1: "POSITIVE"}
34 label2id=label2id, # {"NEGATIVE": 0, "POSITIVE": 1}
35 quantization_config=bnb_config # configuration for quantization
36)
37
38
39# predict entity
40
41def predict(input_text, model=model):
42 """
43 Predicts the sentiment label for a given text input.
44
45 Args:
46 input_text (str): The text to predict the sentiment for.
47
48 Returns:
49 float: The predicted probability of the text being positive sentiment.
50 """
51 inputs = tokenizer(input_text, return_tensors="pt").to("cuda") # Convert to PyTorch tensors and move to GPU (if available)
52 with torch.no_grad():
53 outputs = model(**inputs).logits # Get the model's output logits
54 y_prob = torch.sigmoid(outputs).tolist()[0] # Apply sigmoid activation and convert to list
55 return np.round(y_prob, 5) # Round the predicted probability to 5 decimal places
56
57predict("input_text") # ["Negative_Prob", "Positive_prob"]