pyerualjetwork 4.3.8.dev14__py3-none-any.whl → 4.3.9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyerualjetwork/__init__.py +1 -1
- pyerualjetwork/activation_functions.py +2 -2
- pyerualjetwork/activation_functions_cuda.py +63 -114
- pyerualjetwork/data_operations_cuda.py +1 -1
- pyerualjetwork/fitness_functions.py +72 -0
- pyerualjetwork/fitness_functions_cuda.py +85 -0
- pyerualjetwork/model_operations.py +14 -14
- pyerualjetwork/model_operations_cuda.py +16 -17
- pyerualjetwork/plan.py +159 -382
- pyerualjetwork/plan_cuda.py +149 -387
- pyerualjetwork/planeat.py +24 -54
- pyerualjetwork/planeat_cuda.py +11 -47
- pyerualjetwork/visualizations.py +33 -30
- pyerualjetwork/visualizations_cuda.py +22 -24
- {pyerualjetwork-4.3.8.dev14.dist-info → pyerualjetwork-4.3.9.dist-info}/METADATA +3 -19
- pyerualjetwork-4.3.9.dist-info/RECORD +24 -0
- pyerualjetwork-4.3.9.dist-info/top_level.txt +1 -0
- pyerualjetwork/loss_functions.py +0 -21
- pyerualjetwork/loss_functions_cuda.py +0 -21
- pyerualjetwork-4.3.8.dev14.dist-info/RECORD +0 -44
- pyerualjetwork-4.3.8.dev14.dist-info/top_level.txt +0 -2
- pyerualjetwork_afterburner/__init__.py +0 -11
- pyerualjetwork_afterburner/activation_functions.py +0 -290
- pyerualjetwork_afterburner/activation_functions_cuda.py +0 -289
- pyerualjetwork_afterburner/data_operations.py +0 -406
- pyerualjetwork_afterburner/data_operations_cuda.py +0 -461
- pyerualjetwork_afterburner/help.py +0 -17
- pyerualjetwork_afterburner/loss_functions.py +0 -21
- pyerualjetwork_afterburner/loss_functions_cuda.py +0 -21
- pyerualjetwork_afterburner/memory_operations.py +0 -298
- pyerualjetwork_afterburner/metrics.py +0 -190
- pyerualjetwork_afterburner/metrics_cuda.py +0 -163
- pyerualjetwork_afterburner/model_operations.py +0 -408
- pyerualjetwork_afterburner/model_operations_cuda.py +0 -420
- pyerualjetwork_afterburner/plan.py +0 -432
- pyerualjetwork_afterburner/plan_cuda.py +0 -441
- pyerualjetwork_afterburner/planeat.py +0 -793
- pyerualjetwork_afterburner/planeat_cuda.py +0 -840
- pyerualjetwork_afterburner/ui.py +0 -22
- pyerualjetwork_afterburner/visualizations.py +0 -823
- pyerualjetwork_afterburner/visualizations_cuda.py +0 -825
- {pyerualjetwork-4.3.8.dev14.dist-info → pyerualjetwork-4.3.9.dist-info}/WHEEL +0 -0
@@ -1,825 +0,0 @@
|
|
1
|
-
import networkx as nx
|
2
|
-
import matplotlib.pyplot as plt
|
3
|
-
import cupy as cp
|
4
|
-
from scipy.spatial import ConvexHull
|
5
|
-
import seaborn as sns
|
6
|
-
from matplotlib.animation import ArtistAnimation
|
7
|
-
|
8
|
-
def draw_neural_web(W, ax, G, return_objs=False):
|
9
|
-
"""
|
10
|
-
Visualizes a neural web by drawing the neural network structure.
|
11
|
-
|
12
|
-
Parameters:
|
13
|
-
W : numpy.ndarray
|
14
|
-
A 2D array representing the connection weights of the neural network.
|
15
|
-
ax : matplotlib.axes.Axes
|
16
|
-
The matplotlib axes where the graph will be drawn.
|
17
|
-
G : networkx.Graph
|
18
|
-
The NetworkX graph representing the neural network structure.
|
19
|
-
return_objs : bool, optional
|
20
|
-
If True, returns the drawn objects (nodes and edges). Default is False.
|
21
|
-
|
22
|
-
Returns:
|
23
|
-
art1 : matplotlib.collections.PathCollection or None
|
24
|
-
Returns the node collection if return_objs is True; otherwise, returns None.
|
25
|
-
art2 : matplotlib.collections.LineCollection or None
|
26
|
-
Returns the edge collection if return_objs is True; otherwise, returns None.
|
27
|
-
art3 : matplotlib.collections.TextCollection or None
|
28
|
-
Returns the label collection if return_objs is True; otherwise, returns None.
|
29
|
-
|
30
|
-
Example:
|
31
|
-
art1, art2, art3 = draw_neural_web(W, ax, G, return_objs=True)
|
32
|
-
plt.show()
|
33
|
-
"""
|
34
|
-
W = W.get()
|
35
|
-
for i in range(W.shape[0]):
|
36
|
-
for j in range(W.shape[1]):
|
37
|
-
if W[i, j] != 0:
|
38
|
-
G.add_edge(f'Output{i}', f'Input{j}', ltpw=W[i, j])
|
39
|
-
|
40
|
-
edges = G.edges(data=True)
|
41
|
-
weights = [edata['ltpw'] for _, _, edata in edges]
|
42
|
-
pos = {}
|
43
|
-
|
44
|
-
num_motor_neurons = W.shape[0]
|
45
|
-
num_sensory_neurons = W.shape[1]
|
46
|
-
|
47
|
-
for j in range(num_sensory_neurons):
|
48
|
-
pos[f'Input{j}'] = (0, j)
|
49
|
-
|
50
|
-
motor_y_start = (num_sensory_neurons - num_motor_neurons) / 2
|
51
|
-
for i in range(num_motor_neurons):
|
52
|
-
pos[f'Output{i}'] = (1, motor_y_start + i)
|
53
|
-
|
54
|
-
|
55
|
-
art1 = nx.draw_networkx_nodes(G, pos, ax=ax, node_size=1000, node_color='lightblue')
|
56
|
-
art2 = nx.draw_networkx_edges(G, pos, ax=ax, edge_color=weights, edge_cmap=plt.cm.Blues, width=2)
|
57
|
-
art3 = nx.draw_networkx_labels(G, pos, ax=ax, font_size=10, font_weight='bold')
|
58
|
-
|
59
|
-
ax.spines['top'].set_visible(False)
|
60
|
-
ax.spines['right'].set_visible(False)
|
61
|
-
ax.spines['left'].set_visible(False)
|
62
|
-
ax.spines['bottom'].set_visible(False)
|
63
|
-
ax.get_xaxis().set_visible(False)
|
64
|
-
ax.get_yaxis().set_visible(False)
|
65
|
-
ax.set_title('Neural Web')
|
66
|
-
|
67
|
-
if return_objs == True:
|
68
|
-
|
69
|
-
return art1, art2, art3
|
70
|
-
|
71
|
-
|
72
|
-
def draw_model_architecture(model_name, model_path=''):
|
73
|
-
"""
|
74
|
-
The `draw_model_architecture` function visualizes the architecture of a neural network model with
|
75
|
-
multiple inputs based on activation functions.
|
76
|
-
|
77
|
-
:param model_name: The `model_name` parameter in the `draw_model_architecture` function is used to
|
78
|
-
specify the name of the neural network model whose architecture you want to visualize. This function
|
79
|
-
visualizes the architecture of a neural network model with multiple inputs based on activation
|
80
|
-
functions
|
81
|
-
:param model_path: The `model_path` parameter in the `draw_model_architecture` function is used to
|
82
|
-
specify the path where the neural network model is saved. If the model is saved in a specific
|
83
|
-
directory or file location, you can provide that path as a string when calling the function. If the
|
84
|
-
model is saved
|
85
|
-
"""
|
86
|
-
"""
|
87
|
-
Visualizes the architecture of a neural network model with multiple inputs based on activation functions.
|
88
|
-
"""
|
89
|
-
|
90
|
-
from .model_operations_cuda import load_model, get_scaler, get_act_pot, get_weights
|
91
|
-
|
92
|
-
model = load_model(model_name=model_name, model_path=model_path)
|
93
|
-
|
94
|
-
W = model[get_weights()]
|
95
|
-
activation_potentiation = model[get_act_pot()]
|
96
|
-
scaler_params = model[get_scaler()]
|
97
|
-
|
98
|
-
# Calculate dimensions based on number of activation functions
|
99
|
-
num_activations = len(activation_potentiation)
|
100
|
-
input_groups = num_activations # Number of input groups equals number of activations
|
101
|
-
num_inputs = W.shape[1]
|
102
|
-
|
103
|
-
# Create figure
|
104
|
-
fig = plt.figure(figsize=(15, 10))
|
105
|
-
|
106
|
-
# Calculate positions for nodes
|
107
|
-
def get_node_positions():
|
108
|
-
positions = {}
|
109
|
-
|
110
|
-
# Input layer positions
|
111
|
-
total_height = 0.8 # Maksimum dikey alan
|
112
|
-
group_height = total_height / input_groups # Her grup için ayrılan dikey alan
|
113
|
-
input_spacing = min(group_height / (num_inputs + 1), 0.1) # Her girdi arasındaki mesafe
|
114
|
-
|
115
|
-
for group in range(input_groups):
|
116
|
-
group_start_y = 0.9 - (group * group_height) # Grubun başlangıç y koordinatı
|
117
|
-
for i in range(num_inputs):
|
118
|
-
y_pos = group_start_y - ((i + 1) * input_spacing)
|
119
|
-
positions[f'input_{group}_{i}'] = (0.2, y_pos)
|
120
|
-
|
121
|
-
# Aggregation layer positions
|
122
|
-
agg_spacing = total_height / (num_inputs + 1)
|
123
|
-
for i in range(num_inputs):
|
124
|
-
positions[f'summed_{i}'] = (0.5, 0.9 - ((i + 1) * agg_spacing))
|
125
|
-
|
126
|
-
# Output layer positions
|
127
|
-
output_spacing = total_height / (W.shape[0] + 1)
|
128
|
-
for i in range(W.shape[0]):
|
129
|
-
positions[f'output_{i}'] = (0.8, 0.9 - ((i + 1) * output_spacing))
|
130
|
-
|
131
|
-
return positions
|
132
|
-
|
133
|
-
# Draw the network
|
134
|
-
pos = get_node_positions()
|
135
|
-
|
136
|
-
# Draw nodes
|
137
|
-
for group in range(input_groups):
|
138
|
-
# Draw input nodes
|
139
|
-
for i in range(num_inputs):
|
140
|
-
plt.plot(*pos[f'input_{group}_{i}'], 'o', color='lightgreen', markersize=20)
|
141
|
-
plt.text(pos[f'input_{group}_{i}'][0] - 0.05, pos[f'input_{group}_{i}'][1],
|
142
|
-
f'Input #{i+1} ({activation_potentiation[group]})', ha='right', va='center')
|
143
|
-
|
144
|
-
# Draw connections from input to summed input directly
|
145
|
-
plt.plot([pos[f'input_{group}_{i}'][0], pos[f'summed_{i}'][0]],
|
146
|
-
[pos[f'input_{group}_{i}'][1], pos[f'summed_{i}'][1]], 'k-')
|
147
|
-
# Draw aggregation nodes
|
148
|
-
if group == 0:
|
149
|
-
plt.plot(*pos[f'summed_{i}'], 'o', color='lightgreen', markersize=20)
|
150
|
-
plt.text(pos[f'summed_{i}'][0], pos[f'summed_{i}'][1] + 0.02,
|
151
|
-
f'Summed\nInput #{i+1}', ha='center', va='bottom')
|
152
|
-
|
153
|
-
# Draw output nodes and connections
|
154
|
-
for i in range(W.shape[0]):
|
155
|
-
plt.plot(*pos[f'output_{i}'], 'o', color='gold', markersize=20)
|
156
|
-
plt.text(pos[f'output_{i}'][0] + 0.05, pos[f'output_{i}'][1],
|
157
|
-
f'Output #{i+1}', ha='left', va='center', color='purple')
|
158
|
-
|
159
|
-
# Connect all aggregation nodes to each output
|
160
|
-
for group in range(num_inputs):
|
161
|
-
plt.plot([pos[f'summed_{group}'][0], pos[f'output_{i}'][0]],
|
162
|
-
[pos[f'summed_{group}'][1], pos[f'output_{i}'][1]], 'k-')
|
163
|
-
|
164
|
-
# Add labels and annotations
|
165
|
-
plt.text(0.2, 0.95, 'Input Layer', ha='center', va='bottom', fontsize=12)
|
166
|
-
plt.text(0.5, 0.95, 'Aggregation\nLayer', ha='center', va='bottom', fontsize=12)
|
167
|
-
plt.text(0.8, 0.95, 'Output Layer', ha='center', va='bottom', fontsize=12)
|
168
|
-
|
169
|
-
# Remove axes
|
170
|
-
plt.axis('off')
|
171
|
-
|
172
|
-
# Add model information
|
173
|
-
if scaler_params is None:
|
174
|
-
plt.text(0.95, 0.05, 'Standard Scaler=No', fontsize=10, ha='right', va='bottom')
|
175
|
-
else:
|
176
|
-
plt.text(0.95, 0.05, 'Standard Scaler=Yes', fontsize=10, ha='right', va='bottom')
|
177
|
-
|
178
|
-
# Add model architecture title
|
179
|
-
plt.text(0.95, 0.1, f"PLAN Model Architecture: {model_name}", fontsize=12, ha='right', va='bottom', fontweight='bold')
|
180
|
-
plt.tight_layout()
|
181
|
-
plt.show()
|
182
|
-
|
183
|
-
|
184
|
-
def draw_activations(x_train, activation):
|
185
|
-
|
186
|
-
from . import activation_functions_cuda as af
|
187
|
-
|
188
|
-
if activation == 'sigmoid':
|
189
|
-
result = af.Sigmoid(x_train)
|
190
|
-
|
191
|
-
elif activation == 'swish':
|
192
|
-
result = af.swish(x_train)
|
193
|
-
|
194
|
-
elif activation == 'circular':
|
195
|
-
result = af.circular_activation(x_train)
|
196
|
-
|
197
|
-
elif activation == 'mod_circular':
|
198
|
-
result = af.modular_circular_activation(x_train)
|
199
|
-
|
200
|
-
elif activation == 'tanh_circular':
|
201
|
-
result = af.tanh_circular_activation(x_train)
|
202
|
-
|
203
|
-
elif activation == 'leaky_relu':
|
204
|
-
result = af.leaky_relu(x_train)
|
205
|
-
|
206
|
-
elif activation == 'relu':
|
207
|
-
result = af.Relu(x_train)
|
208
|
-
|
209
|
-
elif activation == 'softplus':
|
210
|
-
result = af.softplus(x_train)
|
211
|
-
|
212
|
-
elif activation == 'elu':
|
213
|
-
result = af.elu(x_train)
|
214
|
-
|
215
|
-
elif activation == 'gelu':
|
216
|
-
result = af.gelu(x_train)
|
217
|
-
|
218
|
-
elif activation == 'selu':
|
219
|
-
result = af.selu(x_train)
|
220
|
-
|
221
|
-
elif activation == 'softmax':
|
222
|
-
result = af.Softmax(x_train)
|
223
|
-
|
224
|
-
elif activation == 'tanh':
|
225
|
-
result = af.tanh(x_train)
|
226
|
-
|
227
|
-
elif activation == 'sinakt':
|
228
|
-
result = af.sinakt(x_train)
|
229
|
-
|
230
|
-
elif activation == 'p_squared':
|
231
|
-
result = af.p_squared(x_train)
|
232
|
-
|
233
|
-
elif activation == 'sglu':
|
234
|
-
result = af.sglu(x_train, alpha=1.0)
|
235
|
-
|
236
|
-
elif activation == 'dlrelu':
|
237
|
-
result = af.dlrelu(x_train)
|
238
|
-
|
239
|
-
elif activation == 'exsig':
|
240
|
-
result = af.exsig(x_train)
|
241
|
-
|
242
|
-
elif activation == 'sin_plus':
|
243
|
-
result = af.sin_plus(x_train)
|
244
|
-
|
245
|
-
elif activation == 'acos':
|
246
|
-
result = af.acos(x_train, alpha=1.0, beta=0.0)
|
247
|
-
|
248
|
-
elif activation == 'gla':
|
249
|
-
result = af.gla(x_train, alpha=1.0, mu=0.0)
|
250
|
-
|
251
|
-
elif activation == 'srelu':
|
252
|
-
result = af.srelu(x_train)
|
253
|
-
|
254
|
-
elif activation == 'qelu':
|
255
|
-
result = af.qelu(x_train)
|
256
|
-
|
257
|
-
elif activation == 'isra':
|
258
|
-
result = af.isra(x_train)
|
259
|
-
|
260
|
-
elif activation == 'waveakt':
|
261
|
-
result = af.waveakt(x_train)
|
262
|
-
|
263
|
-
elif activation == 'arctan':
|
264
|
-
result = af.arctan(x_train)
|
265
|
-
|
266
|
-
elif activation == 'bent_identity':
|
267
|
-
result = af.bent_identity(x_train)
|
268
|
-
|
269
|
-
elif activation == 'sech':
|
270
|
-
result = af.sech(x_train)
|
271
|
-
|
272
|
-
elif activation == 'softsign':
|
273
|
-
result = af.softsign(x_train)
|
274
|
-
|
275
|
-
elif activation == 'pwl':
|
276
|
-
result = af.pwl(x_train)
|
277
|
-
|
278
|
-
elif activation == 'cubic':
|
279
|
-
result = af.cubic(x_train)
|
280
|
-
|
281
|
-
elif activation == 'gaussian':
|
282
|
-
result = af.gaussian(x_train)
|
283
|
-
|
284
|
-
elif activation == 'sine':
|
285
|
-
result = af.sine(x_train)
|
286
|
-
|
287
|
-
elif activation == 'tanh_square':
|
288
|
-
result = af.tanh_square(x_train)
|
289
|
-
|
290
|
-
elif activation == 'mod_sigmoid':
|
291
|
-
result = af.mod_sigmoid(x_train)
|
292
|
-
|
293
|
-
elif activation == 'linear':
|
294
|
-
result = x_train
|
295
|
-
|
296
|
-
elif activation == 'quartic':
|
297
|
-
result = af.quartic(x_train)
|
298
|
-
|
299
|
-
elif activation == 'square_quartic':
|
300
|
-
result = af.square_quartic(x_train)
|
301
|
-
|
302
|
-
elif activation == 'cubic_quadratic':
|
303
|
-
result = af.cubic_quadratic(x_train)
|
304
|
-
|
305
|
-
elif activation == 'exp_cubic':
|
306
|
-
result = af.exp_cubic(x_train)
|
307
|
-
|
308
|
-
elif activation == 'sine_square':
|
309
|
-
result = af.sine_square(x_train)
|
310
|
-
|
311
|
-
elif activation == 'logarithmic':
|
312
|
-
result = af.logarithmic(x_train)
|
313
|
-
|
314
|
-
elif activation == 'scaled_cubic':
|
315
|
-
result = af.scaled_cubic(x_train, 1.0)
|
316
|
-
|
317
|
-
elif activation == 'sine_offset':
|
318
|
-
result = af.sine_offset(x_train, 1.0)
|
319
|
-
|
320
|
-
elif activation == 'spiral':
|
321
|
-
result = af.spiral_activation(x_train)
|
322
|
-
|
323
|
-
try: return result
|
324
|
-
except:
|
325
|
-
print('\rWARNING: error in drawing some activation.', end='')
|
326
|
-
return x_train
|
327
|
-
|
328
|
-
|
329
|
-
def plot_evaluate(x_test, y_test, y_preds, acc_list, W, activation_potentiation):
|
330
|
-
|
331
|
-
from .metrics_cuda import metrics, confusion_matrix, roc_curve
|
332
|
-
from .ui import loading_bars, initialize_loading_bar
|
333
|
-
from .data_operations_cuda import decode_one_hot
|
334
|
-
from .model_operations_cuda import predict_model_ram
|
335
|
-
|
336
|
-
bar_format_normal = loading_bars()[0]
|
337
|
-
|
338
|
-
acc = acc_list[len(acc_list) - 1]
|
339
|
-
y_true = decode_one_hot(y_test)
|
340
|
-
|
341
|
-
y_true = cp.array(y_true, copy=True)
|
342
|
-
y_preds = cp.array(y_preds, copy=True)
|
343
|
-
Class = cp.unique(decode_one_hot(y_test))
|
344
|
-
|
345
|
-
precision, recall, f1 = metrics(y_test, y_preds)
|
346
|
-
|
347
|
-
|
348
|
-
cm = confusion_matrix(y_true, y_preds, len(Class))
|
349
|
-
fig, axs = plt.subplots(2, 2, figsize=(16, 12))
|
350
|
-
|
351
|
-
sns.heatmap(cm.get(), annot=True, fmt='d', ax=axs[0, 0])
|
352
|
-
axs[0, 0].set_title("Confusion Matrix")
|
353
|
-
axs[0, 0].set_xlabel("Predicted Class")
|
354
|
-
axs[0, 0].set_ylabel("Actual Class")
|
355
|
-
|
356
|
-
if len(Class) == 2:
|
357
|
-
fpr, tpr, thresholds = roc_curve(y_true, y_preds)
|
358
|
-
|
359
|
-
roc_auc = cp.trapz(tpr, fpr)
|
360
|
-
axs[1, 0].plot(fpr.get(), tpr.get(), color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})')
|
361
|
-
axs[1, 0].plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
|
362
|
-
axs[1, 0].set_xlim([0.0, 1.0])
|
363
|
-
axs[1, 0].set_ylim([0.0, 1.05])
|
364
|
-
axs[1, 0].set_xlabel('False Positive Rate')
|
365
|
-
axs[1, 0].set_ylabel('True Positive Rate')
|
366
|
-
axs[1, 0].set_title('Receiver Operating Characteristic (ROC) Curve')
|
367
|
-
axs[1, 0].legend(loc="lower right")
|
368
|
-
axs[1, 0].legend(loc="lower right")
|
369
|
-
else:
|
370
|
-
|
371
|
-
for i in range(len(Class)):
|
372
|
-
|
373
|
-
y_true_copy = cp.copy(y_true)
|
374
|
-
y_preds_copy = cp.copy(y_preds)
|
375
|
-
|
376
|
-
y_true_copy[y_true_copy == i] = 0
|
377
|
-
y_true_copy[y_true_copy != 0] = 1
|
378
|
-
|
379
|
-
y_preds_copy[y_preds_copy == i] = 0
|
380
|
-
y_preds_copy[y_preds_copy != 0] = 1
|
381
|
-
|
382
|
-
|
383
|
-
fpr, tpr, thresholds = roc_curve(y_true_copy, y_preds_copy)
|
384
|
-
|
385
|
-
roc_auc = cp.trapz(tpr, fpr)
|
386
|
-
axs[1, 0].plot(fpr.get(), tpr.get(), color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})')
|
387
|
-
axs[1, 0].plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
|
388
|
-
axs[1, 0].set_xlim([0.0, 1.0])
|
389
|
-
axs[1, 0].set_ylim([0.0, 1.05])
|
390
|
-
axs[1, 0].set_xlabel('False Positive Rate')
|
391
|
-
axs[1, 0].set_ylabel('True Positive Rate')
|
392
|
-
axs[1, 0].set_title('Receiver Operating Characteristic (ROC) Curve')
|
393
|
-
axs[1, 0].legend(loc="lower right")
|
394
|
-
axs[1, 0].legend(loc="lower right")
|
395
|
-
|
396
|
-
|
397
|
-
metric = ['Precision', 'Recall', 'F1 Score', 'Accuracy']
|
398
|
-
values = [precision, recall, f1, acc.get()]
|
399
|
-
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
|
400
|
-
|
401
|
-
|
402
|
-
bars = axs[0, 1].bar(metric, values, color=colors)
|
403
|
-
|
404
|
-
|
405
|
-
for bar, value in zip(bars, values):
|
406
|
-
axs[0, 1].text(bar.get_x() + bar.get_width() / 2, bar.get_height() - 0.05, f'{value:.2f}',
|
407
|
-
ha='center', va='bottom', fontsize=12, color='white', weight='bold')
|
408
|
-
|
409
|
-
axs[0, 1].set_ylim(0, 1)
|
410
|
-
axs[0, 1].set_xlabel('Metrics')
|
411
|
-
axs[0, 1].set_ylabel('Score')
|
412
|
-
axs[0, 1].set_title('Precision, Recall, F1 Score, and Accuracy (Weighted)')
|
413
|
-
axs[0, 1].grid(True, axis='y', linestyle='--', alpha=0.7)
|
414
|
-
|
415
|
-
feature_indices=[0, 1]
|
416
|
-
|
417
|
-
h = .02
|
418
|
-
x_min, x_max = x_test[:, feature_indices[0]].min() - 1, x_test[:, feature_indices[0]].max() + 1
|
419
|
-
y_min, y_max = x_test[:, feature_indices[1]].min() - 1, x_test[:, feature_indices[1]].max() + 1
|
420
|
-
xx, yy = cp.meshgrid(cp.arange(x_min, x_max, h),
|
421
|
-
cp.arange(y_min, y_max, h))
|
422
|
-
|
423
|
-
grid = cp.c_[xx.ravel(), yy.ravel()]
|
424
|
-
|
425
|
-
grid_full = cp.zeros((grid.shape[0], x_test.shape[1]), dtype=cp.float32)
|
426
|
-
grid_full[:, feature_indices] = grid
|
427
|
-
|
428
|
-
Z = [None] * len(grid_full)
|
429
|
-
|
430
|
-
predict_progress = initialize_loading_bar(total=len(grid_full),leave=False,
|
431
|
-
bar_format=bar_format_normal ,desc="Predicts For Decision Boundary",ncols= 65)
|
432
|
-
|
433
|
-
for i in range(len(grid_full)):
|
434
|
-
|
435
|
-
Z[i] = cp.argmax(predict_model_ram(grid_full[i], W=W, activation_potentiation=activation_potentiation))
|
436
|
-
predict_progress.update(1)
|
437
|
-
|
438
|
-
predict_progress.close()
|
439
|
-
|
440
|
-
Z = cp.array(Z)
|
441
|
-
Z = Z.reshape(xx.shape)
|
442
|
-
|
443
|
-
axs[1,1].contourf(xx.get(), yy.get(), Z.get(), alpha=0.8)
|
444
|
-
axs[1,1].scatter(x_test[:, feature_indices[0]].get(), x_test[:, feature_indices[1]].get(), c=decode_one_hot(y_test).get(), edgecolors='k', marker='o', s=20, alpha=0.9)
|
445
|
-
axs[1,1].set_xlabel(f'Feature {0 + 1}')
|
446
|
-
axs[1,1].set_ylabel(f'Feature {1 + 1}')
|
447
|
-
axs[1,1].set_title('Decision Boundary')
|
448
|
-
|
449
|
-
plt.show()
|
450
|
-
|
451
|
-
|
452
|
-
def plot_decision_boundary(x, y, activation_potentiation, W, artist=None, ax=None):
|
453
|
-
|
454
|
-
from .model_operations_cuda import predict_model_ram
|
455
|
-
from .data_operations_cuda import decode_one_hot
|
456
|
-
|
457
|
-
feature_indices = [0, 1]
|
458
|
-
|
459
|
-
h = .02
|
460
|
-
x_min, x_max = x[:, feature_indices[0]].min() - 1, x[:, feature_indices[0]].max() + 1
|
461
|
-
y_min, y_max = x[:, feature_indices[1]].min() - 1, x[:, feature_indices[1]].max() + 1
|
462
|
-
xx, yy = cp.meshgrid(cp.arange(x_min, x_max, h),
|
463
|
-
cp.arange(y_min, y_max, h))
|
464
|
-
|
465
|
-
grid = cp.c_[xx.ravel(), yy.ravel()]
|
466
|
-
grid_full = cp.zeros((grid.shape[0], x.shape[1]))
|
467
|
-
grid_full[:, feature_indices] = grid
|
468
|
-
|
469
|
-
Z = [None] * len(grid_full)
|
470
|
-
|
471
|
-
for i in range(len(grid_full)):
|
472
|
-
Z[i] = cp.argmax(predict_model_ram(grid_full[i], W=W, activation_potentiation=activation_potentiation))
|
473
|
-
|
474
|
-
Z = cp.array(Z, dtype=cp.int32)
|
475
|
-
Z = Z.reshape(xx.shape)
|
476
|
-
|
477
|
-
if ax is None:
|
478
|
-
|
479
|
-
plt.contourf(xx.get(), yy.get(), Z.get(), alpha=0.8)
|
480
|
-
plt.scatter(x[:, feature_indices[0]].get(), x[:, feature_indices[1]].get(), c=decode_one_hot(y).get(), edgecolors='k', marker='o', s=20, alpha=0.9)
|
481
|
-
plt.xlabel(f'Feature {0 + 1}')
|
482
|
-
plt.ylabel(f'Feature {1 + 1}')
|
483
|
-
plt.title('Decision Boundary')
|
484
|
-
|
485
|
-
plt.show()
|
486
|
-
|
487
|
-
else:
|
488
|
-
|
489
|
-
try:
|
490
|
-
art1_1 = ax[1, 0].contourf(xx.get(), yy.get(), Z.get(), alpha=0.8)
|
491
|
-
art1_2 = ax[1, 0].scatter(x[:, feature_indices[0]].get(), x[:, feature_indices[1]].get(), c=decode_one_hot(y).get(), edgecolors='k', marker='o', s=20, alpha=0.9)
|
492
|
-
ax[1, 0].set_xlabel(f'Feature {0 + 1}')
|
493
|
-
ax[1, 0].set_ylabel(f'Feature {1 + 1}')
|
494
|
-
ax[1, 0].set_title('Decision Boundary')
|
495
|
-
|
496
|
-
return art1_1, art1_2
|
497
|
-
|
498
|
-
except:
|
499
|
-
|
500
|
-
art1_1 = ax.contourf(xx.get(), yy.get(), Z.get(), alpha=0.8)
|
501
|
-
art1_2 = ax.scatter(x[:, feature_indices[0]].get(), x[:, feature_indices[1]].get(), c=decode_one_hot(y).get(), edgecolors='k', marker='o', s=20, alpha=0.9)
|
502
|
-
ax.set_xlabel(f'Feature {0 + 1}')
|
503
|
-
ax.set_ylabel(f'Feature {1 + 1}')
|
504
|
-
ax.set_title('Decision Boundary')
|
505
|
-
|
506
|
-
|
507
|
-
return art1_1, art1_2
|
508
|
-
|
509
|
-
|
510
|
-
def plot_decision_space(x, y, y_preds=None, s=100, color='tab20'):
|
511
|
-
|
512
|
-
from .metrics_cuda import pca
|
513
|
-
from .data_operations_cuda import decode_one_hot
|
514
|
-
|
515
|
-
if x.shape[1] > 2:
|
516
|
-
|
517
|
-
X_pca = pca(x, n_components=2)
|
518
|
-
else:
|
519
|
-
X_pca = x
|
520
|
-
|
521
|
-
if y_preds == None:
|
522
|
-
y_preds = decode_one_hot(y)
|
523
|
-
|
524
|
-
y = decode_one_hot(y)
|
525
|
-
num_classes = len(cp.unique(y))
|
526
|
-
|
527
|
-
cmap = plt.get_cmap(color)
|
528
|
-
|
529
|
-
|
530
|
-
norm = plt.Normalize(vmin=0, vmax=num_classes - 1)
|
531
|
-
|
532
|
-
|
533
|
-
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, edgecolor='k', s=50, cmap=cmap, norm=norm)
|
534
|
-
|
535
|
-
|
536
|
-
for cls in range(num_classes):
|
537
|
-
|
538
|
-
class_points = []
|
539
|
-
|
540
|
-
|
541
|
-
for i in range(len(y)):
|
542
|
-
if y_preds[i] == cls:
|
543
|
-
class_points.append(X_pca[i])
|
544
|
-
|
545
|
-
class_points = cp.array(class_points, dtype=y.dtype)
|
546
|
-
|
547
|
-
|
548
|
-
if len(class_points) > 2:
|
549
|
-
hull = ConvexHull(class_points)
|
550
|
-
hull_points = class_points[hull.vertices]
|
551
|
-
|
552
|
-
hull_points = cp.vstack([hull_points, hull_points[0]])
|
553
|
-
|
554
|
-
plt.fill(hull_points[:, 0], hull_points[:, 1], color=cmap(norm(cls)), alpha=0.3, edgecolor='k', label=f'Class {cls} Hull')
|
555
|
-
|
556
|
-
plt.title("Decision Space (Data Distribution)")
|
557
|
-
|
558
|
-
plt.draw()
|
559
|
-
|
560
|
-
|
561
|
-
def update_neuron_history(LTPW, ax1, row, col, class_count, artist5, fig1, acc=False, loss=False):
|
562
|
-
|
563
|
-
for j in range(class_count):
|
564
|
-
|
565
|
-
if acc != False and loss != False:
|
566
|
-
suptitle_info = ' Accuracy:' + str(acc) + '\n' + '\nNeurons Memory:'
|
567
|
-
else:
|
568
|
-
suptitle_info = 'Neurons Memory:'
|
569
|
-
|
570
|
-
mat = LTPW[j,:].reshape(row, col).get()
|
571
|
-
|
572
|
-
title_info = f'{j+1}. Neuron'
|
573
|
-
|
574
|
-
art5 = ax1[j].imshow(mat, interpolation='sinc', cmap='viridis')
|
575
|
-
|
576
|
-
ax1[j].set_aspect('equal')
|
577
|
-
ax1[j].set_xticks([])
|
578
|
-
ax1[j].set_yticks([])
|
579
|
-
ax1[j].set_title(title_info)
|
580
|
-
|
581
|
-
|
582
|
-
artist5.append([art5])
|
583
|
-
|
584
|
-
fig1.suptitle(suptitle_info, fontsize=16)
|
585
|
-
|
586
|
-
|
587
|
-
def initialize_visualization_for_fit(val, show_training, neurons_history, x_train, y_train):
|
588
|
-
"""Initializes the visualization setup based on the parameters."""
|
589
|
-
from .data_operations_cuda import find_closest_factors
|
590
|
-
visualization_objects = {}
|
591
|
-
|
592
|
-
if show_training or neurons_history:
|
593
|
-
if not val:
|
594
|
-
raise ValueError("For showing training or neurons history, 'val' parameter must be True.")
|
595
|
-
|
596
|
-
G = nx.Graph()
|
597
|
-
fig, ax = plt.subplots(2, 2)
|
598
|
-
fig.suptitle('Train History')
|
599
|
-
visualization_objects.update({
|
600
|
-
'G': G,
|
601
|
-
'fig': fig,
|
602
|
-
'ax': ax,
|
603
|
-
'artist1': [],
|
604
|
-
'artist2': [],
|
605
|
-
'artist3': [],
|
606
|
-
'artist4': []
|
607
|
-
})
|
608
|
-
|
609
|
-
if neurons_history:
|
610
|
-
row, col = find_closest_factors(len(x_train[0]))
|
611
|
-
fig1, ax1 = plt.subplots(1, len(y_train[0]), figsize=(18, 14))
|
612
|
-
visualization_objects.update({
|
613
|
-
'fig1': fig1,
|
614
|
-
'ax1': ax1,
|
615
|
-
'artist5': [],
|
616
|
-
'row': row,
|
617
|
-
'col': col
|
618
|
-
})
|
619
|
-
|
620
|
-
return visualization_objects
|
621
|
-
|
622
|
-
|
623
|
-
def update_weight_visualization_for_fit(ax, LTPW, artist2):
|
624
|
-
"""Updates the weight visualization plot."""
|
625
|
-
art2 = ax.imshow(LTPW.get(), interpolation='sinc', cmap='viridis')
|
626
|
-
artist2.append([art2])
|
627
|
-
|
628
|
-
def show():
|
629
|
-
plt.tight_layout()
|
630
|
-
plt.show()
|
631
|
-
|
632
|
-
def update_neural_web_for_fit(W, ax, G, artist):
|
633
|
-
"""
|
634
|
-
The function `update_neural_web_for_fit` updates a neural web visualization for fitting.
|
635
|
-
"""
|
636
|
-
art5_1, art5_2, art5_3 = draw_neural_web(W=W, ax=ax, G=G, return_objs=True)
|
637
|
-
art5_list = [art5_1] + [art5_2] + list(art5_3.values())
|
638
|
-
artist.append(art5_list)
|
639
|
-
|
640
|
-
def update_decision_boundary_for_fit(ax, x_val, y_val, activation_potentiation, LTPW, artist1):
|
641
|
-
"""Updates the decision boundary visualization."""
|
642
|
-
art1_1, art1_2 = plot_decision_boundary(x_val, y_val, activation_potentiation, LTPW, artist=artist1, ax=ax)
|
643
|
-
artist1.append([*art1_1.collections, art1_2])
|
644
|
-
|
645
|
-
|
646
|
-
def update_validation_history_for_fit(ax, val_list, artist3):
|
647
|
-
"""Updates the validation accuracy history plot."""
|
648
|
-
val_list_cpu = []
|
649
|
-
for i in range(len(val_list)):
|
650
|
-
val_list_cpu.append(val_list[i].get())
|
651
|
-
period = list(range(1, len(val_list_cpu) + 1))
|
652
|
-
art3 = ax.plot(
|
653
|
-
period,
|
654
|
-
val_list_cpu,
|
655
|
-
linestyle='--',
|
656
|
-
color='g',
|
657
|
-
marker='o',
|
658
|
-
markersize=6,
|
659
|
-
linewidth=2,
|
660
|
-
label='Validation Accuracy'
|
661
|
-
)
|
662
|
-
ax.set_title('Validation History')
|
663
|
-
ax.set_xlabel('Time')
|
664
|
-
ax.set_ylabel('Validation Accuracy')
|
665
|
-
ax.set_ylim([0, 1])
|
666
|
-
artist3.append(art3)
|
667
|
-
|
668
|
-
|
669
|
-
def display_visualization_for_fit(fig, artist_list, interval):
|
670
|
-
"""Displays the animation for the given artist list."""
|
671
|
-
ani = ArtistAnimation(fig, artist_list, interval=interval, blit=True)
|
672
|
-
return ani
|
673
|
-
|
674
|
-
def update_neuron_history_for_learner(LTPW, ax1, row, col, class_count, artist5, data, fig1, acc=False, loss=False):
|
675
|
-
|
676
|
-
for j in range(len(class_count)):
|
677
|
-
|
678
|
-
if acc != False and loss != False:
|
679
|
-
suptitle_info = data + ' Accuracy:' + str(acc) + '\n' + data + ' Loss:' + str(loss) + '\nNeurons Memory:'
|
680
|
-
else:
|
681
|
-
suptitle_info = 'Neurons Memory:'
|
682
|
-
|
683
|
-
mat = LTPW[j,:].reshape(row, col)
|
684
|
-
|
685
|
-
title_info = f'{j+1}. Neuron'
|
686
|
-
|
687
|
-
art5 = ax1[j].imshow(mat.get(), interpolation='sinc', cmap='viridis')
|
688
|
-
|
689
|
-
ax1[j].set_aspect('equal')
|
690
|
-
ax1[j].set_xticks([])
|
691
|
-
ax1[j].set_yticks([])
|
692
|
-
ax1[j].set_title(title_info)
|
693
|
-
|
694
|
-
|
695
|
-
artist5.append([art5])
|
696
|
-
|
697
|
-
fig1.suptitle(suptitle_info, fontsize=16)
|
698
|
-
|
699
|
-
return artist5
|
700
|
-
|
701
|
-
def initialize_visualization_for_learner(show_history, neurons_history, neural_web_history, x_train, y_train):
|
702
|
-
"""Initialize all visualization components"""
|
703
|
-
from .data_operations_cuda import find_closest_factors
|
704
|
-
viz_objects = {}
|
705
|
-
|
706
|
-
if show_history:
|
707
|
-
fig, ax = plt.subplots(3, 1, figsize=(6, 8))
|
708
|
-
fig.suptitle('Learner History')
|
709
|
-
viz_objects['history'] = {
|
710
|
-
'fig': fig,
|
711
|
-
'ax': ax,
|
712
|
-
'artist1': [],
|
713
|
-
'artist2': [],
|
714
|
-
'artist3': []
|
715
|
-
}
|
716
|
-
|
717
|
-
if neurons_history:
|
718
|
-
row, col = find_closest_factors(len(x_train[0]))
|
719
|
-
if row != 0:
|
720
|
-
fig1, ax1 = plt.subplots(1, len(y_train[0]), figsize=(18, 14))
|
721
|
-
else:
|
722
|
-
fig1, ax1 = plt.subplots(1, 1, figsize=(18, 14))
|
723
|
-
viz_objects['neurons'] = {
|
724
|
-
'fig': fig1,
|
725
|
-
'ax': ax1,
|
726
|
-
'artists': [],
|
727
|
-
'row': row,
|
728
|
-
'col': col
|
729
|
-
}
|
730
|
-
|
731
|
-
if neural_web_history:
|
732
|
-
G = nx.Graph()
|
733
|
-
fig2, ax2 = plt.subplots(figsize=(18, 4))
|
734
|
-
viz_objects['web'] = {
|
735
|
-
'fig': fig2,
|
736
|
-
'ax': ax2,
|
737
|
-
'G': G,
|
738
|
-
'artists': []
|
739
|
-
}
|
740
|
-
|
741
|
-
return viz_objects
|
742
|
-
|
743
|
-
def update_history_plots_for_learner(viz_objects, depth_list, loss_list, best_acc_per_depth_list, x_train, final_activations):
|
744
|
-
"""Update history visualization plots"""
|
745
|
-
if 'history' not in viz_objects:
|
746
|
-
return
|
747
|
-
|
748
|
-
hist = viz_objects['history']
|
749
|
-
for i in range(len(loss_list)):
|
750
|
-
loss_list[i] = loss_list[i].get()
|
751
|
-
|
752
|
-
# Loss plot
|
753
|
-
art1 = hist['ax'][0].plot(depth_list, loss_list, color='r', markersize=6, linewidth=2)
|
754
|
-
hist['ax'][0].set_title('Train Loss Over Gen')
|
755
|
-
hist['artist1'].append(art1)
|
756
|
-
|
757
|
-
# Accuracy plot
|
758
|
-
|
759
|
-
for i in range(len(best_acc_per_depth_list)):
|
760
|
-
best_acc_per_depth_list[i] = best_acc_per_depth_list[i].get()
|
761
|
-
|
762
|
-
art2 = hist['ax'][1].plot(depth_list, best_acc_per_depth_list, color='g', markersize=6, linewidth=2)
|
763
|
-
hist['ax'][1].set_title('Train Accuracy Over Gen')
|
764
|
-
hist['artist2'].append(art2)
|
765
|
-
|
766
|
-
# Activation shape plot
|
767
|
-
x = cp.linspace(cp.min(x_train), cp.max(x_train), len(x_train))
|
768
|
-
translated_x_train = cp.copy(x)
|
769
|
-
for activation in final_activations:
|
770
|
-
translated_x_train += draw_activations(x, activation)
|
771
|
-
|
772
|
-
art3 = hist['ax'][2].plot(x.get(), translated_x_train.get(), color='b', markersize=6, linewidth=2)
|
773
|
-
hist['ax'][2].set_title('Potentiation Shape Over Gen')
|
774
|
-
hist['artist3'].append(art3)
|
775
|
-
|
776
|
-
def display_visualizations_for_learner(viz_objects, best_weights, data, best_acc, test_loss, y_train, interval):
|
777
|
-
"""Display all final visualizations"""
|
778
|
-
if 'history' in viz_objects:
|
779
|
-
hist = viz_objects['history']
|
780
|
-
for _ in range(30):
|
781
|
-
hist['artist1'].append(hist['artist1'][-1])
|
782
|
-
hist['artist2'].append(hist['artist2'][-1])
|
783
|
-
hist['artist3'].append(hist['artist3'][-1])
|
784
|
-
|
785
|
-
ani1 = ArtistAnimation(hist['fig'], hist['artist1'], interval=interval, blit=True)
|
786
|
-
ani2 = ArtistAnimation(hist['fig'], hist['artist2'], interval=interval, blit=True)
|
787
|
-
ani3 = ArtistAnimation(hist['fig'], hist['artist3'], interval=interval, blit=True)
|
788
|
-
plt.tight_layout()
|
789
|
-
plt.show()
|
790
|
-
|
791
|
-
if 'neurons' in viz_objects:
|
792
|
-
neurons = viz_objects['neurons']
|
793
|
-
for _ in range(10):
|
794
|
-
neurons['artists'] = update_neuron_history_for_learner(
|
795
|
-
cp.copy(best_weights),
|
796
|
-
neurons['ax'],
|
797
|
-
neurons['row'],
|
798
|
-
neurons['col'],
|
799
|
-
y_train[0],
|
800
|
-
neurons['artists'],
|
801
|
-
data=data,
|
802
|
-
fig1=neurons['fig'],
|
803
|
-
acc=best_acc,
|
804
|
-
loss=test_loss
|
805
|
-
)
|
806
|
-
|
807
|
-
ani4 = ArtistAnimation(neurons['fig'], neurons['artists'], interval=interval, blit=True)
|
808
|
-
plt.tight_layout()
|
809
|
-
plt.show()
|
810
|
-
|
811
|
-
if 'web' in viz_objects:
|
812
|
-
web = viz_objects['web']
|
813
|
-
for _ in range(30):
|
814
|
-
art5_1, art5_2, art5_3 = draw_neural_web(
|
815
|
-
W=best_weights,
|
816
|
-
ax=web['ax'],
|
817
|
-
G=web['G'],
|
818
|
-
return_objs=True
|
819
|
-
)
|
820
|
-
art5_list = [art5_1] + [art5_2] + list(art5_3.values())
|
821
|
-
web['artists'].append(art5_list)
|
822
|
-
|
823
|
-
ani5 = ArtistAnimation(web['fig'], web['artists'], interval=interval, blit=True)
|
824
|
-
plt.tight_layout()
|
825
|
-
plt.show()
|