Repository navigation
Expand file tree
/
Copy pathplot_utils.py
More file actions
238 lines (192 loc) · 9.61 KB
/
Copy pathplot_utils.py
File metadata and controls
238 lines (192 loc) · 9.61 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
from pathlib import Path
import matplotlib.pyplot as plt
from game_objects.game import NFGame
from portfolio_methods.portfolio import MixedPortfolio, PurePortfolio
import numpy as np
def draw_lines_dim_time(gradients_from_logger, method_name=""):
for player_num in range(2):
# Visualize gradients
stacked_iterations = [np.stack(it) for it in gradients_from_logger[player_num]]
# |A_i| x num of gradients
stacked_gradients = np.concatenate(stacked_iterations, axis=0).transpose()
# print(stacked_gradients.shape)
for dimension in range(stacked_gradients.shape[0]):
plt.plot(np.arange(stacked_gradients.shape[1]), stacked_gradients[dimension, :], label=f"dim{dimension}",
alpha=0.7)
# plt.imshow(stacked_gradients)
plt.xlabel("step")
plt.ylabel("size")
plt.title(f"{method_name} gradient's dimensions during convergence player {player_num}")
plt.legend()
plt.show()
def draw_stacked_bar_dim_avg_in_iterations(gradients_from_logger, method_name=""):
# before taking the average, there is abs
for player_num in range(2):
# num of gradients in iteration x |A_i|
stacked_gradients_iterations = [np.stack(it, axis=1).transpose() for it in gradients_from_logger[player_num]]
# print(len(stacked_gradients_iterations))
# print(stacked_gradients_iterations[0].shape)
num_dim = stacked_gradients_iterations[0].shape[1]
num_it = len(gradients_from_logger[player_num])
x = [f"it{i}" for i in range(num_it)]
bottom = np.zeros(num_it)
for dimension in range(num_dim):
# plt.bar(dimension, stacked_gradients[:, dimension].mean(), label=f"dim{dimension}")
y = [np.abs(stacked_gradients[:, dimension]).mean() for stacked_gradients in stacked_gradients_iterations]
plt.bar(x, y, bottom=bottom, label=f"dim{dimension}")
bottom = y
plt.xlabel("step")
plt.ylabel("size")
plt.title(f"{method_name} avg of each dimension - player {player_num}")
plt.legend()
plt.show()
def draw_gradient_by_dim(gradient, info_for_title=""):
# num_dim
plt.bar(list(range(gradient.shape[0])), gradient)
plt.xlabel("dimensions")
plt.ylabel("size")
plt.title(f"{info_for_title} Gradient by dimensions")
plt.show()
def draw_gradients(gradients, info_for_title="", info_small_title="Gradient"):
# draw by dimenstions
if type(gradients) is MixedPortfolio:
gradients = [policy.policy_values for policy in gradients.policies]
num_gradients = len(gradients)
# Calculate grid size
cols = min(5, num_gradients) # Limit to 5 columns max
rows = int(np.ceil(num_gradients / cols))
# Create the figure and axes
fig, axes = plt.subplots(rows, cols, figsize=(cols * 4, rows * 3))
axes = axes.flatten() if num_gradients > 1 else [axes]
fig.suptitle("Gradients" if info_for_title == "" else info_for_title, fontsize=16)
fig.subplots_adjust(top=0.88)
# Plot each gradient in a bar plot
for i, gradient in enumerate(gradients):
# gradient= normalize_by_length(gradient)
axes[i].bar(range(len(gradient)), gradient)
axes[i].set_title(f'{info_small_title} {i + 1} ')
# Hide unused subplots
for ax in axes[num_gradients:]:
ax.set_visible(False)
plt.xlabel("dimensions")
plt.tight_layout()
plt.show()
# this function will analise the lengths of gradients
def draw_lenghts(gradients_from_logger, method_name="", bins_count=10):
for player_num in range(2):
# Visualize gradients
stacked_iterations = [np.stack(it) for it in gradients_from_logger[player_num]]
# num_it x num_gradients_in_it x num_dim
gradients = np.concatenate(stacked_iterations, axis=0)
# num_gradients x num_dim
lengths = np.linalg.norm(gradients, axis=1)
# if you want to manually calculate histogram (less bins and looks worse)
# len_counts, bins = np.histogram(lengths, bins_count)
# # bins_names =[ f"{bin[0]:.1e}" for bin in list(zip(bins[:-1],bins[1:]))]
# bins_names =[ f"{bin[0]:.0e}-{bin[1]:.0e}" for bin in list(zip(bins[:-1],bins[1:]))]
# plt.bar(bins_names, len_counts, label= "count of gradients with the length in the bin")
draw_histogram(lengths,
title=f"{method_name} histogram of gradient lenghts P{player_num} - avg: {np.mean(lengths):.1e}, [{np.min(lengths):.1e}, {np.max(lengths):.1e}] ",
x_label="Gradient lengths")
def draw_histogram(data, title="Histogram", x_label="bins", bins="auto"):
plt.hist(data, bins=bins)
plt.xlabel(x_label)
plt.ylabel("count")
plt.title(title)
# style
# {'sci', 'scientific', 'plain'}
# useOffset = False,
plt.ticklabel_format(axis="x",scilimits=(-2, 2))
# plt.legend()
plt.show()
def draw_cov_matrix_of_gradients(gradients_from_logger, covariance=True, game: NFGame = None, method_name: str = ""):
for player_id in range(2):
gradients = np.array(
[it[i] for it in gradients_from_logger[player_id] for i in range(len(it))]).transpose()
if covariance:
covariance_matrix = np.cov(gradients)
plt.imshow(covariance_matrix, cmap="coolwarm")
else:
covariance_matrix_normalized = np.corrcoef(gradients)
plt.imshow(covariance_matrix_normalized, vmin=-1, vmax=1, cmap="coolwarm")
if game is not None:
plt.xticks(np.arange(game.get_player_action_num(player_id)),
[game.get_action_name(player_id=player_id, action_id=action_id) for action_id in
range(game.get_player_action_num(player_id))])
plt.yticks(np.arange(game.get_player_action_num(player_id)),
[game.get_action_name(player_id=player_id, action_id=action_id) for action_id in
range(game.get_player_action_num(player_id))])
plt.title(
f"{'Covariance' if covariance else 'Correlation'} of gradients for {method_name} and player {player_id}")
plt.colorbar()
plt.show()
def plot_gradient_boxplots(gradients_from_logger, method_name="", figsize=(8, 5), xlabel="Gradient Dimensions",
ylabel="Gradient Values", show_grid=True,game:NFGame=None, showoutliers =False):
"""
Plots boxplots of gradients in each dimension.
Parameters:
gradients list(np.array):
method_name (str):
figsize (tuple): Figure size as (width, height).
xlabel (str): Label for the x-axis.
ylabel (str): Label for the y-axis.
show_grid (bool): Whether to show grid lines on the plot.
"""
for player_id in range(2):
gradients = np.array([it[i] for it in gradients_from_logger[player_id] for i in range(len(it))])
gradients = gradients[:,:game.get_player_action_num(player_id)]
num_dimensions = gradients.shape[1]
plt.figure(figsize=figsize)
plt.boxplot(gradients, patch_artist=True, showfliers=showoutliers, notch=False,flierprops={"markersize":0.02,"alpha":0.2,})
# Set plot properties
plt.title(f"Gradients {method_name} player {player_id}")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if game is not None:
plt.xticks(ticks=np.arange(1, num_dimensions + 1), labels=[game.get_action_name(player_id=player_id, action_id=action_id) for action_id in
range(game.get_player_action_num(player_id))])
else:
plt.xticks(ticks=np.arange(1, num_dimensions + 1), labels=[f"Action {i + 1}" for i in range(num_dimensions)])
if show_grid:
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
def draw_action_pairs(z_val:np.ndarray, cmap = "coolwarm", vmin =None, vmax=None, game=None, title = ""):
if vmin is not None and vmax is not None:
plt.imshow(z_val, cmap=cmap, vmin=vmin, vmax=vmax)
elif vmin is not None:
plt.imshow(z_val, cmap=cmap, vmin=vmin)
elif vmax is not None:
plt.imshow(z_val, cmap=cmap, vmax=vmax)
else:
plt.imshow(z_val, cmap=cmap)
plt.colorbar()
plt.title(title)
if game is not None:
plt.xticks(ticks=range(game.get_player_action_num(1)),
labels=[game.get_action_name(player_id=1, action_id=action_id) for action_id in
range(game.get_player_action_num(1))])
plt.yticks(ticks=range(game.get_player_action_num(1)),
labels=[game.get_action_name(player_id=1, action_id=action_id) for action_id in
range(game.get_player_action_num(1))])
def draw_heatmap(array_to_plot,x_title,y_title, x_labels, y_labels, title = "", dir_path=Path("."), file_name="heatmap",logger = None ):
fig, ax = plt.subplots()
cax = ax.matshow(array_to_plot)
plt.xticks(fontsize=int(15/int(1+array_to_plot.shape[0]/10)))
plt.yticks(fontsize=int(15/int(1+array_to_plot.shape[1]/10)))
fig.colorbar(cax)
if x_labels is None:
x_labels = [str(i) for i in range(array_to_plot.shape[1])]
if y_labels is None:
y_labels = [str(i) for i in range(array_to_plot.shape[0])]
ax.set_xticks([i for i in range(array_to_plot.shape[1])],
x_labels)
ax.set_yticks([i for i in range(array_to_plot.shape[0])],
y_labels)
ax.set_xlabel(x_title)
ax.set_ylabel(y_title)
ax.set_title(title)
plt.savefig(dir_path / f"{file_name}.png")
if logger is not None:
logger.log_debug(f"Saved utility heatmap to {logger.dir_path / 'utility_matrix.png'}")
plt.close()