Python matplotlib.pyplot.clf() Examples

The following are 30 code examples of matplotlib.pyplot.clf(). 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.pyplot , or try the search function .
Example #1
Source File: SimplicialComplex.py    From OpenTDA with Apache License 2.0 8 votes vote down vote up
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show() 
Example #2
Source File: FilteredSimplicialComplex.py    From OpenTDA with Apache License 2.0 8 votes vote down vote up
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show() 
Example #3
Source File: plotting.py    From OpenTDA with Apache License 2.0 6 votes vote down vote up
def drawComplex(data, ph, axes=[-6, 8, -6, 6]):
    plt.clf()
    plt.axis(axes)  # axes = [x1, x2, y1, y2]
    plt.scatter(data[:, 0], data[:, 1])  # plotting just for clarity
    for i, txt in enumerate(data):
        plt.annotate(i, (data[i][0] + 0.05, data[i][1]))  # add labels

    # add lines for edges
    for edge in [e for e in ph.ripsComplex if len(e) == 2]:
        # print(edge)
        pt1, pt2 = [data[pt] for pt in [n for n in edge]]
        # plt.gca().add_line(plt.Line2D(pt1,pt2))
        line = plt.Polygon([pt1, pt2], closed=None, fill=None, edgecolor='r')
        plt.gca().add_line(line)

    # add triangles
    for triangle in [t for t in ph.ripsComplex if len(t) == 3]:
        pt1, pt2, pt3 = [data[pt] for pt in [n for n in triangle]]
        line = plt.Polygon([pt1, pt2, pt3], closed=False,
                           color="blue", alpha=0.3, fill=True, edgecolor=None)
        plt.gca().add_line(line)
    plt.show() 
Example #4
Source File: plot_distributions.py    From AMLSim with Apache License 2.0 6 votes vote down vote up
def plot_wcc_distribution(_g, _plot_img):
    """Plot weakly connected components size distributions
    :param _g: Transaction graph
    :param _plot_img: WCC size distribution image (log-log plot)
    :return:
    """
    all_wcc = nx.weakly_connected_components(_g)
    wcc_sizes = Counter([len(wcc) for wcc in all_wcc])
    size_seq = sorted(wcc_sizes.keys())
    size_hist = [wcc_sizes[x] for x in size_seq]

    plt.figure(figsize=(16, 12))
    plt.clf()
    plt.loglog(size_seq, size_hist, 'ro-')
    plt.title("WCC Size Distribution")
    plt.xlabel("Size")
    plt.ylabel("Number of WCCs")
    plt.savefig(_plot_img) 
Example #5
Source File: utility_functions.py    From MaskTrack with MIT License 6 votes vote down vote up
def plot_precision_recall(train_precision, train_recall, val_precision=None, val_recall=None, resume_epoch = 0, nepochs = -1, save_dir=None, online=False, seq_name = None, object_id = -1):
    assert len(range(resume_epoch + 1, nepochs+1)) == len(train_precision)
    xaxis = range(resume_epoch + 1, nepochs+1)
    plt.plot(xaxis, train_precision, label = "train_precision")
    plt.plot(xaxis, train_recall, label = "train_recall")

    if not online:
        plt.plot(xaxis, val_precision, label = "val_precision")
        plt.plot(xaxis, val_recall, label = "val_recall")

    plt.legend()

    if online:
        plt.savefig(os.path.join(save_dir, 'plots', seq_name, str(object_id),'accuracies.png'))
    else:
        plt.savefig(os.path.join(save_dir, 'plots', 'accuracies.png'))

    plt.clf() 
Example #6
Source File: malware.py    From trees with Apache License 2.0 6 votes vote down vote up
def classify(self, features, show=False):
        recs, _ = features.shape
        result_shape = (features.shape[0], len(self.root))
        scores = np.zeros(result_shape)
        print scores.shape
        R = Record(np.arange(recs, dtype=int), features)

        for i, T in enumerate(self.root):
            for idxs, result in classify(T, R):
                for idx in idxs.indexes():
                    scores[idx, i] = float(result[0]) / sum(result.values())


        if show:
            plt.cla()
            plt.clf()
            plt.close()

            plt.imshow(scores, cmap=plt.cm.gray)
            plt.title('Scores matrix')
            plt.savefig(r"../scratch/tree_scores.png", bbox_inches='tight')
        
        return scores 
Example #7
Source File: plot.py    From tensorflow_end2end_speech_recognition with MIT License 6 votes vote down vote up
def plot_loss(train_losses, dev_losses, steps, save_path):
    """Save history of training & dev loss as figure.
    Args:
        train_losses (list): train losses
        dev_losses (list): dev losses
        steps (list): steps
    """
    # Save as csv file
    loss_graph = np.column_stack((steps, train_losses, dev_losses))
    if os.path.isfile(os.path.join(save_path, "ler.csv")):
        os.remove(os.path.join(save_path, "ler.csv"))
    np.savetxt(os.path.join(save_path, "loss.csv"), loss_graph, delimiter=",")

    # TODO: error check for inf loss

    # Plot & save as png file
    plt.clf()
    plt.plot(steps, train_losses, blue, label="Train")
    plt.plot(steps, dev_losses, orange, label="Dev")
    plt.xlabel('step', fontsize=12)
    plt.ylabel('loss', fontsize=12)
    plt.legend(loc="upper right", fontsize=12)
    if os.path.isfile(os.path.join(save_path, "loss.png")):
        os.remove(os.path.join(save_path, "loss.png"))
    plt.savefig(os.path.join(save_path, "loss.png"), dvi=500) 
Example #8
Source File: plot_images_grid.py    From Deep-SAD-PyTorch with MIT License 6 votes vote down vote up
def plot_images_grid(x: torch.tensor, export_img, title: str = '', nrow=8, padding=2, normalize=False, pad_value=0):
    """Plot 4D Tensor of images of shape (B x C x H x W) as a grid."""

    grid = make_grid(x, nrow=nrow, padding=padding, normalize=normalize, pad_value=pad_value)
    npgrid = grid.cpu().numpy()

    plt.imshow(np.transpose(npgrid, (1, 2, 0)), interpolation='nearest')

    ax = plt.gca()
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)

    if not (title == ''):
        plt.title(title)

    plt.savefig(export_img, bbox_inches='tight', pad_inches=0.1)
    plt.clf() 
Example #9
Source File: visualize_flow.py    From residual-flows with MIT License 6 votes vote down vote up
def visualize_transform(
    potential_or_samples, prior_sample, prior_density, transform=None, inverse_transform=None, samples=True, npts=100,
    memory=100, device="cpu"
):
    """Produces visualization for the model density and samples from the model."""
    plt.clf()
    ax = plt.subplot(1, 3, 1, aspect="equal")
    if samples:
        plt_samples(potential_or_samples, ax, npts=npts)
    else:
        plt_potential_func(potential_or_samples, ax, npts=npts)

    ax = plt.subplot(1, 3, 2, aspect="equal")
    if inverse_transform is None:
        plt_flow(prior_density, transform, ax, npts=npts, device=device)
    else:
        plt_flow_density(prior_density, inverse_transform, ax, npts=npts, memory=memory, device=device)

    ax = plt.subplot(1, 3, 3, aspect="equal")
    if transform is not None:
        plt_flow_samples(prior_sample, transform, ax, npts=npts, memory=memory, device=device) 
Example #10
Source File: chart.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def image(path: str, costs: Dict[str, int]) -> str:
    ys = ['0', '1', '2', '3', '4', '5', '6', '7+', 'X']
    xs = [costs.get(k, 0) for k in ys]
    sns.set_style('white')
    sns.set(font='Concourse C3', font_scale=3)
    g = sns.barplot(ys, xs, palette=['#cccccc'] * len(ys))
    g.axes.yaxis.set_ticklabels([])
    rects = g.patches
    sns.set(font='Concourse C3', font_scale=2)
    for rect, label in zip(rects, xs):
        if label == 0:
            continue
        height = rect.get_height()
        g.text(rect.get_x() + rect.get_width()/2, height + 0.5, label, ha='center', va='bottom')
    g.margins(y=0, x=0)
    sns.despine(left=True, bottom=True)
    g.get_figure().savefig(path, transparent=True, pad_inches=0, bbox_inches='tight')
    plt.clf() # Clear all data from matplotlib so it does not persist across requests.
    return path 
Example #11
Source File: naive-policy-gradient.py    From Deep-reinforcement-learning-with-pytorch with MIT License 6 votes vote down vote up
def plot_durations(episode_durations):
    plt.ion()
    plt.figure(2)
    plt.clf()
    duration_t = torch.FloatTensor(episode_durations)
    plt.title('Training')
    plt.xlabel('Episodes')
    plt.ylabel('Duration')
    plt.plot(duration_t.numpy())

    if len(duration_t) >= 100:
        means = duration_t.unfold(0,100,1).mean(1).view(-1)
        means = torch.cat((torch.zeros(99), means))
        plt.plot(means.numpy())

    plt.pause(0.00001) 
Example #12
Source File: LSDMap_KnickpointPlotting_old.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def DEBUG_print_KDE(self):
        """
            This function is used to print one ksn profile per river to check the effect of the different filters on the dataset
            BG - 12/01/2018
        """
        plt.clf()
        print("I will now print ksn(chi) with the different KDE")
        svdir = self.fpath+'river_plots/'
        if not os.path.isdir(svdir):
            os.makedirs(svdir)

        for SK in self.df_kp_raw["source_key"].unique():
            print("printing river: " +str(SK))

            # Selecting the river
            df = self.df_kp_raw[self.df_kp_raw["source_key"] == SK]

            fig = plt.figure(1, facecolor='white',figsize=(9,5))

            gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95)
            ax1 = fig.add_subplot(gs[0:100,0:100])

            ax1.scatter(df["dksn/dchi"], df["KDE"], c = "k", s = 1, marker = "+", label = "ksn")

            ax1.set_xlabel(r'$ \frac{dk_{sn}}{\chi}$')
            ax1.set_ylabel(r'$ KDE_pdf $')

            plt.savefig(svdir + self.fprefix + "_KDE_SK_" +str(SK)+".png", dpi = 300)
            plt.clf() 
Example #13
Source File: common.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _check_plot_works(f, filterwarnings='always', **kwargs):
    import matplotlib.pyplot as plt
    ret = None
    with warnings.catch_warnings():
        warnings.simplefilter(filterwarnings)
        try:
            try:
                fig = kwargs['figure']
            except KeyError:
                fig = plt.gcf()

            plt.clf()

            ax = kwargs.get('ax', fig.add_subplot(211))  # noqa
            ret = f(**kwargs)

            assert_is_valid_plot_return_object(ret)

            try:
                kwargs['ax'] = fig.add_subplot(212)
                ret = f(**kwargs)
            except Exception:
                pass
            else:
                assert_is_valid_plot_return_object(ret)

            with ensure_clean(return_filelike=True) as path:
                plt.savefig(path)
        finally:
            tm.close(fig)

        return ret 
Example #14
Source File: LSDMap_KnickpointPlotting_old.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def DEBUG_print_ksn_filters(self):
        """
            This function is used to print one ksn profile per river to check the effect of the different filters on the dataset
            BG - 12/01/2018
        """
        plt.clf()
        print("I will now print ksn(chi) with the different filter")
        svdir = self.fpath+'river_plots/'
        if not os.path.isdir(svdir):
            os.makedirs(svdir)

        for SK in self.df_river["source_key"].unique():
            print("printing river: " +str(SK))

            # Selecting the river
            df = self.df_river[self.df_river["source_key"] == SK]

            fig = plt.figure(1, facecolor='white',figsize=(9,5))

            gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95)
            ax1 = fig.add_subplot(gs[0:100,0:100])

            ax1.scatter(df["chi"], df["m_chi"], c = "r", s = 1, marker = "o", label = "ksn")
            ax1.scatter(df["chi"], df["lumped_ksn"], c = "g", s = 1, marker = "s", label = "lumped ksn")
            ax1.scatter(df["chi"], df["TVD_ksn"], c = "k", s = 1, marker = "+", label = "TVD ksn")

            ax1.legend()

            ax1.set_xlabel(r'$ \chi$')
            ax1.set_ylabel(r'$ k_{sn}$')

            plt.savefig(svdir + self.fprefix + "_ksn_SK_" +str(SK)+".png", dpi = 300)
            plt.clf() 
Example #15
Source File: plot_hillslope_morphology.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def JoyPlot(HillslopeData,Column,XLabel,Colour,Outfile,BinMin,BinSpacing,BinMax):
    
    CreateFigure(AspectRatio=0.5,FigSizeFormat="small")
    Ax = plt.subplot(111)
    
    Basins = np.sort(HillslopeData.BasinID.unique())
    
    for Basin in range(0,NoBasins):
        #Get hillslopes for basin
        BasinHillslopeData = HillslopeData[HillslopeData.BasinID == Basins[Basin]]

        #create the PDF
        freq, BinEdges = np.histogram(BasinHillslopeData[Column],bins=np.arange(BinMin,BinMax+BinSpacing,BinSpacing))
        BinMidpoints = BinEdges+BinSpacing*0.5
        freq_norm = freq.astype(np.float)/float(np.max(freq))

        #plot, offset by Basin #
        plt.plot(BinMidpoints[:-1],freq_norm-Basin,'k-',linewidth=1)
        plt.fill_between(BinMidpoints[:-1],freq_norm-Basin,-Basin,color=Colour)
    
    if np.abs(BinMin) < np.abs(BinMax):
        plt.xlim(BinMin,BinMax)
    else:
        plt.xlim(BinMax,BinMin)
        BinSpacing *= -1
        
    plt.xlabel(XLabel)
    plt.text(-BinSpacing,0,"North-West",rotation=90,verticalalignment='top')
    plt.text(-BinSpacing,-(NoBasins-1),"South-East",rotation=90,verticalalignment='bottom')
    
    #only display bottom axis
    Ax.spines['right'].set_visible(False)
    Ax.spines['top'].set_visible(False)
    Ax.spines['left'].set_visible(False)
    Ax.yaxis.set_visible(False)
    
    plt.tight_layout(rect=[0.02, 0.02, 0.98, 0.98])
    plt.savefig(PlotDirectory+Outfile, dpi=300)
    plt.clf() 
Example #16
Source File: squad_evaluation.py    From FARM with Apache License 2.0 5 votes vote down vote up
def histogram_na_prob(na_probs, qid_list, image_dir, name):
  if not qid_list:
    return
  x = [na_probs[k] for k in qid_list]
  weights = np.ones_like(x) / float(len(x))
  plt.hist(x, weights=weights, bins=20, range=(0.0, 1.0))
  plt.xlabel('Model probability of no-answer')
  plt.ylabel('Proportion of dataset')
  plt.title('Histogram of no-answer probability: %s' % name)
  plt.savefig(os.path.join(image_dir, 'na_prob_hist_%s.png' % name))
  plt.clf() 
Example #17
Source File: squad_evaluation.py    From FARM with Apache License 2.0 5 votes vote down vote up
def plot_pr_curve(precisions, recalls, out_image, title):
  plt.step(recalls, precisions, color='b', alpha=0.2, where='post')
  plt.fill_between(recalls, precisions, step='post', alpha=0.2, color='b')
  plt.xlabel('Recall')
  plt.ylabel('Precision')
  plt.xlim([0.0, 1.05])
  plt.ylim([0.0, 1.05])
  plt.title(title)
  plt.savefig(out_image)
  plt.clf() 
Example #18
Source File: evaluation.py    From tsinfer with GNU General Public License v3.0 5 votes vote down vote up
def save_figure(basename):
    plt.savefig(basename + "." + _output_format)
    plt.clf() 
Example #19
Source File: display_methods.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def update_plot(self, i):
        """
        This is our animation function.
        For line graphs, redraw the whole thing.
        """
        plt.clf()
        (data_points, varieties) = self.data_func()
        self.draw_graph(data_points, varieties)
        self.show() 
Example #20
Source File: evaluate.py    From ssai-cnn with MIT License 5 votes vote down vote up
def draw_pre_rec_curve(pre_rec, breakeven_pt):
    plt.clf()
    plt.plot(pre_rec[:, 0], pre_rec[:, 1])
    plt.plot(breakeven_pt[0], breakeven_pt[1],
             'x', label='breakeven recall: %f' % (breakeven_pt[1]))
    plt.ylabel('recall')
    plt.xlabel('precision')
    plt.ylim([0.0, 1.1])
    plt.xlim([0.0, 1.1])
    plt.legend(loc='lower left')
    plt.grid(linestyle='--') 
Example #21
Source File: draw_loss.py    From ssai-cnn with MIT License 5 votes vote down vote up
def draw_loss(logfile, outfile):
    train_epoch_loss = []
    valid_epoch_loss = []
    for line in open(logfile):
        line = line.strip()
        if 'epoch:' not in line:
            continue
        epoch = int(re.search('epoch:([0-9]+)', line).groups()[0])
        if 'iter' not in line and 'train loss' in line:
            tr_l = float(re.search('loss:([0-9\.e-]+)', line).groups()[0])
            train_epoch_loss.append([epoch, tr_l])
        if 'iter' not in line and 'validate loss' in line:
            va_l = float(re.search('loss:([0-9\.e-]+)', line).groups()[0])
            valid_epoch_loss.append([epoch, va_l])

    train_epoch_loss = np.asarray(train_epoch_loss)
    valid_epoch_loss = np.asarray(valid_epoch_loss)

    plt.clf()
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.plot(train_epoch_loss[:, 0], train_epoch_loss[:, 1], c='b',
             label='training loss', marker='x')

    if valid_epoch_loss.shape[0] > 2:
        plt.plot(valid_epoch_loss[:, 0], valid_epoch_loss[:, 1], c='r',
                 label='validation loss', marker='x')

    plt.legend(loc='upper right')
    plt.savefig(outfile, bbox_inches='tight') 
Example #22
Source File: plot.py    From tensorflow_end2end_speech_recognition with MIT License 5 votes vote down vote up
def plot_ler(train_lers, dev_lers, steps, label_type, save_path):
    """Save history of training & dev LERs as figure.
    Args:
        train_lers (list): train losses
        dev_lers (list): dev losses
        steps (list): steps
    """
    if 'word' in label_type:
        name = 'WER'
    elif 'char' in label_type or 'kana' in label_type or 'kanji' in label_type:
        name = 'CER'
    elif 'phone' in label_type:
        name = 'PER'
    else:
        name = 'LER'

    # Save as csv file
    loss_graph = np.column_stack((steps, train_lers, dev_lers))
    if os.path.isfile(os.path.join(save_path, "ler.csv")):
        os.remove(os.path.join(save_path, "ler.csv"))
    np.savetxt(os.path.join(save_path, "ler.csv"), loss_graph, delimiter=",")

    # Plot & save as png file
    plt.clf()
    plt.plot(steps, train_lers, blue, label="Train")
    plt.plot(steps, dev_lers, orange, label="Dev")
    plt.xlabel('step', fontsize=12)
    plt.ylabel(name, fontsize=12)
    plt.legend(loc="upper right", fontsize=12)
    if os.path.isfile(os.path.join(save_path, name.lower() + '.png')):
        os.remove(os.path.join(save_path, name.lower() + '.png'))
    plt.savefig(os.path.join(save_path, name.lower() + '.png'), dvi=500) 
Example #23
Source File: evaluate_single.py    From ssai-cnn with MIT License 5 votes vote down vote up
def draw_pre_rec_curve(pre_rec, breakeven_pt):
    plt.clf()
    plt.plot(pre_rec[:, 0], pre_rec[:, 1])
    plt.plot(breakeven_pt[0], breakeven_pt[1],
             'x', label='breakeven recall: %f' % (breakeven_pt[1]))
    plt.ylabel('recall')
    plt.xlabel('precision')
    plt.ylim([0.0, 1.1])
    plt.xlim([0.0, 1.1])
    plt.legend(loc='lower left')
    plt.grid(linestyle='--') 
Example #24
Source File: plot_distributions.py    From AMLSim with Apache License 2.0 5 votes vote down vote up
def plot_diameter(dia_csv, _plot_img):
    """Plot the diameter and the average of largest distance transitions
    :param dia_csv: Diameter transition CSV file
    :param _plot_img: Output image file
    :return:
    """
    x = list()
    dia = list()
    aver = list()

    with open(dia_csv, "r") as _rf:
        reader = csv.reader(_rf)
        next(reader)
        for row in reader:
            step = int(row[0])
            d = float(row[1])
            a = float(row[2])
            x.append(step)
            dia.append(d)
            aver.append(a)

    plt.figure(figsize=(16, 12))
    plt.clf()
    plt.ylim(0, max(dia) + 1)
    p_d = plt.plot(x, dia, "r")
    p_a = plt.plot(x, aver, "b")
    plt.legend((p_d[0], p_a[0]), ("Diameter", "Average"))
    plt.title("Diameter and Average Distance")
    plt.xlabel("Simulation step")
    plt.ylabel("Distance")
    plt.savefig(_plot_img) 
Example #25
Source File: plot_distributions.py    From AMLSim with Apache License 2.0 5 votes vote down vote up
def plot_clustering_coefficient(_g, _plot_img, interval=30):
    """Plot the clustering coefficient transition
    :param _g: Transaction graph
    :param _plot_img: Output image file
    :param interval: Simulation step interval for plotting
    (it takes too much time to compute clustering coefficient)
    :return:
    """
    date_list = get_date_list(_g)

    gg = nx.Graph()
    edges = defaultdict(list)
    for k, v in nx.get_edge_attributes(_g, "date").items():
        e = (k[0], k[1])
        edges[v].append(e)

    sample_dates = list()
    values = list()
    for i, t in enumerate(date_list):
        gg.add_edges_from(edges[t])
        if i % interval == 0:
            v = nx.average_clustering(gg) if gg.number_of_nodes() else 0.0
            sample_dates.append(t)
            values.append(v)
            print("Clustering coefficient at %s: %f" % (str(t), v))

    plt.figure(figsize=(16, 12))
    plt.clf()
    plt.plot(sample_dates, values, 'bo-')
    plt.title("Clustering Coefficient Transition")
    plt.xlabel("date")
    plt.ylabel("Clustering Coefficient")
    plt.savefig(_plot_img) 
Example #26
Source File: plot_distributions.py    From AMLSim with Apache License 2.0 5 votes vote down vote up
def plot_tx_count(_g, _plot_img):
    """Plot the number of normal and SAR transactions
    :param _g: Transaction graph
    :param _plot_img: Output image file path
    """
    date_list = get_date_list(_g)
    normal_tx_count = Counter()
    sar_tx_count = Counter()

    for _, _, attr in _g.edges(data=True):
        is_sar = attr["is_sar"]
        date = attr["date"]
        if is_sar:
            sar_tx_count[date] += 1
        else:
            normal_tx_count[date] += 1

    normal_tx_list = [normal_tx_count[d] for d in date_list]
    sar_tx_list = [sar_tx_count[d] for d in date_list]

    plt.figure(figsize=(16, 12))
    plt.clf()
    p_n = plt.plot(date_list, normal_tx_list, "b")
    p_f = plt.plot(date_list, sar_tx_list, "r")
    plt.yscale('log')
    plt.legend((p_n[0], p_f[0]), ("Normal", "SAR"))
    plt.title("Number of transactions per step")
    plt.xlabel("Simulation step")
    plt.ylabel("Number of transactions")
    plt.savefig(_plot_img) 
Example #27
Source File: cudaHelperFunctions.py    From Action-Recognition with MIT License 5 votes vote down vote up
def PlotAccuracies(l1, l2, name="accuracies.png"):
	plt.clf()
	plt.cla()
	plt.close()
	plt.plot(l1)
	plt.plot(l2)
	plt.show()
	plt.savefig(name) 
Example #28
Source File: cudaHelperFunctions.py    From Action-Recognition with MIT License 5 votes vote down vote up
def PlotLoss(l,name = 'currentLoss.png'):
	plt.clf()
	plt.cla()
	plt.close()
	plt.plot(l)			
	plt.show()
	plt.savefig(name) 
Example #29
Source File: cudaHelperFunctions.py    From Action-Recognition with MIT License 5 votes vote down vote up
def PlotLoss(l,name = 'currentLoss.png'):
	plt.clf()
	plt.cla()
	plt.close()
	plt.plot(l)			
	plt.show()
	plt.savefig(name) 
Example #30
Source File: cudaHelperFunctions.py    From Action-Recognition with MIT License 5 votes vote down vote up
def PlotAccuracies(l1, l2, name="accuracies.png"):
	plt.clf()
	plt.cla()
	plt.close()
	plt.plot(l1)
	plt.plot(l2)
	plt.show()
	plt.savefig(name)