Upload neat\visualization.py with huggingface_hub
Browse files- neat//visualization.py +183 -0
neat//visualization.py
ADDED
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Visualization utilities for NEAT networks."""
|
2 |
+
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import networkx as nx
|
5 |
+
import numpy as np
|
6 |
+
import jax.numpy as jnp
|
7 |
+
from typing import List, Dict, Any
|
8 |
+
from .network import Network
|
9 |
+
|
10 |
+
def plot_network_structure(network: Network, title: str = "Network Structure",
|
11 |
+
save_path: str = None, show: bool = True) -> None:
|
12 |
+
"""Plot network structure using networkx.
|
13 |
+
|
14 |
+
Args:
|
15 |
+
network: Network to visualize
|
16 |
+
title: Plot title
|
17 |
+
save_path: Path to save plot to
|
18 |
+
show: Whether to display plot
|
19 |
+
"""
|
20 |
+
# Create graph
|
21 |
+
G = nx.DiGraph()
|
22 |
+
|
23 |
+
# Add nodes
|
24 |
+
input_nodes = network.get_input_nodes()
|
25 |
+
hidden_nodes = network.get_hidden_nodes()
|
26 |
+
output_nodes = network.get_output_nodes()
|
27 |
+
|
28 |
+
# Position nodes in layers
|
29 |
+
pos = {}
|
30 |
+
|
31 |
+
# Input layer
|
32 |
+
for i, node in enumerate(input_nodes):
|
33 |
+
G.add_node(node, layer='input')
|
34 |
+
pos[node] = (0, (i - len(input_nodes)/2) / max(1, len(input_nodes)-1))
|
35 |
+
|
36 |
+
# Hidden layer
|
37 |
+
for i, node in enumerate(hidden_nodes):
|
38 |
+
G.add_node(node, layer='hidden')
|
39 |
+
pos[node] = (1, (i - len(hidden_nodes)/2) / max(1, len(hidden_nodes)-1))
|
40 |
+
|
41 |
+
# Output layer
|
42 |
+
for i, node in enumerate(output_nodes):
|
43 |
+
G.add_node(node, layer='output')
|
44 |
+
pos[node] = (2, (i - len(output_nodes)/2) / max(1, len(output_nodes)-1))
|
45 |
+
|
46 |
+
# Add edges with weights
|
47 |
+
connections = network.get_connections()
|
48 |
+
for src, dst, weight in connections:
|
49 |
+
# Convert JAX array to NumPy float
|
50 |
+
if isinstance(weight, jnp.ndarray):
|
51 |
+
weight = float(weight)
|
52 |
+
G.add_edge(src, dst, weight=weight)
|
53 |
+
|
54 |
+
# Draw network
|
55 |
+
plt.figure(figsize=(8, 6))
|
56 |
+
|
57 |
+
# Draw nodes
|
58 |
+
node_colors = ['lightblue' if G.nodes[n]['layer'] == 'input' else
|
59 |
+
'lightgreen' if G.nodes[n]['layer'] == 'hidden' else
|
60 |
+
'salmon' for n in G.nodes()]
|
61 |
+
nx.draw_networkx_nodes(G, pos, node_color=node_colors)
|
62 |
+
|
63 |
+
# Draw edges with weights as colors
|
64 |
+
edges = G.edges()
|
65 |
+
weights = [G[u][v]['weight'] for u, v in edges]
|
66 |
+
|
67 |
+
# Normalize weights for coloring
|
68 |
+
max_weight = max(abs(min(weights)), abs(max(weights)))
|
69 |
+
if max_weight > 0:
|
70 |
+
norm_weights = [(w + max_weight)/(2*max_weight) for w in weights]
|
71 |
+
else:
|
72 |
+
norm_weights = [0.5] * len(weights) # Default to middle color if all weights are 0
|
73 |
+
|
74 |
+
nx.draw_networkx_edges(G, pos, edge_color=norm_weights,
|
75 |
+
edge_cmap=plt.cm.RdYlBu, width=2)
|
76 |
+
|
77 |
+
# Add labels
|
78 |
+
labels = {n: str(n) for n in G.nodes()}
|
79 |
+
nx.draw_networkx_labels(G, pos, labels)
|
80 |
+
|
81 |
+
plt.title(title)
|
82 |
+
plt.axis('off')
|
83 |
+
|
84 |
+
if save_path:
|
85 |
+
plt.savefig(save_path)
|
86 |
+
|
87 |
+
if show:
|
88 |
+
plt.show()
|
89 |
+
else:
|
90 |
+
plt.close()
|
91 |
+
|
92 |
+
def plot_decision_boundary(network: Network, X: np.ndarray, y: np.ndarray,
|
93 |
+
title: str = "Decision Boundary",
|
94 |
+
save_path: str = None, show: bool = True) -> None:
|
95 |
+
"""Plot decision boundary for 2D classification problem.
|
96 |
+
|
97 |
+
Args:
|
98 |
+
network: Trained network
|
99 |
+
X: Input data (n_samples, 2)
|
100 |
+
y: Labels
|
101 |
+
title: Plot title
|
102 |
+
save_path: Path to save plot to
|
103 |
+
show: Whether to display plot
|
104 |
+
"""
|
105 |
+
# Convert JAX arrays to NumPy
|
106 |
+
if isinstance(X, jnp.ndarray):
|
107 |
+
X = np.array(X)
|
108 |
+
if isinstance(y, jnp.ndarray):
|
109 |
+
y = np.array(y)
|
110 |
+
|
111 |
+
# Create mesh grid
|
112 |
+
h = 0.02 # Step size
|
113 |
+
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
|
114 |
+
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
|
115 |
+
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
|
116 |
+
np.arange(y_min, y_max, h))
|
117 |
+
|
118 |
+
# Make predictions on mesh
|
119 |
+
mesh_points = np.c_[xx.ravel(), yy.ravel()]
|
120 |
+
Z = network.predict(mesh_points)
|
121 |
+
if isinstance(Z, jnp.ndarray):
|
122 |
+
Z = np.array(Z)
|
123 |
+
Z = Z.reshape(xx.shape)
|
124 |
+
|
125 |
+
# Plot decision boundary
|
126 |
+
plt.figure(figsize=(8, 6))
|
127 |
+
plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu_r, alpha=0.3)
|
128 |
+
|
129 |
+
# Plot training points
|
130 |
+
plt.scatter(X[:, 0], X[:, 1], c=y,
|
131 |
+
cmap=plt.cm.RdYlBu_r,
|
132 |
+
alpha=0.6,
|
133 |
+
edgecolors='gray')
|
134 |
+
plt.xlim(xx.min(), xx.max())
|
135 |
+
plt.ylim(yy.min(), yy.max())
|
136 |
+
|
137 |
+
plt.title(title)
|
138 |
+
|
139 |
+
if save_path:
|
140 |
+
plt.savefig(save_path)
|
141 |
+
|
142 |
+
if show:
|
143 |
+
plt.show()
|
144 |
+
else:
|
145 |
+
plt.close()
|
146 |
+
|
147 |
+
def plot_training_history(history: Dict[str, List[float]],
|
148 |
+
title: str = "Training History",
|
149 |
+
save_path: str = None, show: bool = True) -> None:
|
150 |
+
"""Plot training history metrics.
|
151 |
+
|
152 |
+
Args:
|
153 |
+
history: Dictionary of metrics
|
154 |
+
title: Plot title
|
155 |
+
save_path: Path to save plot to
|
156 |
+
show: Whether to display plot
|
157 |
+
"""
|
158 |
+
plt.figure(figsize=(10, 6))
|
159 |
+
|
160 |
+
# Convert JAX arrays to NumPy if needed
|
161 |
+
plot_history = {}
|
162 |
+
for metric, values in history.items():
|
163 |
+
if isinstance(values[0], jnp.ndarray):
|
164 |
+
plot_history[metric] = [float(v) for v in values]
|
165 |
+
else:
|
166 |
+
plot_history[metric] = values
|
167 |
+
|
168 |
+
for metric, values in plot_history.items():
|
169 |
+
plt.plot(values, label=metric)
|
170 |
+
|
171 |
+
plt.title(title)
|
172 |
+
plt.xlabel('Generation')
|
173 |
+
plt.ylabel('Value')
|
174 |
+
plt.legend()
|
175 |
+
plt.grid(True)
|
176 |
+
|
177 |
+
if save_path:
|
178 |
+
plt.savefig(save_path)
|
179 |
+
|
180 |
+
if show:
|
181 |
+
plt.show()
|
182 |
+
else:
|
183 |
+
plt.close()
|