Python matplotlib.pylab.figure() Examples

The following are 30 code examples of matplotlib.pylab.figure(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pylab , or try the search function .
Example #1
Source File: models.py    From philo2vec with MIT License 7 votes vote down vote up
def plot(self, words, num_points=None):
        if not num_points:
            num_points = len(words)

        embeddings = self.get_words_embeddings(words)
        tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
        two_d_embeddings = tsne.fit_transform(embeddings[:num_points, :])

        assert two_d_embeddings.shape[0] >= len(words), 'More labels than embeddings'
        pylab.figure(figsize=(15, 15))  # in inches
        for i, label in enumerate(words[:num_points]):
            x, y = two_d_embeddings[i, :]
            pylab.scatter(x, y)
            pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
                           ha='right', va='bottom')
        pylab.show() 
Example #2
Source File: dataset.py    From Image-Restoration with MIT License 6 votes vote down vote up
def show_pred(images, predictions, ground_truth):
    # choose 10 indice from images and visualize them
    indice = [np.random.randint(0, len(images)) for i in range(40)]
    for i in range(0, 40):
        plt.figure()
        plt.subplot(1, 3, 1)
        plt.tight_layout()
        plt.title('deformed image')
        plt.imshow(images[indice[i]])
        plt.subplot(1, 3, 2)
        plt.tight_layout()
        plt.title('predicted mask')
        plt.imshow(predictions[indice[i]])
        plt.subplot(1, 3, 3)
        plt.tight_layout()
        plt.title('ground truth label')
        plt.imshow(ground_truth[indice[i]])
    plt.show()

# Load Data Science Bowl 2018 training dataset 
Example #3
Source File: plot_kmeans_example.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_clustering(x, y, title, mx=None, ymax=None, xmin=None, km=None):
    pylab.figure(num=None, figsize=(8, 6))
    if km:
        pylab.scatter(x, y, s=50, c=km.predict(list(zip(x, y))))
    else:
        pylab.scatter(x, y, s=50)

    pylab.title(title)
    pylab.xlabel("Occurrence word 1")
    pylab.ylabel("Occurrence word 2")

    pylab.autoscale(tight=True)
    pylab.ylim(ymin=0, ymax=1)
    pylab.xlim(xmin=0, xmax=1)
    pylab.grid(True, linestyle='-', color='0.75')

    return pylab 
Example #4
Source File: plots.py    From ee-atmcorr-timeseries with Apache License 2.0 6 votes vote down vote up
def figure_plotting_space():
    """
    defines the plotting space
    """
  
    fig = plt.figure(figsize=(10,10))
    bar_height = 0.04
    mini_gap = 0.03
    gap = 0.05
    graph_height = 0.24

    axH = fig.add_axes([0.1,gap+3*graph_height+2.5*mini_gap,0.87,bar_height])
    axS = fig.add_axes([0.1,gap+2*graph_height+2*mini_gap,0.87,graph_height])
    axV = fig.add_axes([0.1,gap+graph_height+mini_gap,0.87,graph_height])
    
    return fig, axH, axS, axV 
Example #5
Source File: prod_basis.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def generate_png_chess_dp_vertex(self):
    """Produces pictures of the dominant product vertex a chessboard convention"""
    import matplotlib.pylab as plt
    plt.ioff()
    dab2v = self.get_dp_vertex_doubly_sparse()
    for i, ab in enumerate(dab2v): 
        fname = "chess-v-{:06d}.png".format(i)
        print('Matrix No.#{}, Size: {}, Type: {}'.format(i+1, ab.shape, type(ab)), fname)
        if type(ab) != 'numpy.ndarray': ab = ab.toarray()
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(ab, interpolation='nearest', cmap=plt.cm.ocean)
        plt.colorbar()
        plt.savefig(fname)
        plt.close(fig) 
Example #6
Source File: mediator_utils.py    From whynot with MIT License 6 votes vote down vote up
def error_bar_plot(experiment_data, results, title="", ylabel=""):

    true_effect = experiment_data.true_effects.mean()
    estimators = list(results.keys())

    x = list(estimators)
    y = [results[estimator].ate for estimator in estimators]

    cis = [
        np.array(results[estimator].ci) - results[estimator].ate
        if results[estimator].ci is not None
        else [0, 0]
        for estimator in estimators
    ]
    err = [[abs(ci[0]) for ci in cis], [abs(ci[1]) for ci in cis]]

    plt.figure(figsize=(12, 5))
    (_, caps, _) = plt.errorbar(x, y, yerr=err, fmt="o", markersize=8, capsize=5)
    for cap in caps:
        cap.set_markeredgewidth(2)
    plt.plot(x, [true_effect] * len(x), label="True Effect")
    plt.legend(fontsize=12, loc="lower right")
    plt.ylabel(ylabel)
    plt.title(title) 
Example #7
Source File: demo_mi.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_entropy():
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))

    title = "Entropy $H(X)$"
    pylab.title(title)
    pylab.xlabel("$P(X=$coin will show heads up$)$")
    pylab.ylabel("$H(X)$")

    pylab.xlim(xmin=0, xmax=1.1)
    x = np.arange(0.001, 1, 0.001)
    y = -x * np.log2(x) - (1 - x) * np.log2(1 - x)
    pylab.plot(x, y)
    # pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in
    # [0,1,2,3,4]])

    pylab.autoscale(tight=True)
    pylab.grid(True)

    filename = "entropy_demo.png"
    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight") 
Example #8
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_roc(auc_score, name, tpr, fpr, label=None):
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))
    pylab.grid(True)
    pylab.plot([0, 1], [0, 1], 'k--')
    pylab.plot(fpr, tpr)
    pylab.fill_between(fpr, tpr, alpha=0.5)
    pylab.xlim([0.0, 1.0])
    pylab.ylim([0.0, 1.0])
    pylab.xlabel('False Positive Rate')
    pylab.ylabel('True Positive Rate')
    pylab.title('ROC curve (AUC = %0.2f) / %s' %
                (auc_score, label), verticalalignment="bottom")
    pylab.legend(loc="lower right")
    filename = name.replace(" ", "_")
    pylab.savefig(
        os.path.join(CHART_DIR, "roc_" + filename + ".png"), bbox_inches="tight") 
Example #9
Source File: drawing.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_figure(im_size, figsize_max=MAX_FIGURE_SIZE):
    """ create an empty figure of image size maximise maximal size

    :param tuple(int,int) im_size:
    :param float figsize_max:
    :return:

    >>> fig, ax = create_figure((100, 150))
    >>> isinstance(fig, plt.Figure)
    True
    """
    assert len(im_size) >= 2, 'not valid image size - %r' % im_size
    size = np.array(im_size[:2])
    fig_size = size[::-1] / float(size.max()) * figsize_max
    fig, ax = plt.subplots(figsize=fig_size)
    return fig, ax 
Example #10
Source File: drawing.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def export_figure(path_fig, fig):
    """ export the figure and close it afterwords

    :param str path_fig: path to the new figure image
    :param fig: object

    >>> path_fig = './sample_figure.jpg'
    >>> export_figure(path_fig, plt.figure())
    >>> os.remove(path_fig)
    """
    assert os.path.isdir(os.path.dirname(path_fig)), \
        'missing folder "%s"' % os.path.dirname(path_fig)
    fig.subplots_adjust(left=0., right=1., top=1., bottom=0.)
    logging.debug('exporting Figure: %s', path_fig)
    fig.savefig(path_fig)
    plt.close(fig) 
Example #11
Source File: dos.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_total_dos(self, **kwargs):
        """
        Plots the total DOS

        Args:
            **kwargs: Variables for matplotlib.pylab.plot customization (linewidth, linestyle, etc.)

        Returns:
            matplotlib.pylab.plot
        """
        try:
            import matplotlib.pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        fig = plt.figure(1, figsize=(6, 4))
        ax1 = fig.add_subplot(111)
        ax1.set_xlabel("E (eV)", fontsize=14)
        ax1.set_ylabel("DOS", fontsize=14)
        plt.fill_between(self.energies, self.t_dos, **kwargs)
        return plt 
Example #12
Source File: mpl.py    From spotpy with MIT License 6 votes vote down vote up
def __init__(self, rect, wtype, *args, **kwargs):
        """
        Creates a matplotlib.widgets widget
        :param rect: The rectangle of the position [left, bottom, width, height] in relative figure coordinates
        :param wtype: A type from matplotlib.widgets, eg. Button, Slider, TextBox, RadioButtons
        :param args: Positional arguments passed to the widget
        :param kwargs: Keyword arguments passed to the widget and events used for the widget
                       eg. if wtype is Slider, on_changed=f can be used as keyword argument

        """
        self.ax = plt.axes(rect)
        events = {}
        for k in list(kwargs.keys()):
            if k.startswith('on_'):
                events[k] = kwargs.pop(k)
        self.object = wtype(self.ax, *args, **kwargs)
        for k in events:
            if hasattr(self.object, k):
                getattr(self.object, k)(events[k]) 
Example #13
Source File: utils.py    From yolo_v2 with Apache License 2.0 6 votes vote down vote up
def visualize_voxel_spectral(points, vis_size=128):
  """Function to visualize voxel (spectral)."""
  points = np.rint(points)
  points = np.swapaxes(points, 0, 2)
  fig = p.figure(figsize=(1, 1), dpi=vis_size)
  verts, faces = measure.marching_cubes_classic(points, 0, spacing=(0.1, 0.1, 0.1))
  ax = fig.add_subplot(111, projection='3d')
  ax.plot_trisurf(
      verts[:, 0], verts[:, 1], faces, verts[:, 2], cmap='Spectral_r', lw=0.1)
  ax.set_axis_off()
  fig.tight_layout(pad=0)
  fig.canvas.draw()
  data = np.fromstring(
      fig.canvas.tostring_rgb(), dtype=np.uint8, sep='').reshape(
          vis_size, vis_size, 3)
  p.close('all')
  return data 
Example #14
Source File: evaluate.py    From text-classifier with Apache License 2.0 6 votes vote down vote up
def plot_pr(auc_score, precision, recall, label=None, figure_path=None):
    """绘制R/P曲线"""
    try:
        from matplotlib import pylab
        pylab.figure(num=None, figsize=(6, 5))
        pylab.xlim([0.0, 1.0])
        pylab.ylim([0.0, 1.0])
        pylab.xlabel('Recall')
        pylab.ylabel('Precision')
        pylab.title('P/R (AUC=%0.2f) / %s' % (auc_score, label))
        pylab.fill_between(recall, precision, alpha=0.5)
        pylab.grid(True, linestyle='-', color='0.75')
        pylab.plot(recall, precision, lw=1)
        pylab.savefig(figure_path)
    except Exception as e:
        print("save image error with matplotlib")
        pass 
Example #15
Source File: utils.py    From ndvr-dml with Apache License 2.0 6 votes vote down vote up
def plot_pr_curve(pr_curve_dml, pr_curve_base, title):
    """
      Function that plots the PR-curve.

      Args:
        pr_curve: the values of precision for each recall value
        title: the title of the plot
    """
    plt.figure(figsize=(16, 9))
    plt.plot(np.arange(0.0, 1.05, 0.05),
             pr_curve_base, color='r', marker='o', linewidth=3, markersize=10)
    plt.plot(np.arange(0.0, 1.05, 0.05),
             pr_curve_dml, color='b', marker='o', linewidth=3, markersize=10)
    plt.grid(True, linestyle='dotted')
    plt.xlabel('Recall', color='k', fontsize=27)
    plt.ylabel('Precision', color='k', fontsize=27)
    plt.yticks(color='k', fontsize=20)
    plt.xticks(color='k', fontsize=20)
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.title(title, color='k', fontsize=27)
    plt.tight_layout()
    plt.show() 
Example #16
Source File: utils.py    From Gun-Detector with Apache License 2.0 6 votes vote down vote up
def visualize_voxel_spectral(points, vis_size=128):
  """Function to visualize voxel (spectral)."""
  points = np.rint(points)
  points = np.swapaxes(points, 0, 2)
  fig = p.figure(figsize=(1, 1), dpi=vis_size)
  verts, faces = measure.marching_cubes_classic(points, 0, spacing=(0.1, 0.1, 0.1))
  ax = fig.add_subplot(111, projection='3d')
  ax.plot_trisurf(
      verts[:, 0], verts[:, 1], faces, verts[:, 2], cmap='Spectral_r', lw=0.1)
  ax.set_axis_off()
  fig.tight_layout(pad=0)
  fig.canvas.draw()
  data = np.fromstring(
      fig.canvas.tostring_rgb(), dtype=np.uint8, sep='').reshape(
          vis_size, vis_size, 3)
  p.close('all')
  return data 
Example #17
Source File: kNN.py    From statistical-learning-methods-note with Apache License 2.0 6 votes vote down vote up
def plotKChart(self, misClassDict, saveFigPath):
        kList = []
        misRateList = []
        for k, misClassNum in misClassDict.iteritems():
            kList.append(k)
            misRateList.append(1.0 - 1.0/k*misClassNum)

        fig = plt.figure(saveFigPath)
        plt.plot(kList, misRateList, 'r--')
        plt.title(saveFigPath)
        plt.xlabel('k Num.')
        plt.ylabel('Misclassified Rate')
        plt.legend(saveFigPath)
        plt.grid(True)
        plt.savefig(saveFigPath)
        plt.show()

################################### PART3 TEST ########################################
# 例子 
Example #18
Source File: elecsus_gui.py    From ElecSus with Apache License 2.0 5 votes vote down vote up
def __init__(self, parent, mainwin, ID):
		""" mainwin is the main panel so we can bind buttons to actions in the main frame """
		wx.Panel.__init__(self, parent, id=-1)
				
		self.fig = plt.figure(ID,facecolor=(240./255,240./255,240./255),figsize=(12.9,9.75),dpi=80)
		
		#self.ax = self.fig.add_subplot(111)
		
		# create the wx objects to hold the figure
		self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
		self.toolbar = Toolbar(self.canvas) #matplotlib toolbar (pan, zoom, save etc)
		#self.toolbar.Realize()
		
		# Create vertical sizer to hold figure and toolbar - dynamically expand with window size
		plot_sizer = wx.BoxSizer(wx.VERTICAL)
		plot_sizer.Add(self.canvas, 1, flag = wx.EXPAND|wx.ALL) #wx.TOP|wx.LEFT|wx.GROW)
		plot_sizer.Add(self.toolbar, 0, wx.EXPAND)

		mainwin.figs.append(self.fig)
		mainwin.fig_IDs.append(ID) # use an ID number to keep track of figures
		mainwin.canvases.append(self.canvas)

		# display some text in the middle of the window to begin with
		self.fig.text(0.5,0.5,'ElecSus GUI\n\nVersion '+__version__+'\n\nTo get started, use the panel on the right\nto either Compute a spectrum or Import some data...', ha='center',va='center')
		#self.fig.hold(False)
		
		self.SetSizer(plot_sizer)
		#self.Layout() #Fit() 
Example #19
Source File: elecsus_gui.py    From ElecSus with Apache License 2.0 5 votes vote down vote up
def OnDismiss(self):
		""" 
		Action to perform when the popup loses focus and is closed. 
		
		Gets the tick box values, updates the main plot and changes 
		the menu items to match the popup box
		"""
		# re=plot the figure
		#self.OnTicked(1)

		#self.mainwin.Refresh()

		self.Dismiss() 
Example #20
Source File: io_methods.py    From signaltrain with GNU General Public License v3.0 5 votes vote down vote up
def plot_valdata(x_val_cuda, knobs_val_cuda, y_val_cuda, y_val_hat_cuda, effect, \
	epoch, loss_val, file_prefix='val_data', num_plots=50, target_size=None):

	x_size = len(x_val_cuda.data.cpu().numpy()[0])
	if target_size is None:
		y_size = len(y_val_cuda.data.cpu().numpy()[0])
	else:
		y_size = target_size
	t_small = range(x_size-y_size, x_size)
	for plot_i in range(0, num_plots):
		x_val = x_val_cuda.data.cpu().numpy()
		knobs_w = effect.knobs_wc( knobs_val_cuda.data.cpu().numpy()[plot_i,:] )
		plt.figure(plot_i,figsize=(6,8))
		titlestr = f'{effect.name} Val data, epoch {epoch+1}, loss_val = {loss_val.item():.3e}\n'
		for i in range(len(effect.knob_names)):
		    titlestr += f'{effect.knob_names[i]} = {knobs_w[i]:.2f}'
		    if i < len(effect.knob_names)-1: titlestr += ', '
		plt.suptitle(titlestr)
		plt.subplot(3, 1, 1)
		plt.plot(x_val[plot_i, :], 'b', label='Input')
		plt.ylim(-1,1)
		plt.xlim(0,x_size)
		plt.legend()
		plt.subplot(3, 1, 2)
		y_val = y_val_cuda.data.cpu().numpy()
		plt.plot(t_small, y_val[plot_i, -y_size:], 'r', label='Target')
		plt.xlim(0,x_size)
		plt.ylim(-1,1)
		plt.legend()
		plt.subplot(3, 1, 3)
		plt.plot(t_small, y_val[plot_i, -y_size:], 'r', label='Target')
		y_val_hat = y_val_hat_cuda.data.cpu().numpy()
		plt.plot(t_small, y_val_hat[plot_i, -y_size:], c=(0,0.5,0,0.85), label='Predicted')
		plt.ylim(-1,1)
		plt.xlim(0,x_size)
		plt.legend()
		filename = file_prefix + '_' + str(plot_i) + '.png'
		savefig(filename)
	return 
Example #21
Source File: util.py    From Azimuth with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pvalhist(pv,numbins=50,linewidth=3.0,linespec='--r', figsize=[5,5]):    
    '''
    Plots normalized histogram, plus theoretical null-only line.
    '''    
    h2=pl.figure(figsize=figsize)      
    [nn,bins,patches]=pl.hist(pv,numbins,normed=True)    
    pl.plot([0, 1],[1,1],linespec,linewidth=linewidth) 
Example #22
Source File: utils.py    From Gun-Detector with Apache License 2.0 5 votes vote down vote up
def visualize_voxel_scatter(points, vis_size=128):
  """Function to visualize voxel (scatter)."""
  points = np.rint(points)
  points = np.swapaxes(points, 0, 2)
  fig = p.figure(figsize=(1, 1), dpi=vis_size)
  ax = fig.add_subplot(111, projection='3d')
  x = []
  y = []
  z = []
  (x_dimension, y_dimension, z_dimension) = points.shape
  for i in range(x_dimension):
    for j in range(y_dimension):
      for k in range(z_dimension):
        if points[i, j, k]:
          x.append(i)
          y.append(j)
          z.append(k)
  ax.scatter3D(x, y, z)
  ax.set_axis_off()
  fig.tight_layout(pad=0)
  fig.canvas.draw()
  data = np.fromstring(
      fig.canvas.tostring_rgb(), dtype=np.uint8, sep='').reshape(
          vis_size, vis_size, 3)
  p.close('all')
  return data 
Example #23
Source File: io_methods.py    From signaltrain with GNU General Public License v3.0 5 votes vote down vote up
def plot_spectrograms(model, mag_val, mag_val_hat):
	'''
	Routine for plotting magnitude and phase spectorgrams
	'''
	plt.figure(1)
	plt.imshow(mag_val.data.cpu().numpy()[0, :, :].T, aspect='auto', origin='lower')
	plt.title('Initial magnitude')
	savefig('mag.png')
	plt.figure(2)  # <---- Check this out! Some "sub-harmonic" content is generated for the compressor if the analysis weights make only small perturbations
	plt.imshow(mag_val_hat.data.cpu().numpy()[0, :, :].T, aspect='auto', origin='lower')
	plt.title('Processed magnitude')
	savefig('mag_hat.png')

	#if isinstance(model, nn_proc.AsymMPAEC):     # Plot the spectrograms
	plt.matshow(model.mpaec.dft_analysis.conv_analysis_real.weight.data.cpu().numpy().astype(float)[:, 0, :] + 1)
	plt.title('Conv-Analysis Real')
	savefig('conv_anal_real.png')
	plt.matshow(model.mpaec.dft_analysis.conv_analysis_imag.weight.data.cpu().numpy().astype(float)[:, 0, :])
	plt.title('Conv-Analysis Imag')
	savefig('conv_anal_imag.png')
	plt.matshow(model.mpaec.dft_synthesis.conv_synthesis_real.weight.data.cpu().numpy().astype(float)[:, 0, :])
	plt.title('Conv-Synthesis Real')
	savefig('conv_synth_real.png')
	plt.matshow(model.mpaec.dft_synthesis.conv_synthesis_imag.weight.data.cpu().numpy().astype(float)[:, 0, :])
	plt.title('Conv-Synthesis Imag')
	savefig('conv_synth_imag.png')

	return 
Example #24
Source File: lr_finder.py    From signaltrain with GNU General Public License v3.0 5 votes vote down vote up
def lrfind(model, dataloader, optimizer, calc_loss, start=1e-6, stop=4e-3, num_lrs=150, to_screen=False):
    """ Learning Rate finder.  See leslie howard, sylvian gugger & jeremy howard's work """
    print("Running LR Find:",end="",flush=True)

    lrs, losses = [], []
    lr_tries = np.logspace(np.log10(start), np.log10(stop), num_lrs)
    ind, count, repeat = 0, 0, 3
    for x, y, knobs in dataloader:
        count+=1
        if ind >= len(lr_tries):
            break
        lr_try = lr_tries[ind]
        if count % repeat ==0:  # repeat over this many data points per lr value
            ind+=1
            print(".",sep="",end="",flush=True)
        optimizer.param_groups[0]['lr'] = lr_try

        #x_cuda, y_cuda, knobs_cuda = datagen.new()
        x_cuda, y_cuda, knobs_cuda = x.to(device), y.to(device), knobs.to(device)
        x_hat, mag, mag_hat = model.forward(x_cuda, knobs_cuda)
        loss = calc_loss(x_hat.float() ,y_cuda.float(), mag.float())
        lrs.append(lr_try)
        losses.append(loss.item())
        optimizer.zero_grad()
        loss.backward()
        model.clip_grad_norm_()
        optimizer.step()

    plt.figure(1)
    plt.semilogx(lrs,losses)
    if to_screen:
        plt.show()
    else:
        outfile = 'lrfind.png'
        plt.savefig(outfile)
        plt.close(plt.gcf())
        print("\nLR Find finished. See "+outfile)
    return 
Example #25
Source File: convolutional_sccs.py    From tick with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_learning_curves(self, hyperparameter):
        if hyperparameter == "TV":
            C = self.C_tv_history
        elif hyperparameter == "Group L1":
            C = self.C_group_l1_history
        else:
            raise ValueError("hyperparameter value should be either `TV` or"
                             " `Group L1`")
        x = np.log10(C)
        order = np.argsort(x)
        m = np.array(self.kfold_mean_train_scores)[order]
        sd = np.array(self.kfold_sd_train_scores)[order]
        fig = plt.figure()
        ax = plt.gca()
        p1 = ax.plot(x[order], m)
        p2 = ax.fill_between(x[order], m - sd, m + sd, alpha=.3)
        min_point_train = np.min(m - sd)
        m = np.array(self.kfold_mean_test_scores)[order]
        sd = np.array(self.kfold_sd_test_scores)[order]
        p3 = ax.plot(x[order], m)
        p4 = ax.fill_between(x[order], m - sd, m + sd, alpha=.3)
        min_point_test = np.min(m - sd)
        min_point = min(min_point_train, min_point_test)
        p5 = plt.scatter(np.log10(C), min_point * np.ones_like(C))

        ax.legend([(p1[0], p2), (p3[0], p4), p5],
                  ['train score', 'test score', 'tested hyperparameters'],
                  loc='lower right')
        ax.set_title('Learning curves')
        ax.set_xlabel('C %s (log scale)' % hyperparameter)
        ax.set_ylabel('Loss')
        return fig, ax 
Example #26
Source File: evaluate.py    From text-classifier with Apache License 2.0 5 votes vote down vote up
def plt_history(history, output_dir='output/', model_name='cnn'):
    try:
        from matplotlib import pyplot
        model_name = model_name.upper()
        fig1 = pyplot.figure()
        pyplot.plot(history.history['loss'], 'r', linewidth=3.0)
        pyplot.plot(history.history['val_loss'], 'b', linewidth=3.0)
        pyplot.legend(['Training loss', 'Validation Loss'], fontsize=18)
        pyplot.xlabel('Epochs ', fontsize=16)
        pyplot.ylabel('Loss', fontsize=16)
        pyplot.title('Loss Curves :' + model_name, fontsize=16)
        loss_path = output_dir + model_name + '_loss.png'
        fig1.savefig(loss_path)
        print('save to:', loss_path)
        # pyplot.show()

        fig2 = pyplot.figure()
        pyplot.plot(history.history['acc'], 'r', linewidth=3.0)
        pyplot.plot(history.history['val_acc'], 'b', linewidth=3.0)
        pyplot.legend(['Training Accuracy', 'Validation Accuracy'], fontsize=18)
        pyplot.xlabel('Epochs ', fontsize=16)
        pyplot.ylabel('Accuracy', fontsize=16)
        pyplot.title('Accuracy Curves : ' + model_name, fontsize=16)
        acc_path = output_dir + model_name + '_accuracy.png'
        fig2.savefig(acc_path)
        print('save to:', acc_path)
    except Exception as e:
        print("save image error with matplotlib")
        pass 
Example #27
Source File: deepjdot_svhn_mnist.py    From deepJDOT with MIT License 5 votes vote down vote up
def tsne_plot(xs, xt, xs_label, xt_label, subset=True, title=None, pname=None):
    num_test=1000
    import matplotlib.cm as cm
    if subset:
        combined_imgs = np.vstack([xs[0:num_test, :], xt[0:num_test, :]])
        combined_labels = np.vstack([xs_label[0:num_test, :],xt_label[0:num_test, :]])
        combined_labels = combined_labels.astype('int')
        combined_domain = np.vstack([np.zeros((num_test,1)),np.ones((num_test,1))])
    
    from sklearn.manifold import TSNE
    tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=3000)
    source_only_tsne = tsne.fit_transform(combined_imgs)
    plt.figure(figsize=(15,15))
    plt.scatter(source_only_tsne[:num_test,0], source_only_tsne[:num_test,1], c=combined_labels[:num_test].argmax(1),
                s=50, alpha=0.5,marker='o', cmap=cm.jet, label='source')
    plt.scatter(source_only_tsne[num_test:,0], source_only_tsne[num_test:,1], c=combined_labels[num_test:].argmax(1),
                s=50, alpha=0.5,marker='+',cmap=cm.jet,label='target')
    plt.axis('off')
    plt.legend(loc='best')
    plt.title(title)
    if filesave:
        plt.savefig(os.path.join(pname,title+'.png'),bbox_inches='tight', pad_inches = 0,
                    format='png')
    else:
        plt.savefig(title+'.png')
    plt.close() 


#%% source model 
Example #28
Source File: utils.py    From yolo_v2 with Apache License 2.0 5 votes vote down vote up
def visualize_voxel_scatter(points, vis_size=128):
  """Function to visualize voxel (scatter)."""
  points = np.rint(points)
  points = np.swapaxes(points, 0, 2)
  fig = p.figure(figsize=(1, 1), dpi=vis_size)
  ax = fig.add_subplot(111, projection='3d')
  x = []
  y = []
  z = []
  (x_dimension, y_dimension, z_dimension) = points.shape
  for i in range(x_dimension):
    for j in range(y_dimension):
      for k in range(z_dimension):
        if points[i, j, k]:
          x.append(i)
          y.append(j)
          z.append(k)
  ax.scatter3D(x, y, z)
  ax.set_axis_off()
  fig.tight_layout(pad=0)
  fig.canvas.draw()
  data = np.fromstring(
      fig.canvas.tostring_rgb(), dtype=np.uint8, sep='').reshape(
          vis_size, vis_size, 3)
  p.close('all')
  return data 
Example #29
Source File: mpl.py    From spotpy with MIT License 5 votes vote down vote up
def __init__(self, setup):
        """
        Creates the GUI

        :param setup: A spotpy setup
        """
        self.fig = plt.figure(type(setup).__name__)
        self.ax = plt.axes([0.05, 0.1, 0.65, 0.85])
        self.button_run = Widget([0.75, 0.01, 0.1, 0.03], Button, 'Simulate', on_clicked=self.run)
        self.button_clear = Widget([0.87, 0.01, 0.1, 0.03], Button, 'Clear plot', on_clicked=self.clear)
        self.parameter_values = {}
        self.setup = setup
        self.sliders = self._make_widgets()
        self.lines = []
        self.clear() 
Example #30
Source File: elecsus_gui.py    From ElecSus with Apache License 2.0 5 votes vote down vote up
def OnPlotHold(self,event):
		""" 
		Toggle plot hold (keep data on updating figure) on/off
		Allows multiple data sets to be shown on same plot
		"""
		#self.PlotHold = bool(event.IsChecked())
		#self.figs[0].hold(self.PlotHold)
		dlg = wx.MessageDialog(self, "Not implemented yet...", "No no no", wx.OK)
		dlg.ShowModal()