Spaces:
Paused
Paused
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| from sklearn.datasets import load_iris | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.ensemble import RandomForestClassifier | |
| from sklearn.metrics import confusion_matrix | |
| import pandas as pd | |
| import platform | |
| import os | |
| print(f"Running on: {platform.node()} ({platform.system()})") | |
| print(f"Working dir: {os.getcwd()}") | |
| # 1. Carica dati | |
| print("Loading Iris dataset...") | |
| iris = load_iris() | |
| X = iris.data | |
| y = iris.target | |
| class_names = iris.target_names | |
| # 2. Train | |
| print("Training Random Forest...") | |
| X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) | |
| clf = RandomForestClassifier(random_state=42) | |
| clf.fit(X_train, y_train) | |
| acc = clf.score(X_test, y_test) | |
| print(f"Accuracy: {acc:.2f}") | |
| # 3. Plot | |
| print("Generating Confusion Matrix plot...") | |
| y_pred = clf.predict(X_test) | |
| cm = confusion_matrix(y_test, y_pred) | |
| plt.figure(figsize=(8, 6)) | |
| sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', | |
| xticklabels=class_names, | |
| yticklabels=class_names) | |
| plt.title(f'Confusion Matrix (Acc: {acc:.2f})') | |
| plt.ylabel('True Label') | |
| plt.xlabel('Predicted Label') | |
| # Salva immagine | |
| filename = "confusion_matrix.png" | |
| plt.savefig(filename) | |
| print(f"Saved: {filename}") | |