Created
April 27, 2020 18:20
-
-
Save elumixor/22b76c76c787e2a05528ea46bf5c295d to your computer and use it in GitHub Desktop.
Visualizer for my DLE Assignment 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from visualizer import visualize | |
from YOUR_CLASSIFIER import YourClassifier | |
if __name__ == '__main__': | |
# Load data | |
model = G2Model(**data) | |
sample_size = int(2e4) | |
training_set = model.generate_sample(sample_size) | |
# Create your classifier | |
net = YourClassifier() | |
# Train it, return history of a network. This is a list of a list of netwroks' state, as it learns | |
parameters_history = net.train(training_set, epochs=1000, step_size=0.05, quiet=True) | |
# Visualize your result. | |
# Provide path to a save file to save a gif. | |
# Set display=True to display. You might need to set | |
# matplotlib.use("TkAgg") | |
# to set neccessary backend. | |
visualize(net, parameters_history, training_set, save_file="path/to/your.gif", epochs=100) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExampleClassifier: | |
@property | |
def parameters(self): | |
""" | |
Here you should return a copy of your network's parameters, that specify its state. | |
These are learanable weights of your layers. | |
Later, visualizer will call set_paramters(params) on your network, setting it to a specific state. | |
""" | |
pass | |
def set_parameters(self, params): | |
""" | |
Sets network to a state, given by parameters. Should set layers' learnable weights to the given ones in the argument. | |
""" | |
pass | |
def train(self, training_set, epochs=1000, step_size=0.001, quiet=False): | |
""" | |
Here you train your network on the whole training set. | |
For each epoch you should save network's parameters into an array and then return that array. | |
That is required for visualization. | |
""" | |
x, label = training_set | |
parameters_history = [] | |
for epoch in range(epochs): | |
prediction = self.forward(x) | |
parameters_history.append(self.parameters) | |
self.backward(prediction, label, step_size) | |
return parameters_history |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from matplotlib import animation | |
class HeightGrid: | |
def __init__(self, x_bounds=(-8, 8), y_bounds=(-8, 8)): | |
self.grid = np.meshgrid(np.linspace(*x_bounds, 100), np.linspace(*y_bounds, 100)) | |
self.y, self.x = self.grid | |
self.dim = 100, 100 | |
self.__points = np.stack(self.grid, axis=2) | |
self.bounds = [*x_bounds, *y_bounds] | |
def map(self, predictor, classification=False): | |
z = np.array([predictor.classify(row) if classification else predictor.score(row) for row in self.__points]) | |
z = z.reshape(-1, z.shape[-2])[:-1, :-1] | |
return self.x, self.y, z | |
class Displayer: | |
def __init__(self): | |
self.fig, self.ax = plt.subplots() | |
self.height_grid = HeightGrid() | |
self.ax.axis(self.height_grid.bounds) | |
C = np.ones(self.height_grid.dim) * float('nan') | |
self.c = self.ax.pcolormesh(*self.height_grid.grid, C, cmap='plasma', vmin=0, vmax=1) | |
def plot_points(self, class_0, class_1): | |
print(class_0[:, 0]) | |
p0, = self.ax.plot(class_0[:, 0], class_0[:, 1], 'bo') | |
p1, = self.ax.plot(class_1[:, 0], class_1[:, 1], 'yd') | |
return p0, p1 | |
def plot_height_grid(self, predictor, classification=False): | |
x, y, z = self.height_grid.map(predictor, classification) | |
self.c.set_array(z.ravel()) | |
def plot(self, predictor, class_0, class_1, classification=False): | |
self.plot_height_grid(predictor, classification) | |
self.plot_points(class_0, class_1) | |
self.show() | |
def animate(self, predictor, parameters, train_set, classify=False, save_file=None, epochs=-1, display=True, fps=30): | |
points, labels = train_set | |
class_0 = np.array([s for i, s in enumerate(points) if labels[i] == 0]) | |
class_1 = np.array([s for i, s in enumerate(points) if labels[i] == 1]) | |
cb = self.fig.colorbar(self.c, ax=self.ax) | |
old = predictor.parameters | |
parameters = parameters if epochs < 0 else parameters[:epochs] | |
p0, p1 = self.plot_points(class_0, class_1) | |
def animate(frame): | |
predictor.set_parameters(frame) | |
x, y, z = self.height_grid.map(predictor, classify) | |
self.c.set_array(z.ravel()) | |
return self.c, p0, p1 | |
anim = animation.FuncAnimation(self.fig, animate, frames=parameters, interval=0, blit=True, repeat=True) | |
if save_file is not None: | |
print("saving animation") | |
anim.save(save_file, writer='imagemagick', fps=fps) | |
print(f"animation saved to {save_file}") | |
if display: | |
plt.show() | |
cb.remove() | |
predictor.set_parameters(old) | |
def show(self): | |
self.fig.show() | |
d = Displayer() | |
matplotlib.use("tkagg") | |
def visualize(predictor, parameters, train_set, classify=False, save_file=None, epochs=-1, display=True, fps=30): | |
d.animate(predictor, parameters, train_set, classify=classify, save_file=save_file, epochs=epochs, display=display, fps=30) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment