Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def on_start(self, state):
from livelossplot import PlotLosses
self.plt = PlotLosses(**self._kwargs)
self.batch_plt = PlotLosses(**self._kwargs)
# TO START:
# pip install livelossplot
# pip install neptune-cli
# neptune account login
# neptune run minimal-neptune.py
# enjoy results
from time import sleep
import numpy as np
from livelossplot import PlotLosses
liveplot = PlotLosses(target='neptune')
for i in range(20):
liveplot.update({
'accuracy': 1 - np.random.rand() / (i + 2.),
'val_accuracy': 1 - np.random.rand() / (i + 0.5),
'mse': 1. / (i + 2.),
'val_mse': 1. / (i + 0.5)
})
liveplot.draw()
sleep(.5)
def on_start(self, state):
from livelossplot import PlotLosses
self.plt = PlotLosses(**self._kwargs)
self.batch_plt = PlotLosses(**self._kwargs)
def draw(self):
if self.target == MATPLOTLIB_TARGET:
draw_plot(self.logs, self.base_metrics,
figsize=self.figsize,
max_epoch=self.max_epoch,
max_cols=self.max_cols,
series_fmt=self.series_fmt,
metric2title=self.metric2title,
skip_first=self.skip_first,
extra_plots=self.extra_plots,
fig_path=self.fig_path)
if self.metrics_extrema:
print_extrema(self.logs,
self.base_metrics,
self.metrics_extrema,
series_fmt=self.series_fmt,
metric2title=self.metric2title)
if self.target == NEPTUNE_TARGET:
def _validate_target(self):
assert isinstance(self.target, str),\
'target must be str, got "{}" instead.'.format(type(self.target))
if self.target != MATPLOTLIB_TARGET and self.target != NEPTUNE_TARGET:
raise ValueError('Target must be "{}" or "{}", got "{}" instead.'.format(MATPLOTLIB_TARGET, NEPTUNE_TARGET, self.target))
def __init__(self,
figsize=None,
cell_size=(6, 4),
dynamic_x_axis=False,
max_cols=2,
max_epoch=None,
metric2title={},
series_fmt={'training': '{}', 'validation':'val_{}'},
validation_fmt="val_{}",
plot_extrema=True,
skip_first=2,
extra_plots=[],
fig_path=None,
tensorboard_dir=None,
target=MATPLOTLIB_TARGET):
self.figsize = figsize
self.cell_size = cell_size
self.dynamic_x_axis = dynamic_x_axis
self.max_cols = max_cols
self.max_epoch = max_epoch
self.metric2title = metric2title
self.series_fmt = series_fmt
if validation_fmt is not None:
# backward compatibility
self.series_fmt['validation'] = validation_fmt
self.logs = None
self.base_metrics = None
self.metrics_extrema = None
self.plot_extrema = plot_extrema
self.skip_first = skip_first
self.target = target
self.model = model
self.X = X
self.Y = Y
def predict(self, model, X):
# e.g. model(torch.fromnumpy(X)).detach().numpy()
return model.predict(X)
def draw(self, *args, **kwargs):
plt.plot(self.X, self.Y, 'r.', label="Ground truth")
plt.plot(self.X, self.predict(self.model, self.X), '-', label="Model")
plt.title("Prediction")
plt.legend(loc='lower right')
class Plot2d(BaseSubplot):
def __init__(self, model, X, Y, valiation_data=(None, None), h=0.02, margin=0.25):
super().__init__()
self.model = model
self.X = X
self.Y = Y
self.X_test, self.Y_test = valiation_data
# add size assertions
self.cm_bg = plt.cm.RdBu
self.cm_points = ListedColormap(['#FF0000', '#0000FF'])
h = .02 # step size in the mesh
x_min = X[:, 0].min() - margin
x_max = X[:, 0].max() + margin
serie_metric_name = serie_fmt.format(self.metric)
serie_metric_logs = [(log.get('_i', i + 1), log[serie_metric_name])
for i, log in enumerate(logs[skip:])
if serie_metric_name in log]
if len(serie_metric_logs) > 0:
xs, ys = zip(*serie_metric_logs)
plt.plot(xs, ys, label=serie_label)
plt.title(self.title)
plt.xlabel('epoch')
plt.legend(loc='center right')
class Plot1D(BaseSubplot):
def __init__(self, model, X, Y):
super().__init__(self)
self.model = model
self.X = X
self.Y = Y
def predict(self, model, X):
# e.g. model(torch.fromnumpy(X)).detach().numpy()
return model.predict(X)
def draw(self, *args, **kwargs):
plt.plot(self.X, self.Y, 'r.', label="Ground truth")
plt.plot(self.X, self.predict(self.model, self.X), '-', label="Model")
plt.title("Prediction")
plt.legend(loc='lower right')
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
class BaseSubplot:
def __init__(self):
pass
def draw(self):
raise Exception("Not implemented")
def __call__(self, *args, **kwargs):
self.draw(*args, **kwargs)
class LossSubplot(BaseSubplot):
def __init__(self,
metric,
title="",
series_fmt={'training': '{}', 'validation':'val_{}'},
skip_first=2,
max_epoch=None):
super().__init__(self)
self.metric = metric
self.title = title
self.series_fmt = series_fmt
self.skip_first = skip_first
self.max_epoch = max_epoch
def _how_many_to_skip(self, log_length, skip_first):
if log_length < skip_first:
return 0
def _validate_target(self):
assert isinstance(self.target, str),\
'target must be str, got "{}" instead.'.format(type(self.target))
if self.target != MATPLOTLIB_TARGET and self.target != NEPTUNE_TARGET:
raise ValueError('Target must be "{}" or "{}", got "{}" instead.'.format(MATPLOTLIB_TARGET, NEPTUNE_TARGET, self.target))