Python matplotlib.pyplot.plot() Examples

The following are 30 code examples of matplotlib.pyplot.plot(). 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: data_augmentation.py    From Sound-Recognition-Tutorial with Apache License 2.0 10 votes vote down vote up
def demo_plot():
    audio = './data/esc10/audio/Dog/1-30226-A.ogg'
    y, sr = librosa.load(audio, sr=44100)
    y_ps = librosa.effects.pitch_shift(y, sr, n_steps=6)   # n_steps控制音调变化尺度
    y_ts = librosa.effects.time_stretch(y, rate=1.2)   # rate控制时间维度的变换尺度
    plt.subplot(311)
    plt.plot(y)
    plt.title('Original waveform')
    plt.axis([0, 200000, -0.4, 0.4])
    # plt.axis([88000, 94000, -0.4, 0.4])
    plt.subplot(312)
    plt.plot(y_ts)
    plt.title('Time Stretch transformed waveform')
    plt.axis([0, 200000, -0.4, 0.4])
    plt.subplot(313)
    plt.plot(y_ps)
    plt.title('Pitch Shift transformed waveform')
    plt.axis([0, 200000, -0.4, 0.4])
    # plt.axis([88000, 94000, -0.4, 0.4])
    plt.tight_layout()
    plt.show() 
Example #2
Source File: util.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def compute_roc(y_true, y_pred, plot=False):
    """
    TODO
    :param y_true: ground truth
    :param y_pred: predictions
    :param plot:
    :return:
    """
    fpr, tpr, _ = roc_curve(y_true, y_pred)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
Example #3
Source File: dataset.py    From neural-combinatorial-optimization-rl-tensorflow with MIT License 8 votes vote down vote up
def visualize_2D_trip(self, trip):
        plt.figure(figsize=(30,30))
        rcParams.update({'font.size': 22})

        # Plot cities
        plt.scatter(trip[:,0], trip[:,1], s=200)

        # Plot tour
        tour=np.array(list(range(len(trip))) + [0])
        X = trip[tour, 0]
        Y = trip[tour, 1]
        plt.plot(X, Y,"--", markersize=100)

        # Annotate cities with order
        labels = range(len(trip))
        for i, (x, y) in zip(labels,(zip(X,Y))):
            plt.annotate(i,xy=(x, y))  

        plt.xlim(0,100)
        plt.ylim(0,100)
        plt.show()


    # Heatmap of permutations (x=cities; y=steps) 
Example #4
Source File: utils.py    From pruning_yolov3 with GNU General Public License v3.0 8 votes vote down vote up
def plot_wh_methods():  # from utils.utils import *; plot_wh_methods()
    # Compares the two methods for width-height anchor multiplication
    # https://github.com/ultralytics/yolov3/issues/168
    x = np.arange(-4.0, 4.0, .1)
    ya = np.exp(x)
    yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2

    fig = plt.figure(figsize=(6, 3), dpi=150)
    plt.plot(x, ya, '.-', label='yolo method')
    plt.plot(x, yb ** 2, '.-', label='^2 power method')
    plt.plot(x, yb ** 2.5, '.-', label='^2.5 power method')
    plt.xlim(left=-4, right=4)
    plt.ylim(bottom=0, top=6)
    plt.xlabel('input')
    plt.ylabel('output')
    plt.legend()
    fig.tight_layout()
    fig.savefig('comparison.png', dpi=200) 
Example #5
Source File: dataset.py    From neural-combinatorial-optimization-rl-tensorflow with MIT License 7 votes vote down vote up
def visualize_2D_trip(self,trip,tw_open,tw_close):
        plt.figure(figsize=(30,30))
        rcParams.update({'font.size': 22})
        # Plot cities
        colors = ['red'] # Depot is first city
        for i in range(len(tw_open)-1):
            colors.append('blue')
        plt.scatter(trip[:,0], trip[:,1], color=colors, s=200)
        # Plot tour
        tour=np.array(list(range(len(trip))) + [0])
        X = trip[tour, 0]
        Y = trip[tour, 1]
        plt.plot(X, Y,"--", markersize=100)
        # Annotate cities with TW
        tw_open = np.rint(tw_open)
        tw_close = np.rint(tw_close)
        time_window = np.concatenate((tw_open,tw_close),axis=1)
        for tw, (x, y) in zip(time_window,(zip(X,Y))):
            plt.annotate(tw,xy=(x, y))  
        plt.xlim(0,60)
        plt.ylim(0,60)
        plt.show()


    # Heatmap of permutations (x=cities; y=steps) 
Example #6
Source File: display_methods.py    From indras_net with GNU General Public License v3.0 7 votes vote down vote up
def create_scats(self, varieties):
        self.scats = pd.DataFrame(columns=["x", "y", "color", "marker", "var"])
        for i, var in enumerate(varieties):
            self.legend.append(var)
            (x_array, y_array) = self.get_arrays(varieties, var)
            if len(x_array) <= 0:  # no data to graph!
                '''
                I am creating a single "position" for an agent that cannot
                be seen. This seems to fix the issue of colors being
                missmatched in the occasion that a group has no agents.
                '''
                x_array = [-1]
                y_array = [-1]
            elif len(x_array) != len(y_array):
                logging.debug("Array length mismatch in scatter plot")
                return
            color = get_color(varieties[var], i)
            marker = get_marker(varieties[var], i)
            scat = pd.DataFrame({"x": pd.Series(x_array),
                                 "y": pd.Series(y_array),
                                 "color": color,
                                 "marker": marker,
                                 "var": var})
            self.scats = self.scats.append(scat, ignore_index=True,
                                           sort=False) 
Example #7
Source File: plotFigures.py    From fullrmc with GNU Affero General Public License v3.0 7 votes vote down vote up
def plot(PDF, figName, imgpath, show=False, save=True):
    # plot
    output = PDF.get_constraint_value()
    plt.plot(PDF.experimentalDistances,PDF.experimentalPDF, 'ro', label="experimental", markersize=7.5, markevery=1 )
    plt.plot(PDF.shellsCenter, output["pdf"], 'k', linewidth=3.0,  markevery=25, label="total" )

    styleIndex = 0
    for key in output:
        val = output[key]
        if key in ("pdf_total", "pdf"):
            continue
        elif "inter" in key:
            plt.plot(PDF.shellsCenter, val, STYLE[styleIndex], markevery=5, label=key.split('rdf_inter_')[1] )
            styleIndex+=1
    plt.legend(frameon=False, ncol=1)
    # set labels
    plt.title("$\\chi^{2}=%.6f$"%PDF.squaredDeviations, size=20)
    plt.xlabel("$r (\AA)$", size=20)
    plt.ylabel("$g(r)$", size=20)
    # show plot
    if save: plt.savefig(figName)
    if show: plt.show()
    plt.close() 
Example #8
Source File: utils.py    From pruning_yolov3 with GNU General Public License v3.0 7 votes vote down vote up
def plot_evolution_results(hyp):  # from utils.utils import *; plot_evolution_results(hyp)
    # Plot hyperparameter evolution results in evolve.txt
    x = np.loadtxt('evolve.txt', ndmin=2)
    f = fitness(x)
    weights = (f - f.min()) ** 2  # for weighted results
    fig = plt.figure(figsize=(12, 10))
    matplotlib.rc('font', **{'size': 8})
    for i, (k, v) in enumerate(hyp.items()):
        y = x[:, i + 5]
        # mu = (y * weights).sum() / weights.sum()  # best weighted result
        mu = y[f.argmax()]  # best single result
        plt.subplot(4, 5, i + 1)
        plt.plot(mu, f.max(), 'o', markersize=10)
        plt.plot(y, f, '.')
        plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9})  # limit to 40 characters
        print('%15s: %.3g' % (k, mu))
    fig.tight_layout()
    plt.savefig('evolve.png', dpi=200) 
Example #9
Source File: __init__.py    From EDeN with MIT License 7 votes vote down vote up
def plot_roc_curve(y_true, y_score, size=None):
    """plot_roc_curve."""
    false_positive_rate, true_positive_rate, thresholds = roc_curve(
        y_true, y_score)
    if size is not None:
        plt.figure(figsize=(size, size))
        plt.axis('equal')
    plt.plot(false_positive_rate, true_positive_rate, lw=2, color='navy')
    plt.plot([0, 1], [0, 1], color='gray', lw=1, linestyle='--')
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.ylim([-0.05, 1.05])
    plt.xlim([-0.05, 1.05])
    plt.grid()
    plt.title('Receiver operating characteristic AUC={0:0.2f}'.format(
        roc_auc_score(y_true, y_score))) 
Example #10
Source File: helper.py    From Stock-Price-Prediction with MIT License 6 votes vote down vote up
def plot_mul(Y_hat, Y, pred_len):
    """
    PLots the predicted data versus true data

    Input: Predicted data, True Data, Length of prediction
    Output: return plot

    Note: Run from timeSeriesPredict.py
    """
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(Y, label='Y')
    # Print the predictions in its respective series-length
    for i, j in enumerate(Y_hat):
        shift = [None for p in range(i * pred_len)]
        plt.plot(shift + j, label='Y_hat')
        plt.legend()
    plt.show() 
Example #11
Source File: plot_utils.py    From keras-anomaly-detection with MIT License 6 votes vote down vote up
def visualize_anomaly(y_true, reconstruction_error, threshold):
    error_df = pd.DataFrame({'reconstruction_error': reconstruction_error,
                             'true_class': y_true})
    print(error_df.describe())

    groups = error_df.groupby('true_class')
    fig, ax = plt.subplots()

    for name, group in groups:
        ax.plot(group.index, group.reconstruction_error, marker='o', ms=3.5, linestyle='',
                label="Fraud" if name == 1 else "Normal")

    ax.hlines(threshold, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold')
    ax.legend()
    plt.title("Reconstruction error for different classes")
    plt.ylabel("Reconstruction error")
    plt.xlabel("Data point index")
    plt.show() 
Example #12
Source File: plot_lfads.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def plot_time_series(vals_bxtxn, bidx=None, n_to_plot=np.inf, scale=1.0,
                     color='r', title=None):

  if bidx is None:
    vals_txn = np.mean(vals_bxtxn, axis=0)
  else:
    vals_txn = vals_bxtxn[bidx,:,:]

  T, N = vals_txn.shape
  if n_to_plot > N:
    n_to_plot = N

  plt.plot(vals_txn[:,0:n_to_plot] + scale*np.array(range(n_to_plot)),
           color=color, lw=1.0)
  plt.axis('tight')
  if title:
    plt.title(title) 
Example #13
Source File: util.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compute_roc_rfeinman(probs_neg, probs_pos, plot=False):
    """
    TODO
    :param probs_neg:
    :param probs_pos:
    :param plot:
    :return:
    """
    probs = np.concatenate((probs_neg, probs_pos))
    labels = np.concatenate((np.zeros_like(probs_neg), np.ones_like(probs_pos)))
    fpr, tpr, _ = roc_curve(labels, probs)
    auc_score = auc(fpr, tpr)
    if plot:
        plt.figure(figsize=(7, 6))
        plt.plot(fpr, tpr, color='blue',
                 label='ROC (AUC = %0.4f)' % auc_score)
        plt.legend(loc='lower right')
        plt.title("ROC Curve")
        plt.xlabel("FPR")
        plt.ylabel("TPR")
        plt.show()

    return fpr, tpr, auc_score 
Example #14
Source File: dataset.py    From neural-combinatorial-optimization-rl-tensorflow with MIT License 6 votes vote down vote up
def visualize_sampling(self, permutations):
        max_length = len(permutations[0])
        grid = np.zeros([max_length,max_length]) # initialize heatmap grid to 0

        transposed_permutations = np.transpose(permutations)
        for t, cities_t in enumerate(transposed_permutations): # step t, cities chosen at step t
            city_indices, counts = np.unique(cities_t,return_counts=True,axis=0)
            for u,v in zip(city_indices, counts):
                grid[t][u]+=v # update grid with counts from the batch of permutations

        # plot heatmap
        fig = plt.figure()
        rcParams.update({'font.size': 22})
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(grid, interpolation='nearest', cmap='gray')
        plt.colorbar()
        plt.title('Sampled permutations')
        plt.ylabel('Time t')
        plt.xlabel('City i')
        plt.show() 
Example #15
Source File: recall.py    From mmdetection with Apache License 2.0 6 votes vote down vote up
def plot_iou_recall(recalls, iou_thrs):
    """Plot IoU-Recalls curve.

    Args:
        recalls(ndarray or list): shape (k,)
        iou_thrs(ndarray or list): same shape as `recalls`
    """
    if isinstance(iou_thrs, np.ndarray):
        _iou_thrs = iou_thrs.tolist()
    else:
        _iou_thrs = iou_thrs
    if isinstance(recalls, np.ndarray):
        _recalls = recalls.tolist()
    else:
        _recalls = recalls

    import matplotlib.pyplot as plt
    f = plt.figure()
    plt.plot(_iou_thrs + [1.0], _recalls + [0.])
    plt.xlabel('IoU')
    plt.ylabel('Recall')
    plt.axis([iou_thrs.min(), 1, 0, 1])
    f.show() 
Example #16
Source File: recall.py    From mmdetection with Apache License 2.0 6 votes vote down vote up
def plot_num_recall(recalls, proposal_nums):
    """Plot Proposal_num-Recalls curve.

    Args:
        recalls(ndarray or list): shape (k,)
        proposal_nums(ndarray or list): same shape as `recalls`
    """
    if isinstance(proposal_nums, np.ndarray):
        _proposal_nums = proposal_nums.tolist()
    else:
        _proposal_nums = proposal_nums
    if isinstance(recalls, np.ndarray):
        _recalls = recalls.tolist()
    else:
        _recalls = recalls

    import matplotlib.pyplot as plt
    f = plt.figure()
    plt.plot([0] + _proposal_nums, [0] + _recalls)
    plt.xlabel('Proposal num')
    plt.ylabel('Recall')
    plt.axis([0, proposal_nums.max(), 0, 1])
    f.show() 
Example #17
Source File: utils.py    From pruning_yolov3 with GNU General Public License v3.0 6 votes vote down vote up
def plot_images(imgs, targets, paths=None, fname='images.jpg'):
    # Plots training images overlaid with targets
    imgs = imgs.cpu().numpy()
    targets = targets.cpu().numpy()
    # targets = targets[targets[:, 1] == 21]  # plot only one class

    fig = plt.figure(figsize=(10, 10))
    bs, _, h, w = imgs.shape  # batch size, _, height, width
    bs = min(bs, 16)  # limit plot to 16 images
    ns = np.ceil(bs ** 0.5)  # number of subplots

    for i in range(bs):
        boxes = xywh2xyxy(targets[targets[:, 0] == i, 2:6]).T
        boxes[[0, 2]] *= w
        boxes[[1, 3]] *= h
        plt.subplot(ns, ns, i + 1).imshow(imgs[i].transpose(1, 2, 0))
        plt.plot(boxes[[0, 2, 2, 0, 0]], boxes[[1, 1, 3, 3, 1]], '.-')
        plt.axis('off')
        if paths is not None:
            s = Path(paths[i]).name
            plt.title(s[:min(len(s), 40)], fontdict={'size': 8})  # limit to 40 characters
    fig.tight_layout()
    fig.savefig(fname, dpi=200)
    plt.close() 
Example #18
Source File: utils.py    From pruning_yolov3 with GNU General Public License v3.0 6 votes vote down vote up
def plot_results(start=0, stop=0):  # from utils.utils import *; plot_results()
    # Plot training results files 'results*.txt'
    fig, ax = plt.subplots(2, 5, figsize=(14, 7))
    ax = ax.ravel()
    s = ['GIoU', 'Objectness', 'Classification', 'Precision', 'Recall',
         'val GIoU', 'val Objectness', 'val Classification', 'mAP', 'F1']
    for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
        results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
        n = results.shape[1]  # number of rows
        x = range(start, min(stop, n) if stop else n)
        for i in range(10):
            y = results[i, x]
            if i in [0, 1, 2, 5, 6, 7]:
                y[y == 0] = np.nan  # dont show zero loss values
            ax[i].plot(x, y, marker='.', label=f.replace('.txt', ''))
            ax[i].set_title(s[i])
            if i in [5, 6, 7]:  # share train and val loss y axes
                ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])

    fig.tight_layout()
    ax[1].legend()
    fig.savefig('results.png', dpi=200) 
Example #19
Source File: utils.py    From pruning_yolov3 with GNU General Public License v3.0 6 votes vote down vote up
def plot_results_overlay(start=0, stop=0):  # from utils.utils import *; plot_results_overlay()
    # Plot training results files 'results*.txt', overlaying train and val losses
    s = ['train', 'train', 'train', 'Precision', 'mAP', 'val', 'val', 'val', 'Recall', 'F1']  # legends
    t = ['GIoU', 'Objectness', 'Classification', 'P-R', 'mAP-F1']  # titles
    for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
        results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
        n = results.shape[1]  # number of rows
        x = range(start, min(stop, n) if stop else n)
        fig, ax = plt.subplots(1, 5, figsize=(14, 3.5))
        ax = ax.ravel()
        for i in range(5):
            for j in [i, i + 5]:
                y = results[j, x]
                if i in [0, 1, 2]:
                    y[y == 0] = np.nan  # dont show zero loss values
                ax[i].plot(x, y, marker='.', label=s[j])
            ax[i].set_title(t[i])
            ax[i].legend()
            ax[i].set_ylabel(f) if i == 0 else None  # add filename
        fig.tight_layout()
        fig.savefig(f.replace('.txt', '.png'), dpi=200) 
Example #20
Source File: simulate_sin.py    From deep-learning-note with MIT License 6 votes vote down vote up
def run_eval(sess, test_X, test_y):
    ds = tf.data.Dataset.from_tensor_slices((test_X, test_y))
    ds = ds.batch(1)
    X, y = ds.make_one_shot_iterator().get_next()

    with tf.variable_scope("model", reuse=True):
        prediction, _, _ = lstm_model(X, [0.0], False)
        predictions = []
        labels = []
        for i in range(TESTING_EXAMPLES):
            p, l = sess.run([prediction, y])
            predictions.append(p)
            labels.append(l)

    predictions = np.array(predictions).squeeze()
    labels = np.array(labels).squeeze()
    rmse = np.sqrt(((predictions-labels) ** 2).mean(axis=0))
    print("Mean Square Error is: %f" % rmse)

    plt.figure()
    plt.plot(predictions, label='predictions')
    plt.plot(labels, label='real_sin')
    plt.legend()
    plt.show() 
Example #21
Source File: plot_3.py    From cs294-112_hws with MIT License 6 votes vote down vote up
def plot_3(data):
    x = data.Iteration.unique()
    y_mean = data.groupby('Iteration').mean()
    y_std = data.groupby('Iteration').std()
    
    sns.set(style="darkgrid", font_scale=1.5)
    value = 'AverageReturn'
    plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_train');
    plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2);
    value = 'ValAverageReturn'
    plt.plot(x, y_mean[value], label=data['Condition'].unique()[0] + '_test');
    plt.fill_between(x, y_mean[value] - y_std[value], y_mean[value] + y_std[value], alpha=0.2);
    
    plt.xlabel('Iteration')
    plt.ylabel('AverageReturn')
    plt.legend(loc='best') 
Example #22
Source File: Flight Analysis.py    From Cheapest-Flights-bot with MIT License 6 votes vote down vote up
def task_3_IQR(flight_data):
    plot=plt.boxplot(flight_data['Price'],patch_artist=True)
    for median in plot['medians']:
        median.set(color='#fc0004', linewidth=2)
    for flier in plot['fliers']:
        flier.set(marker='+', color='#e7298a')
    for whisker in plot['whiskers']:
        whisker.set(color='#7570b3', linewidth=2)
    for cap in plot['caps']:
        cap.set(color='#7570b3', linewidth=2)
    for box in plot['boxes']:
        box.set(color='#7570b3', linewidth=2)
        box.set(facecolor='#1b9e77')
    plt.matplotlib.pyplot.savefig('task_3_iqr.png')
    clean_data=[]
    for index,row in flight_data.loc[flight_data['Price'].isin(plot['fliers'][0].get_ydata())].iterrows():
        clean_data.append([row['Price'],row['Date_of_Flight']])
    return pd.DataFrame(clean_data, columns=['Price', 'Date_of_Flight']) 
Example #23
Source File: tlib.py    From TOPFARM with GNU Affero General Public License v3.0 6 votes vote down vote up
def dist_from_segment(P1, P2, P3):
    """ Calculate the distance of a point P3 from a segment defined by [P1,P2]

    :param P1: ndarray([2]) or [2]
    :param P2: ndarray([2]) or [2]
    :param P3: ndarray([2]) or [2]

    :return dist: float
    """
    l2P2P1 = l2_dist(P2,P1)
    if l2P2P1 == 0:
        return dist(P1,P3)
    x1, y1 = P1
    x2, y2 = P2
    x3, y3 = P3
    u = ((x3-x1)*(x2-x1) + (y3-y1)*(y2-y1)) / l2P2P1
    x = x1 + u*(x2-x1)
    y = y1 + u*(y2-y1)
    if u > 1.0:
        x, y = P2
    if u < 0.0:
        x, y = P1
    #plot([x3, x],[y3, y],'k--')
    return dist([x,y], P3) 
Example #24
Source File: classification.py    From Kaggler with MIT License 6 votes vote down vote up
def plot_roc_curve(y, p):
    fpr, tpr, _ = roc_curve(y, p)

    plt.plot(fpr, tpr)
    plt.plot([0, 1], [0, 1], color='navy', linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate') 
Example #25
Source File: utils.py    From Deep_Learning_Weather_Forecasting with Apache License 2.0 5 votes vote down vote up
def plot_prediction(x, y_true, y_pred, input_ruitu=None):
    """Plots the predictions.
    
    Arguments
    ---------
    x: Input sequence of shape (input_sequence_length,
        dimension_of_signal)
    y_true: True output sequence of shape (input_sequence_length,
        dimension_of_signal)
    y_pred: Predicted output sequence (input_sequence_length,
        dimension_of_signal)
    """

    plt.figure(figsize=(12, 3))

    output_dim = x.shape[-1]# feature dimension
    for j in range(output_dim):
        past = x[:, j] 
        true = y_true[:, j]
        pred = y_pred[:, j]
        if input_ruitu is not None:
            ruitu = input_ruitu[:, j]

        label1 = "Seen (past) values" if j==0 else "_nolegend_"
        label2 = "True future values" if j==0 else "_nolegend_"
        label3 = "Predictions" if j==0 else "_nolegend_"
        label4 = "Ruitu values" if j==0 else "_nolegend_"

        plt.plot(range(len(past)), past, "o-g",
                 label=label1)
        plt.plot(range(len(past),
                 len(true)+len(past)), true, "x--g", label=label2)
        plt.plot(range(len(past), len(pred)+len(past)), pred, "o--y",
                 label=label3)
        if input_ruitu is not None:
            plt.plot(range(len(past), len(ruitu)+len(past)), ruitu, "o--r",
                 label=label4)
    plt.legend(loc='best')
    plt.title("Predictions v.s. true values v.s. Ruitu")
    plt.show() 
Example #26
Source File: dataset.py    From neural-combinatorial-optimization-rl-tensorflow with MIT License 5 votes vote down vote up
def visualize_sampling(self,permutations):
        max_length = len(permutations[0])
        grid = np.zeros([max_length,max_length]) # initialize heatmap grid to 0
        transposed_permutations = np.transpose(permutations)
        for t, cities_t in enumerate(transposed_permutations): # step t, cities chosen at step t
            city_indices, counts = np.unique(cities_t,return_counts=True,axis=0)
            for u,v in zip(city_indices, counts):
                grid[t][u]+=v # update grid with counts from the batch of permutations
        # plot heatmap
        fig = plt.figure()
        rcParams.update({'font.size': 22})
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(grid, interpolation='nearest', cmap='gray')
        plt.colorbar()
        plt.title('Sampled permutations')
        plt.ylabel('Time t')
        plt.xlabel('City i')
        plt.show()

    # Heatmap of attention (x=cities; y=steps) 
Example #27
Source File: run.py    From fullrmc with GNU Affero General Public License v3.0 5 votes vote down vote up
def load_and_plot_constraints_benchmark():
    benchmark = np.loadtxt(fname='benchmark_constraints_time.dat')
    tried     = np.loadtxt(fname='benchmark_constraints_tried.dat')
    accepted  = np.loadtxt(fname='benchmark_constraints_accepted.dat')
    # plot
    keys = open('benchmark_constraints_time.dat').readlines()[0].split("#")[1].split()
    minY = 0
    maxY = 0
    for idx in range(1,len(keys)):
        style = '-'
        if keys[idx] == 'all':
            style = '.-'
        # mean accepted
        meanAccepted = int( sum(benchmark[:,0]*accepted[:,idx])/sum(benchmark[:,0]) )
        plt.plot(benchmark[:,0], benchmark[:,idx], style, label=keys[idx]+" (%i)"%meanAccepted)
        minY = min(minY, min(benchmark[:,idx]) )
        maxY = max(minY, max(benchmark[:,idx]) )
    # annotate tried(accepted)
    for i, txt in enumerate( accepted[:,-1] ):
        T = 100*float(tried[i,-1])/float(tried[1,1])
        A = 100*float(accepted[i,-1])/float(tried[1,1])
        plt.gca().annotate( "%.2f%% (%.2f%%)"%(T,A),  #"%i (%i)"%( int(tried[i,-1]),int(txt) ),
                            xy = (benchmark[i,0],benchmark[i,-1]),
                            rotation=90,
                            horizontalalignment='center',
                            verticalalignment='bottom')
    # show plot
    plt.legend(frameon=False, loc='upper left')
    plt.xlabel("Number of atoms per group")
    plt.ylabel("Time per step (s)")
    plt.gcf().patch.set_facecolor('white')
    # set fig size
    #figSize = plt.gcf().get_size_inches()
    #figSize[1] = figSize[1]+figSize[1]/2.
    #plt.gcf().set_size_inches(figSize, forward=True)
    plt.ylim((None, maxY+0.3*(maxY-minY)))
    # save
    plt.savefig("benchmark_constraint.png")
    # plot
    plt.show() 
Example #28
Source File: run.py    From fullrmc with GNU Affero General Public License v3.0 5 votes vote down vote up
def load_and_plot_steps_benchmark(constraint="all", groupSize=13):
    benchmark = np.loadtxt(fname='benchmark_%sSteps_%iGroupSize_time.dat'%(constraint,groupSize) )
    tried     = np.loadtxt(fname='benchmark_%sSteps_%iGroupSize_tried.dat'%(constraint,groupSize) )
    accepted  = np.loadtxt(fname='benchmark_%sSteps_%iGroupSize_accepted.dat'%(constraint,groupSize) )
    # plot benchmark
    plt.plot(benchmark[:,0], benchmark[:,1])
    minY = min(benchmark[:,1])
    maxY = max(benchmark[:,1])
    # annotate tried(accepted)
    for i, txt in enumerate( accepted[:,-1] ):
        T = 100*float(tried[i,-1])/float(benchmark[i,0])
        A = 100*float(accepted[i,-1])/float(benchmark[i,0])
        plt.gca().annotate( "%.2f%% (%.2f%%)"%(T,A),  #str(int(tried[i,-1]))+" ("+str(int(txt))+")",
                            xy = (benchmark[i,0],benchmark[i,-1]),
                            rotation=90,
                            horizontalalignment='center',
                            verticalalignment='bottom')
    # show plot
    plt.legend(frameon=False, loc='upper left')
    plt.xlabel("Number of steps")
    plt.ylabel("Time per step (s)")
    plt.gcf().patch.set_facecolor('white')
    # set fig size
    #figSize = plt.gcf().get_size_inches()
    #figSize[1] = figSize[1]+figSize[1]/2.
    #plt.gcf().set_size_inches(figSize, forward=True)
    plt.ylim((None, maxY+0.3*(maxY-minY)))
    # save
    plt.savefig("benchmark_steps.png")
    # plot
    plt.show()



##########################################################################################
#####################################  RUN BENCHMARKS  ################################### 
Example #29
Source File: plot_utils.py    From keras-anomaly-detection with MIT License 5 votes vote down vote up
def plot_training_history(history):
    if history is None:
        return
    plt.plot(history['loss'])
    plt.plot(history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper right')
    plt.show() 
Example #30
Source File: tlib.py    From TOPFARM with GNU Affero General Public License v3.0 5 votes vote down vote up
def plot(self):
        plot(self.polygon[:,0], self.polygon[:,1], '--')
        plot(self.X[self.In].flatten(), self.Y[self.In].flatten(), 'k.')