Spaces:
No application file
No application file
Create utils.py
Browse files- src/utils.py +27 -0
src/utils.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# src/utils.py
|
| 2 |
+
import seaborn as sns
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import logging
|
| 5 |
+
from transformers import DistilBertForSequenceClassification, DistilBertTokenizer
|
| 6 |
+
|
| 7 |
+
def setup_logging():
|
| 8 |
+
logging.basicConfig(filename="logs/app.log", level=logging.INFO,
|
| 9 |
+
format="%(asctime)s - %(levelname)s - %(message)s")
|
| 10 |
+
|
| 11 |
+
def plot_confusion_matrix(cm, labels, filename="docs/confusion_matrix.png"):
|
| 12 |
+
"""Plot and save confusion matrix."""
|
| 13 |
+
setup_logging()
|
| 14 |
+
plt.figure(figsize=(8, 6))
|
| 15 |
+
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=labels, yticklabels=labels)
|
| 16 |
+
plt.xlabel("Predicted")
|
| 17 |
+
plt.ylabel("True")
|
| 18 |
+
plt.savefig(filename)
|
| 19 |
+
logging.info(f"Confusion matrix saved to {filename}")
|
| 20 |
+
|
| 21 |
+
def load_model_and_tokenizer(model_path):
|
| 22 |
+
"""Load trained DistilBERT model and tokenizer."""
|
| 23 |
+
setup_logging()
|
| 24 |
+
model = DistilBertForSequenceClassification.from_pretrained(model_path)
|
| 25 |
+
tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
|
| 26 |
+
logging.info(f"Model and tokenizer loaded from {model_path}")
|
| 27 |
+
return model, tokenizer
|