plots loss function as function of iterations. 
        When used in Jupyternotebook, plot will be displayed in notebook. Else, plot will be displayed in console and both plot and loss are saved in save_path.
960780
def plot_loss(self, n_skip=10, n_skip_end=5):
        '''
         
        '''
        if not in_ipynb(): plt.switch_backend('agg')
        plt.plot(self.iterations[n_skip:-n_skip_end], self.losses[n_skip:-n_skip_end])
        if not in_ipynb():
            plt.savefig(os.path.join(self.save_path, 'loss_plot.png'))
            np.save(os.path.join(self.save_path, 'losses.npy'), self.losses[10:])
464318
def plot(self, df_data, center=False, save=False,
             save_name=None, save_path='saved', dated=True, notebook=True):
        ""
        data = df_data.to_json(orient='records')
        options = self.to_dict()
        return plot(data, options, center=center, save=save,
                    save_name=save_name, save_path=save_path, dated=dated, notebook=notebook)
1119389
def _cl_int_plot_multi_top_losses(self, samples:int=3, figsize:Tuple[int,int]=(8,8), save_misclassified:bool=False):
    ""
    if samples >20:
        print("Max 20 samples")
        return
    losses, idxs = self.top_losses(self.data.c)
    l_dim = len(losses.size())
    if l_dim == 1: losses, idxs = self.top_losses()
    infolist, ordlosses_idxs, mismatches_idxs, mismatches, losses_mismatches, mismatchescontainer = [],[],[],[],[],[]
    truthlabels = np.asarray(self.y_true, dtype=int)
    classes_ids = [k for k in enumerate(self.data.classes)]
    predclass = np.asarray(self.pred_class)
    for i,pred in enumerate(predclass):
        where_truth = np.nonzero((truthlabels[i]>0))[0]
        mismatch = np.all(pred!=where_truth)
        if mismatch:
            mismatches_idxs.append(i)
            if l_dim > 1 : losses_mismatches.append((losses[i][pred], i))
            else: losses_mismatches.append((losses[i], i))
        if l_dim > 1: infotup = (i, pred, where_truth, losses[i][pred], np.round(self.probs[i], decimals=3)[pred], mismatch)
        else: infotup = (i, pred, where_truth, losses[i], np.round(self.probs[i], decimals=3)[pred], mismatch)
        infolist.append(infotup)
    ds = self.data.dl(self.ds_type).dataset
    mismatches = ds[mismatches_idxs]
    ordlosses = sorted(losses_mismatches, key = lambda x: x[0], reverse=True)
    for w in ordlosses: ordlosses_idxs.append(w[1])
    mismatches_ordered_byloss = ds[ordlosses_idxs]
    print(f'{str(len(mismatches))} misclassified samples over {str(len(self.data.valid_ds))} samples in the validation set.')
    samples = min(samples, len(mismatches))
    for ima in range(len(mismatches_ordered_byloss)):
        mismatchescontainer.append(mismatches_ordered_byloss[ima][0])
    for sampleN in range(samples):
        actualclasses = ''
        for clas in infolist[ordlosses_idxs[sampleN]][2]:
            actualclasses = f'{actualclasses} -- {str(classes_ids[clas][1])}'
        imag = mismatches_ordered_byloss[sampleN][0]
        imag = show_image(imag, figsize=figsize)
        imag.set_title(f"""Predicted: {classes_ids[infolist[ordlosses_idxs[sampleN]][1]][1]} \nActual: {actualclasses}\nLoss: {infolist[ordlosses_idxs[sampleN]][3]}\nProbability: {infolist[ordlosses_idxs[sampleN]][4]}""",
                        loc='left')
        plt.show()
        if save_misclassified: return mismatchescontainer
799891
def plot_loss_history(history, figsize=(15, 8)):
    

    plt.figure(figsize=figsize)

    plt.plot(history.history["loss"])
    plt.plot(history.history["val_loss"])

    plt.xlabel("# Epochs")
    plt.ylabel("Loss")
    plt.legend(["Training", "Validation"])
    plt.title("Loss over time")

    plt.show()
1297575
def in_jupyter_notebook():
    
    try:
        cfg = get_ipython().config
        #print('cfg = %s' % (ut.repr4(cfg),))
        #x = cfg['IPKernelApp']['parent_appname']
        # might not work if using jupyter-console
        if cfg['IPKernelApp']['connection_file'].count('jupyter'):
            return True
        else:
            return False
    except (AttributeError, NameError):
        return False
1304500
def plotExampleInputOutput(sp, inputVectors, saveFigPrefix=None):
  
  numInputVector, inputSize = inputVectors.shape
  numColumns = np.prod(sp.getColumnDimensions())

  outputColumns = np.zeros((numInputVector, numColumns), dtype=uintType)
  inputOverlap = np.zeros((numInputVector, numColumns), dtype=uintType)

  connectedCounts = np.zeros((numColumns,), dtype=uintType)
  sp.getConnectedCounts(connectedCounts)

  winnerInputOverlap = np.zeros(numInputVector)
  for i in range(numInputVector):
    sp.compute(inputVectors[i][:], False, outputColumns[i][:])
    inputOverlap[i][:] = sp.getOverlaps()
    activeColumns = np.where(outputColumns[i][:] > 0)[0]
    if len(activeColumns) > 0:
      winnerInputOverlap[i] = np.mean(
        inputOverlap[i][np.where(outputColumns[i][:] > 0)[0]])

  fig, axs = plt.subplots(2, 1)
  axs[0].imshow(inputVectors[:, :200], cmap='gray', interpolation="nearest")
  axs[0].set_ylabel('input #')
  axs[0].set_title('input vectors')
  axs[1].imshow(outputColumns[:, :200], cmap='gray', interpolation="nearest")
  axs[1].set_ylabel('input #')
  axs[1].set_title('output vectors')
  if saveFigPrefix is not None:
    plt.savefig('figures/{}_example_input_output.pdf'.format(saveFigPrefix))

  inputDensity = np.sum(inputVectors, 1) / float(inputSize)
  outputDensity = np.sum(outputColumns, 1) / float(numColumns)
  fig, axs = plt.subplots(2, 1)
  axs[0].plot(inputDensity)
  axs[0].set_xlabel('input #')
  axs[0].set_ylim([0, 0.2])

  axs[1].plot(outputDensity)
  axs[1].set_xlabel('input #')
  axs[1].set_ylim([0, 0.05])

  if saveFigPrefix is not None:
    plt.savefig('figures/{}_example_input_output_density.pdf'.format(saveFigPrefix))
269721
def plot_figures():
    """"""
    numpy.random.seed(1000)


    def foo(coord, param):
        return param[0] * numpy.e ** (-param[1] * coord)

    coord = numpy.linspace(0, 10, 200)
    distribution = cp.J(cp.Uniform(1, 2), cp.Uniform(0.1, 0.2))

    samples = distribution.sample(50)
    evals = numpy.array([foo(coord, sample) for sample in samples.T])

    plt.plot(coord, evals.T, "k-", lw=3, alpha=0.2)
    plt.xlabel(r"\verb;coord;")
    plt.ylabel(r"function evaluations \verb;foo;")
    plt.savefig("demonstration.png")
    plt.clf()


    samples = distribution.sample(1000, "H")
    evals = [foo(coord, sample) for sample in samples.T]
    expected = numpy.mean(evals, 0)
    deviation = numpy.std(evals, 0)

    plt.fill_between(
        coord, expected-deviation, expected+deviation,
        color="k", alpha=0.3
    )
    plt.plot(coord, expected, "k--", lw=3)
    plt.xlabel(r"\verb;coord;")
    plt.ylabel(r"function evaluations \verb;foo;")
    plt.title("Results using Monte Carlo simulation")
    plt.savefig("results_montecarlo.png")
    plt.clf()


    polynomial_expansion = cp.orth_ttr(8, distribution)
    foo_approx = cp.fit_regression(polynomial_expansion, samples, evals)
    expected = cp.E(foo_approx, distribution)
    deviation = cp.Std(foo_approx, distribution)

    plt.fill_between(
        coord, expected-deviation, expected+deviation,
        color="k", alpha=0.3
    )
    plt.plot(coord, expected, "k--", lw=3)
    plt.xlabel(r"\verb;coord;")
    plt.ylabel(r"function evaluations \verb;foo;")
    plt.title("Results using point collocation method")
    plt.savefig("results_collocation.png")
    plt.clf()


    absissas, weights = cp.generate_quadrature(8, distribution, "C")
    evals = [foo(coord, val) for val in absissas.T]
    foo_approx = cp.fit_quadrature(polynomial_expansion, absissas, weights, evals)
    expected = cp.E(foo_approx, distribution)
    deviation = cp.Std(foo_approx, distribution)

    plt.fill_between(
        coord, expected-deviation, expected+deviation,
        color="k", alpha=0.3
    )
    plt.plot(coord, expected, "k--", lw=3)
    plt.xlabel(r"\verb;coord;")
    plt.ylabel(r"function evaluations \verb;foo;")
    plt.title("Results using psuedo-spectral projection method")
    plt.savefig("results_spectral.png")
    plt.clf()
526021
def plot(config, image, file):
    
    image = np.squeeze(image)
    print(file, image.shape)
    imsave(file, image)
396881
def plot(self):
    
    plt.ion()
    plt.show()
    x = numpy.linspace(0, 15, 100)
    y = numpy.zeros(x.shape)
    y = self.excite(y, x)
    plt.plot(x, y)
    plt.xlabel('Input')
    plt.ylabel('Persistence')
    plt.title('Sigmoid Activation Function')
540977
def in_notebook():
    
    try:
        # function returns IPython context, but only in IPython
        ipy = get_ipython()  # NOQA
        # we only want to render rich output in notebooks
        # in terminals we definitely do not want to output HTML
        name = str(ipy.__class__).lower()
        terminal = 'terminal' in name

        # spyder uses ZMQshell, and can appear to be a notebook
        spyder = '_' in os.environ and 'spyder' in os.environ['_']

        # assume we are in a notebook if we are not in
        # a terminal and we haven't been run by spyder
        notebook = (not terminal) and (not spyder)

        return notebook

    except BaseException:
        return False
362491
def get_plot(self_or_cls, obj, doc=None, renderer=None, **kwargs):
        
        if doc is None:
            doc = Document() if self_or_cls.notebook_context else curdoc()

        if self_or_cls.notebook_context:
            curdoc().theme = self_or_cls.theme
        doc.theme = self_or_cls.theme
        plot = super(BokehRenderer, self_or_cls).get_plot(obj, renderer, **kwargs)
        plot.document = doc
        return plot
361567
def plot(data, output_dir_path='.', width=10, height=8):
    
    if not isinstance(data, pd.DataFrame):
        data = pd.DataFrame(data)
    plot_accuracy(data, output_dir_path=output_dir_path,
                  width=width, height=height)
    plot_loss(data, output_dir_path, width=width, height=height)
248277
def draw_to_notebook(layers, **kwargs):
    
    from IPython.display import Image
    layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers')
              else layers)
    dot = make_pydot_graph(layers, **kwargs)
    return Image(dot.create_png())
388551
def dump_to_console(pylint_data):
    
    for key, value in list(pylint_data.items()):
        if key not in ('errors', 'total', 'scores', 'average') and len(value) > 0:
            print("\n*********** {}".format(key))
            for line in value:
                print(line.strip('\n'))
            f_score = [score[1] for score in pylint_data['scores'] if score[0] == key][0]
            print("Score: {}".format(f_score))
826973
def save_notebook(self):
        
        try:
            from IPython.display import display, Javascript
        except ImportError:
            log.warning("Could not import IPython Display Function")
            print("Make sure to save your notebook before sending it to OK!")
            return

        if self.mode == "jupyter":
            display(Javascript('IPython.notebook.save_checkpoint();'))
            display(Javascript('IPython.notebook.save_notebook();'))
        elif self.mode == "jupyterlab":
            display(Javascript('document.querySelector(\'[data-command="docmanager:save"]\').click();'))   
                       
        print('Saving notebook...', end=' ')

        ipynbs = [path for path in self.assignment.src
                  if os.path.splitext(path)[1] == '.ipynb']
        # Wait for first .ipynb to save
        if ipynbs:
            if wait_for_save(ipynbs[0]):
                print("Saved '{}'.".format(ipynbs[0]))
            else:
                log.warning("Timed out waiting for IPython save")
                print("Could not automatically save \'{}\'".format(ipynbs[0]))
                print("Make sure your notebook"
                      " is correctly named and saved before submitting to OK!".format(ipynbs[0]))
                return False                
        else:
            print("No valid file sources found")
        return True
87584
def dumps(self):
        

        string = Command('addplot', options=self.options).dumps()

        if self.coordinates is not None:
            string += ' coordinates {%\n'

            if self.error_bar is None:
                for x, y in self.coordinates:
                    # ie: "(x,y)"
                    string += '(' + str(x) + ',' + str(y) + ')%\n'

            else:
                for (x, y), (e_x, e_y) in zip(self.coordinates,
                                              self.error_bar):
                    # ie: "(x,y) +- (e_x,e_y)"
                    string += '(' + str(x) + ',' + str(y) + \
                        ') +- (' + str(e_x) + ',' + str(e_y) + ')%\n'

            string += '};%\n%\n'

        elif self.func is not None:
            string += '{' + self.func + '};%\n%\n'

        if self.name is not None:
            string += Command('addlegendentry', self.name).dumps()

        super().dumps()

        return string
752026
def _cl_int_plot_top_losses(self, k, largest=True, figsize=(12,12), heatmap:bool=True, heatmap_thresh:int=16,
                            return_fig:bool=None)->Optional[plt.Figure]:
    ""
    tl_val,tl_idx = self.top_losses(k, largest)
    classes = self.data.classes
    cols = math.ceil(math.sqrt(k))
    rows = math.ceil(k/cols)
    fig,axes = plt.subplots(rows, cols, figsize=figsize)
    fig.suptitle('prediction/actual/loss/probability', weight='bold', size=14)
    for i,idx in enumerate(tl_idx):
        im,cl = self.data.dl(self.ds_type).dataset[idx]
        cl = int(cl)
        im.show(ax=axes.flat[i], title=
            f'{classes[self.pred_class[idx]]}/{classes[cl]} / {self.losses[idx]:.2f} / {self.probs[idx][cl]:.2f}')
        if heatmap:
            xb,_ = self.data.one_item(im, detach=False, denorm=False)
            m = self.learn.model.eval()
            with hook_output(m[0]) as hook_a:
                with hook_output(m[0], grad= True) as hook_g:
                    preds = m(xb)
                    preds[0,cl].backward()
            acts = hook_a.stored[0].cpu()
            if (acts.shape[-1]*acts.shape[-2]) >= heatmap_thresh:
                grad = hook_g.stored[0][0].cpu()
                grad_chan = grad.mean(1).mean(1)
                mult = F.relu(((acts*grad_chan[...,None,None])).sum(0))
                sz = list(im.shape[-2:])
                axes.flat[i].imshow(mult, alpha=0.6, extent=(0,*sz[::-1],0), interpolation='bilinear', cmap='magma')                
    if ifnone(return_fig, defaults.return_fig): return fig