Views
No views yet
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
# Load model and tokenizer
model_path = "KevSun/climate-attitude-LM" # Ensure this path points to the correct directory
model = AutoModelForSequenceClassification.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(model_path)
# Define the path to your text file
file_path = 'yourtext.txt'
# Read the content of the file
with open(file_path, 'r', encoding='utf-8') as file:
new_text = file.read()
# Encode the text using the tokenizer used during training
encoded_input = tokenizer(new_text, return_tensors='pt', padding=True, truncation=True, max_length=64)
# Move the model to the correct device (CPU or GPU if available)
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device) # Move model to the correct device
encoded_input = {k: v.to(device) for k, v in encoded_input.items()} # Move tensor to the correct device
model.eval() # Set the model to evaluation mode
# Perform the prediction
with torch.no_grad():
outputs = model(**encoded_input)
# Get the predictions (assumes classification with labels)
predictions = outputs.logits.squeeze()
# Assuming softmax is needed to interpret the logits as probabilities
probabilities = torch.softmax(predictions, dim=0)
# Define labels for each class index based on your classification categories
labels = ["risk", "neutral", "opportunity"]
predicted_index = torch.argmax(probabilities).item() # Get the index of the max probability
predicted_label = labels[predicted_index]
predicted_probability = probabilities[predicted_index].item()
# Print the predicted label and its probability
print(f"Predicted Label: {predicted_label}, Probability: {predicted_probability:.4f}")
##the output example: predicted Label: neutral, Probability: 0.8377