Views
No views yet
pip install transformers torch1
2from transformers import BertForSequenceClassification, BertTokenizer
3import torch
4
5# Load quantized model
6quantized_model_path = "AventIQ-AI/sentiment-analysis-for-stock-market-sentiment"
7quantized_model = BertForSequenceClassification.from_pretrained(quantized_model_path)
8quantized_model.eval() # Set to evaluation mode
9quantized_model.half() # Convert model to FP16
10
11# Load tokenizer
12tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
13
14# Define a test sentence
15test_sentence = "Apple Inc. reported stronger-than-expected earnings this quarter, driven by robust iPhone sales and growth in its services segment. Investors reacted positively, pushing the stock up by 3% in after-hours trading. Analysts believe Apple is well-positioned for continued growth, especially with the upcoming product launches.On the other hand, Tesla shares dropped by 5% after the company missed its delivery targets and announced a temporary halt at its Berlin factory due to supply chain issues. Market sentiment remains cautious around Tesla, with concerns about rising competition in the EV space and fluctuating production numbers."
16
17# Tokenize input
18inputs = tokenizer(test_sentence, return_tensors="pt", padding=True, truncation=True, max_length=128)
19
20# Ensure input tensors are in correct dtype
21inputs["input_ids"] = inputs["input_ids"].long() # Convert to long type
22inputs["attention_mask"] = inputs["attention_mask"].long() # Convert to long type
23
24# Make prediction
25with torch.no_grad():
26 outputs = quantized_model(**inputs)
27
28# Get predicted class
29predicted_class = torch.argmax(outputs.logits, dim=1).item()
30print(f"Predicted Class: {predicted_class}")
31
32
33label_mapping = {0: "very_negative", 1: "nagative", 2: "neutral", 3: "Positive", 4: "very_positive"} # Example
34
35predicted_label = label_mapping[predicted_class]
36print(f"Predicted Label: {predicted_label}")
37.
├── model/ # Contains the quantized model files
├── tokenizer_config/ # Tokenizer configuration and vocabulary files
├── model.safensors/ # Fine Tuned Model
├── README.md # Model documentation