Python matplotlib.pyplot.ylim() Examples

The following are 30 code examples of matplotlib.pyplot.ylim(). 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: 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 #2
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 #3
Source File: 1logistic_regression.py    From Fundamentals-of-Machine-Learning-with-scikit-learn with MIT License 7 votes vote down vote up
def show_classification_areas(X, Y, lr):
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    Z = lr.predict(np.c_[xx.ravel(), yy.ravel()])

    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(30, 25))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Pastel1)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=np.abs(Y - 1), edgecolors='k', cmap=plt.cm.coolwarm)
    plt.xlabel('X')
    plt.ylabel('Y')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show() 
Example #4
Source File: plot_utils.py    From celer with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def plot_path_hist(results, labels, tols, figsize, ylim=None):
    configure_plt()
    sns.set_palette('colorblind')
    n_competitors = len(results)
    fig, ax = plt.subplots(figsize=figsize)
    width = 1. / (n_competitors + 1)
    ind = np.arange(len(tols))
    b = (1 - n_competitors) / 2.
    for i in range(n_competitors):
        plt.bar(ind + (i + b) * width, results[i], width,
                label=labels[i])
    ax.set_ylabel('path computation time (s)')
    ax.set_xticks(ind + width / 2)
    plt.xticks(range(len(tols)), ["%.0e" % tol for tol in tols])
    if ylim is not None:
        plt.ylim(ylim)

    ax.set_xlabel(r"$\epsilon$")
    plt.legend(loc='upper left')
    plt.tight_layout()
    plt.show(block=False)
    return fig 
Example #5
Source File: model.py    From fake-news-detection with MIT License 7 votes vote down vote up
def print_roc(self, y_true, y_scores, filename):
        '''
        Prints the ROC for this model.
        '''
        fpr, tpr, thresholds = metrics.roc_curve(y_true, y_scores)
        plt.figure()
        plt.plot(fpr, tpr, color='darkorange', label='ROC curve (area = %0.2f)' % self.roc_auc)
        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')
        plt.title('Receiver operating characteristic')
        plt.legend(loc="lower right")
        plt.savefig(filename)
        plt.close() 
Example #6
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 #7
Source File: plot_threshold_vs_success_trans.py    From pointnet-registration-framework with MIT License 7 votes vote down vote up
def make_plot(files, labels):
	plt.figure()
	for file_idx in range(len(files)):
		rot_err, trans_err = read_csv(files[file_idx])
		success_dict = count_success(trans_err)

		x_range = success_dict.keys()
		x_range.sort()
		success = []
		for i in x_range:
			success.append(success_dict[i])
		success = np.array(success)/total_cases

		plt.plot(x_range, success, linewidth=3, label=labels[file_idx])
		# plt.scatter(x_range, success, s=50)
	plt.ylabel('Success Ratio', fontsize=40)
	plt.xlabel('Threshold for Translation Error', fontsize=40)
	plt.tick_params(labelsize=40, width=3, length=10)
	plt.grid(True)
	plt.ylim(0,1.005)
	plt.yticks(np.arange(0,1.2,0.2))
	plt.xticks(np.arange(0,2.1,0.2))
	plt.xlim(0,2)
	plt.legend(fontsize=30, loc=4) 
Example #8
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 #9
Source File: score.py    From EvalNE with MIT License 6 votes vote down vote up
def _plot(self, results, x, y, x_label, y_label, curve, filename):
        r"""
        Contains the actual plot functionality.
        """
        plt.plot(x, y)
        plt.xlabel(x_label)
        plt.ylabel(y_label)
        plt.ylim([0.0, 1.0])
        plt.xlim([0.0, 1.0])
        if results == 'test':
            plt.title('{} test set {} curve'.format(self.method, curve))
        else:
            plt.title('{} train set {} curve'.format(self.method, curve))
        if filename is not None:
            plt.savefig(filename + '_' + curve + '.pdf')
            plt.close()
        else:
            plt.show() 
Example #10
Source File: mf.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def plot_contour(self, w=0.0):
    """
      Plot contour with poles of Green's function in the self-energy 
      SelfEnergy(w) = G(w+w')W(w')
      with respect to w' = Re(w')+Im(w')
      Poles of G(w+w') are located: w+w'-(E_n-Fermi)+i*eps sign(E_n-Fermi)==0 ==> 
      w'= (E_n-Fermi) - w -i eps sign(E_n-Fermi)
    """
    try :
      import matplotlib.pyplot as plt
      from matplotlib.patches import Arc, Arrow 
    except:
      print('no matplotlib?')
      return

    fig,ax = plt.subplots()
    fe = self.fermi_energy
    ee = self.mo_energy
    iee = 0.5-np.array(ee>fe)
    eew = ee-fe-w
    ax.plot(eew, iee, 'r.', ms=10.0)
    pp = list()
    pp.append(Arc((0,0),4,4,angle=0, linewidth=2, theta1=0, theta2=90, zorder=2, color='b'))
    pp.append(Arc((0,0),4,4,angle=0, linewidth=2, theta1=180, theta2=270, zorder=2, color='b'))
    pp.append(Arrow(0,2,0,-4,width=0.2, color='b', hatch='o'))
    pp.append(Arrow(-2,0,4,0,width=0.2, color='b', hatch='o'))
    for p in pp: ax.add_patch(p)
    ax.set_aspect('equal')
    ax.grid(True, which='both')
    ax.axhline(y=0, color='k')
    ax.axvline(x=0, color='k')
    plt.ylim(-3.0,3.0)
    plt.show() 
Example #11
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 #12
Source File: display.py    From radiometric_normalization with Apache License 2.0 6 votes vote down vote up
def plot_pixels(file_name, candidate_data_single_band,
                reference_data_single_band, limits=None, fit_line=None):

    logging.info('Display: Creating pixel plot - {}'.format(file_name))
    fig = plt.figure()
    plt.hexbin(
        candidate_data_single_band, reference_data_single_band, mincnt=1)
    if not limits:
        min_value = 0
        _, ymax = plt.gca().get_ylim()
        _, xmax = plt.gca().get_xlim()
        max_value = max([ymax, xmax])
        limits = [min_value, max_value]
    plt.plot(limits, limits, 'k-')
    if fit_line:
        start = limits[0] * fit_line.gain + fit_line.offset
        end = limits[1] * fit_line.gain + fit_line.offset
        plt.plot(limits, [start, end], 'g-')
    plt.xlim(limits)
    plt.ylim(limits)
    plt.xlabel('Candidate DNs')
    plt.ylabel('Reference DNs')
    fig.savefig(file_name, bbox_inches='tight')
    plt.close(fig) 
Example #13
Source File: prediction.py    From malss with MIT License 6 votes vote down vote up
def __plot_curve(self, name, val, ylim, suffix=''):
        x = val['learning_curve']['x']
        y_train = val['learning_curve']['y_train']
        y_cv = val['learning_curve']['y_cv']

        plt.plot(x, y_train, 'o-', color='dodgerblue',
                 label='Training score')
        plt.plot(x, y_cv, 'o-', color='darkorange',
                 label='Cross-validation score')
        plt.title(name)
        plt.xlabel('Training examples')
        plt.ylabel('Score')
        plt.grid(True)
        plt.ylim(ylim)
        plt.legend(loc="lower right")
        fname = self.params.out_dir + '/Learning curve_' + name
        if suffix != '':
            fname += '_' + suffix
        fname += '.png'
        plt.savefig(fname, bbox_inches='tight')
        plt.close() 
Example #14
Source File: lr_finder.py    From keras_lr_finder with MIT License 6 votes vote down vote up
def plot_loss_change(self, sma=1, n_skip_beginning=10, n_skip_end=5, y_lim=(-0.01, 0.01)):
        """
        Plots rate of change of the loss function.
        Parameters:
            sma - number of batches for simple moving average to smooth out the curve.
            n_skip_beginning - number of batches to skip on the left.
            n_skip_end - number of batches to skip on the right.
            y_lim - limits for the y axis.
        """
        derivatives = self.get_derivatives(sma)[n_skip_beginning:-n_skip_end]
        lrs = self.lrs[n_skip_beginning:-n_skip_end]
        plt.ylabel("rate of loss change")
        plt.xlabel("learning rate (log scale)")
        plt.plot(lrs, derivatives)
        plt.xscale('log')
        plt.ylim(y_lim)
        plt.show() 
Example #15
Source File: classification_perf.py    From ctw-baseline with MIT License 5 votes vote down vote up
def draw_by_models(all):
    def model_recall(attr_perfs):
        n = rc = 0
        for k, o in enumerate(attr_perfs):
            n += o['n']
            rc += o['recalls'][1]
        return 0. if n == 0 else rc / n
    data = [
        [
            {
                'legend': szname,
                'data': [model_recall(model['performance'][szname]['attributes']) for model in all],
            }
        ] for szname, _ in settings.SIZE_RANGES
    ]
    labels = [list(filter(lambda o: o['model_name'] == model['model_name'], predictions2html.cfgs))[0]['display_name'] for model in all]
    with plt.style.context({
        'figure.subplot.left': .10,
        'figure.subplot.right': .96,
        'figure.subplot.top': .96,
        'legend.loc': 'upper center',
        'pdf.fonttype': 42,
    }):
        plt.figure(figsize=(6, 3))
        plt.ylim((0., 1.))
        plt.grid(which='major', axis='y', linestyle='dotted')
        plot_tools.draw_bar(data, labels, width=.18, legend_kwargs={'ncol': len(settings.SIZE_RANGES)})
        plt.ylabel('accuracy')
        plt.savefig(os.path.join(settings.PLOTS_DIR, 'cls_precision_by_model_size.pdf'))
        plt.close() 
Example #16
Source File: 8voting_classifier.py    From Fundamentals-of-Machine-Learning-with-scikit-learn with MIT License 5 votes vote down vote up
def plot_accuracies(accuracies):
    fig, ax = plt.subplots(figsize=(12, 8))
    positions = np.array([0, 1, 2, 3])

    ax.bar(positions, accuracies, 0.5)
    ax.set_ylabel('Accuracy')
    ax.set_xticklabels(('Logistic Regression', 'Decision Tree', 'SVM', 'Ensemble'))
    ax.set_xticks(positions + (5.0 / 20))
    plt.ylim([0.80, 0.93])
    plt.show() 
Example #17
Source File: classification_perf.py    From ctw-baseline with MIT License 5 votes vote down vote up
def draw_by_attrs(model_name, performance):
    def attr_recall(attr_perfs, attr_id):
        m = len(settings.ATTRIBUTES)
        n = rc = 0
        for k, o in enumerate(attr_perfs):
            if attr_id == -1 or (attr_id < m and 0 != int(k) & 2 ** attr_id) or (m <= attr_id and 0 == int(k) & 2 ** (attr_id - m)):
                n += o['n']
                rc += o['recalls'][1]
        return 0. if n == 0 else rc / n

    data = [
        [
            {
                'legend': szname,
                'data': [attr_recall(performance[szname]['attributes'], i) for i in range(-1, 2 * len(settings.ATTRIBUTES))],
            }
        ] for szname, _ in settings.SIZE_RANGES
    ]
    labels = ['all'] + settings.ATTRIBUTES + list(map('~{}'.format, settings.ATTRIBUTES))
    with plt.style.context({
        'figure.subplot.left': .05,
        'figure.subplot.right': .98,
        'figure.subplot.top': .96,
        'legend.loc': 'upper center',
        'pdf.fonttype': 42,
    }):
        plt.figure(figsize=(12, 3))
        plt.xlim((.3, .7 + len(labels)))
        plt.ylim((0., 1.))
        plt.grid(which='major', axis='y', linestyle='dotted')
        plot_tools.draw_bar(data, labels, width=.18, legend_kwargs={'ncol': len(settings.SIZE_RANGES)})
        plt.ylabel('accuracy')
        plt.savefig(os.path.join(settings.PLOTS_DIR, 'cls_precision_by_attr_size_{}.pdf'.format(model_name)))
        plt.close() 
Example #18
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 #19
Source File: random_walk.py    From reinforcement-learning-an-introduction with MIT License 5 votes vote down vote up
def figure7_2():
    # all possible steps
    steps = np.power(2, np.arange(0, 10))

    # all possible alphas
    alphas = np.arange(0, 1.1, 0.1)

    # each run has 10 episodes
    episodes = 10

    # perform 100 independent runs
    runs = 100

    # track the errors for each (step, alpha) combination
    errors = np.zeros((len(steps), len(alphas)))
    for run in tqdm(range(0, runs)):
        for step_ind, step in enumerate(steps):
            for alpha_ind, alpha in enumerate(alphas):
                # print('run:', run, 'step:', step, 'alpha:', alpha)
                value = np.zeros(N_STATES + 2)
                for ep in range(0, episodes):
                    temporal_difference(value, step, alpha)
                    # calculate the RMS error
                    errors[step_ind, alpha_ind] += np.sqrt(np.sum(np.power(value - TRUE_VALUE, 2)) / N_STATES)
    # take average
    errors /= episodes * runs

    for i in range(0, len(steps)):
        plt.plot(alphas, errors[i, :], label='n = %d' % (steps[i]))
    plt.xlabel('alpha')
    plt.ylabel('RMS error')
    plt.ylim([0.25, 0.55])
    plt.legend()

    plt.savefig('../images/figure_7_2.png')
    plt.close() 
Example #20
Source File: plots.py    From yatsm with MIT License 5 votes vote down vote up
def plot_crossvalidation_scores(kfold_scores, test_labels):
    """ Plots KFold test summary statistics

    Args:
      kfold_scores (np.ndarray): n by 2 shaped array of mean and standard
        deviation of KFold scores
      test_labels (list): n length list of KFold label names

    """
    return
    ind = np.arange(kfold_scores.shape[0])
    width = 0.5

    fig, ax = plt.subplots()
    bars = ax.bar(ind, kfold_scores[:, 0], width)
    _, caplines, _ = ax.errorbar(ind + width / 2.0, kfold_scores[:, 0],
                                 fmt='none',
                                 yerr=kfold_scores[:, 1],
                                 capsize=10, elinewidth=3)
    for capline in caplines:
        capline.set_linewidth(10)
        capline.set_markeredgewidth(3)
        capline.set_color('red')

    for i, bar in enumerate(bars):
        txt = r'%.3f $\pm$ %.3f' % (kfold_scores[i, 0], kfold_scores[i, 1])
        ax.text(ind[i] + width / 2.0,
                kfold_scores[i, 0] / 2.0,
                txt,
                ha='center', va='bottom', size='large')

    ax.set_xticks(ind + width / 2.0)
    ax.set_xticklabels(test_labels, ha='center')
    # plt.ylim((0, 1.0))

    plt.title('KFold Cross Validation Summary Statistics')
    plt.xlabel('Test')
    plt.ylabel(r'Accuracy ($\pm$ standard deviation)')

    plt.tight_layout()
    plt.show() 
Example #21
Source File: mountain_car.py    From reinforcement-learning-an-introduction with MIT License 5 votes vote down vote up
def figure_12_10():
    runs = 30
    episodes = 50
    alphas = np.arange(1, 8) / 4.0
    lams = [0.99, 0.95, 0.5, 0]

    steps = np.zeros((len(lams), len(alphas), runs, episodes))
    for lamInd, lam in enumerate(lams):
        for alphaInd, alpha in enumerate(alphas):
            for run in tqdm(range(runs)):
                evaluator = Sarsa(alpha, lam, replacing_trace)
                for ep in range(episodes):
                    step = play(evaluator)
                    steps[lamInd, alphaInd, run, ep] = step

    # average over episodes
    steps = np.mean(steps, axis=3)

    # average over runs
    steps = np.mean(steps, axis=2)

    for lamInd, lam in enumerate(lams):
        plt.plot(alphas, steps[lamInd, :], label='lambda = %s' % (str(lam)))
    plt.xlabel('alpha * # of tilings (8)')
    plt.ylabel('averaged steps per episode')
    plt.ylim([180, 300])
    plt.legend()

    plt.savefig('../images/figure_12_10.png')
    plt.close()

# figure 12.11, summary comparision of Sarsa(lambda) algorithms
# I use 8 tilings rather than 10 tilings 
Example #22
Source File: plot.py    From sumo-rl with MIT License 5 votes vote down vote up
def plot_df(df, color, xaxis, yaxis, init_time=0, ma=1, acc=False, label=''):
    df[yaxis] = pd.to_numeric(df[yaxis], errors='coerce')  # convert NaN string to NaN value

    mean = df.groupby(xaxis).mean()[yaxis]
    std = df.groupby(xaxis).std()[yaxis]
    if ma > 1:
        mean = moving_average(mean, ma)
        std = moving_average(std, ma)

    x = df.groupby(xaxis)[xaxis].mean().keys().values
    plt.plot(x, mean, label=label, color=color, linestyle=next(dashes_styles))
    plt.fill_between(x, mean + std, mean - std, alpha=0.25, color=color, rasterized=True)
    
    #plt.ylim([0,200])
    #plt.xlim([40000, 70000]) 
Example #23
Source File: __init__.py    From EDeN with MIT License 5 votes vote down vote up
def plot_precision_recall_curve(y_true, y_score, size=None):
    """plot_precision_recall_curve."""
    precision, recall, thresholds = precision_recall_curve(y_true, y_score)
    if size is not None:
        plt.figure(figsize=(size, size))
        plt.axis('equal')
    plt.plot(recall, precision, lw=2, color='navy')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.ylim([-0.05, 1.05])
    plt.xlim([-0.05, 1.05])
    plt.grid()
    plt.title('Precision-Recall AUC={0:0.2f}'.format(average_precision_score(
        y_true, y_score))) 
Example #24
Source File: evaluate.py    From ganomaly with MIT License 5 votes vote down vote up
def roc(labels, scores, saveto=None):
    """Compute ROC curve and ROC area for each class"""
    fpr = dict()
    tpr = dict()
    roc_auc = dict()

    labels = labels.cpu()
    scores = scores.cpu()

    # True/False Positive Rates.
    fpr, tpr, _ = roc_curve(labels, scores)
    roc_auc = auc(fpr, tpr)

    # Equal Error Rate
    eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.)

    if saveto:
        plt.figure()
        lw = 2
        plt.plot(fpr, tpr, color='darkorange', lw=lw, label='(AUC = %0.2f, EER = %0.2f)' % (roc_auc, eer))
        plt.plot([eer], [1-eer], marker='o', markersize=5, color="navy")
        plt.plot([0, 1], [1, 0], color='navy', lw=1, linestyle=':')
        plt.xlim([0.0, 1.0])
        plt.ylim([0.0, 1.05])
        plt.xlabel('False Positive Rate')
        plt.ylabel('True Positive Rate')
        plt.title('Receiver operating characteristic')
        plt.legend(loc="lower right")
        plt.savefig(os.path.join(saveto, "ROC.pdf"))
        plt.close()

    return roc_auc 
Example #25
Source File: mountain_car.py    From reinforcement-learning-an-introduction with MIT License 5 votes vote down vote up
def figure_12_11():
    traceTypes = [dutch_trace, replacing_trace, replacing_trace_with_clearing, accumulating_trace]
    alphas = np.arange(0.2, 2.2, 0.2)
    episodes = 20
    runs = 30
    lam = 0.9
    rewards = np.zeros((len(traceTypes), len(alphas), runs, episodes))

    for traceInd, trace in enumerate(traceTypes):
        for alphaInd, alpha in enumerate(alphas):
            for run in tqdm(range(runs)):
                evaluator = Sarsa(alpha, lam, trace)
                for ep in range(episodes):
                    if trace == accumulating_trace and alpha > 0.6:
                        steps = STEP_LIMIT
                    else:
                        steps = play(evaluator)
                    rewards[traceInd, alphaInd, run, ep] = -steps

    # average over episodes
    rewards = np.mean(rewards, axis=3)

    # average over runs
    rewards = np.mean(rewards, axis=2)

    for traceInd, trace in enumerate(traceTypes):
        plt.plot(alphas, rewards[traceInd, :], label=trace.__name__)
    plt.xlabel('alpha * # of tilings (8)')
    plt.ylabel('averaged rewards pre episode')
    plt.ylim([-550, -150])
    plt.legend()

    plt.savefig('../images/figure_12_11.png')
    plt.close() 
Example #26
Source File: random_walk.py    From reinforcement-learning-an-introduction with MIT License 5 votes vote down vote up
def figure_9_2_right(true_value):
    # all possible steps
    steps = np.power(2, np.arange(0, 10))

    # all possible alphas
    alphas = np.arange(0, 1.1, 0.1)

    # each run has 10 episodes
    episodes = 10

    # perform 100 independent runs
    runs = 100

    # track the errors for each (step, alpha) combination
    errors = np.zeros((len(steps), len(alphas)))
    for run in tqdm(range(runs)):
        for step_ind, step in zip(range(len(steps)), steps):
            for alpha_ind, alpha in zip(range(len(alphas)), alphas):
                # we have 20 aggregations in this example
                value_function = ValueFunction(20)
                for ep in range(0, episodes):
                    semi_gradient_temporal_difference(value_function, step, alpha)
                    # calculate the RMS error
                    state_value = np.asarray([value_function.value(i) for i in STATES])
                    errors[step_ind, alpha_ind] += np.sqrt(np.sum(np.power(state_value - true_value[1: -1], 2)) / N_STATES)
    # take average
    errors /= episodes * runs
    # truncate the error
    for i in range(len(steps)):
        plt.plot(alphas, errors[i, :], label='n = ' + str(steps[i]))
    plt.xlabel('alpha')
    plt.ylabel('RMS error')
    plt.ylim([0.25, 0.55])
    plt.legend() 
Example #27
Source File: car_rental_synchronous.py    From reinforcement-learning-an-introduction with MIT License 5 votes vote down vote up
def plot(self):
        print(self.policy)
        plt.figure()
        plt.xlim(0, MAX_CARS + 1)
        plt.ylim(0, MAX_CARS + 1)
        plt.table(cellText=np.flipud(self.policy), loc=(0, 0), cellLoc='center')
        plt.show() 
Example #28
Source File: prediction.py    From malss with MIT License 5 votes vote down vote up
def __plot_curves(self):
        ylim = self.__get_ylim(self.params.results['algorithms'])
        if self.params.results_fs is not None:
            ylim2 = self.__get_ylim(self.params.results_fs['algorithms'])
            if ylim2[0] < ylim[0]:
                ylim[0] = ylim2[0]
            if ylim2[1] > ylim[1]:
                ylim[1] = ylim2[1]

        for name, val in self.params.results['algorithms'].items():
            self.__plot_curve(name, val, ylim)

        if self.params.results_fs is not None:
            for name, val in self.params.results_fs['algorithms'].items():
                self.__plot_curve(name, val, ylim, 'Feature selected') 
Example #29
Source File: link_prediction_utils.py    From EDeN with MIT License 5 votes vote down vote up
def show_graph(g, vertex_color='typeof', size=15, vertex_label=None):
    """show_graph."""
    degrees = [len(g.neighbors(u)) for u in g.nodes()]

    print(('num nodes=%d' % len(g)))
    print(('num edges=%d' % len(g.edges())))
    print(('num non edges=%d' % len(list(nx.non_edges(g)))))
    print(('max degree=%d' % max(degrees)))
    print(('median degree=%d' % np.percentile(degrees, 50)))

    draw_graph(g, size=size,
               vertex_color=vertex_color, vertex_label=vertex_label,
               vertex_size=200, edge_label=None)

    # display degree distribution
    size = int((max(degrees) - min(degrees)) / 1.5)
    plt.figure(figsize=(size, 3))
    plt.title('Degree distribution')
    _bins = np.arange(min(degrees), max(degrees) + 2) - .5
    n, bins, patches = plt.hist(degrees, _bins,
                                alpha=0.3,
                                facecolor='navy', histtype='bar',
                                rwidth=0.8, edgecolor='k')
    labels = np.array([str(int(i)) for i in n])
    for xi, yi, label in zip(bins, n, labels):
        plt.text(xi + 0.5, yi, label, ha='center', va='bottom')

    plt.xticks(bins + 0.5)
    plt.xlim((min(degrees) - 1, max(degrees) + 1))
    plt.ylim((0, max(n) * 1.1))
    plt.xlabel('Node degree')
    plt.ylabel('Counts')
    plt.grid(linestyle=":")
    plt.show() 
Example #30
Source File: __init__.py    From EDeN with MIT License 5 votes vote down vote up
def draw_graph_row(graphs,
                   index=0,
                   contract=True,
                   n_graphs_per_line=5,
                   size=4,
                   xlim=None,
                   ylim=None,
                   **args):
    """draw_graph_row."""
    dim = len(graphs)
    size_y = size
    size_x = size * n_graphs_per_line * args.get('size_x_to_y_ratio', 1)
    plt.figure(figsize=(size_x, size_y))

    if xlim is not None:
        plt.xlim(xlim)
        plt.ylim(ylim)
    else:
        plt.xlim(xmax=3)

    for i in range(dim):
        plt.subplot(1, n_graphs_per_line, i + 1)
        graph = graphs[i]
        draw_graph(graph,
                   size=None,
                   pos=graph.graph.get('pos_dict', None),
                   **args)
    if args.get('file_name', None) is None:
        plt.show()
    else:
        row_file_name = '%d_' % (index) + args['file_name']
        plt.savefig(row_file_name,
                    bbox_inches='tight',
                    transparent=True,
                    pad_inches=0)
        plt.close()