File size: 1,298 Bytes
2d1b6e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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}")