Python matplotlib.pyplot.pcolormesh() Examples

The following are 30 code examples of matplotlib.pyplot.pcolormesh(). 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: 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 #2
Source File: spectrogram.py    From AudioSegment with MIT License 6 votes vote down vote up
def test_visualize(self):
        seg = audiosegment.from_file("furelise.wav")

        duration_s = 2.5
        hist_bins, times, amplitudes = seg.spectrogram(start_s=0, duration_s=duration_s, window_length_s=0.03, overlap=0.25)
        amplitudes = 10 * np.log10(amplitudes + 1e-9)

        plt.subplot(121)
        plt.pcolormesh(times, hist_bins, amplitudes)
        plt.xlabel("Time in Seconds")
        plt.ylabel("Frequency in Hz")

        hist_bins, times, amplitudes = seg.spectrogram(start_s=duration_s, duration_s=duration_s, window_length_s=0.03, overlap=0.25)
        times += duration_s
        amplitudes = 10 * np.log10(amplitudes + 1e-9)

        plt.subplot(122)
        plt.pcolormesh(times,hist_bins,amplitudes)
        plt.show() 
Example #3
Source File: visualize_flow.py    From residual-flows with MIT License 6 votes vote down vote up
def plt_potential_func(potential, ax, npts=100, title="$p(x)$"):
    """
    Args:
        potential: computes U(z_k) given z_k
    """
    xside = np.linspace(LOW, HIGH, npts)
    yside = np.linspace(LOW, HIGH, npts)
    xx, yy = np.meshgrid(xside, yside)
    z = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])

    z = torch.Tensor(z)
    u = potential(z).cpu().numpy()
    p = np.exp(-u).reshape(npts, npts)

    plt.pcolormesh(xx, yy, p)
    ax.invert_yaxis()
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    ax.set_title(title) 
Example #4
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pcolorargs():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Z = np.sqrt(X**2 + Y**2)/5

    _, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.pcolormesh(y, x, Z)
    with pytest.raises(TypeError):
        ax.pcolormesh(X, Y, Z.T)
    with pytest.raises(TypeError):
        ax.pcolormesh(x, y, Z[:-1, :-1], shading="gouraud")
    with pytest.raises(TypeError):
        ax.pcolormesh(X, Y, Z[:-1, :-1], shading="gouraud")
    x[0] = np.NaN
    with pytest.raises(ValueError):
        ax.pcolormesh(x, y, Z[:-1, :-1])
    with np.errstate(invalid='ignore'):
        x = np.ma.array(x, mask=(x < 0))
    with pytest.raises(ValueError):
        ax.pcolormesh(x, y, Z[:-1, :-1]) 
Example #5
Source File: test_axes.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_pcolormesh_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolormesh(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolormesh(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolormesh(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example #6
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pcolormesh():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Qx = np.cos(Y) - np.cos(X)
    Qz = np.sin(Y) + np.sin(X)
    Qx = (Qx + 1.1)
    Z = np.hypot(X, Y) / 5
    Z = (Z - Z.min()) / Z.ptp()

    # The color array can include masked values:
    Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z)

    fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
    ax1.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k')
    ax2.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w'])
    ax3.pcolormesh(Qx, Qz, Z, shading="gouraud") 
Example #7
Source File: test_axes.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_pcolormesh():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Qx = np.cos(Y) - np.cos(X)
    Qz = np.sin(Y) + np.sin(X)
    Qx = (Qx + 1.1)
    Z = np.sqrt(X**2 + Y**2)/5
    Z = (Z - Z.min()) / (Z.max() - Z.min())

    # The color array can include masked values:
    Zm = ma.masked_where(np.fabs(Qz) < 0.5*np.amax(Qz), Z)

    fig = plt.figure()
    ax = fig.add_subplot(131)
    ax.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k')

    ax = fig.add_subplot(132)
    ax.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w'])

    ax = fig.add_subplot(133)
    ax.pcolormesh(Qx, Qz, Z, shading="gouraud") 
Example #8
Source File: thinkplot.py    From Lie_to_me with MIT License 6 votes vote down vote up
def Pcolor(xs, ys, zs, pcolor=True, contour=False, **options):
    """Makes a pseudocolor plot.
    
    xs:
    ys:
    zs:
    pcolor: boolean, whether to make a pseudocolor plot
    contour: boolean, whether to make a contour plot
    options: keyword args passed to plt.pcolor and/or plt.contour
    """
    _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)

    X, Y = np.meshgrid(xs, ys)
    Z = zs

    x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    axes = plt.gca()
    axes.xaxis.set_major_formatter(x_formatter)

    if pcolor:
        plt.pcolormesh(X, Y, Z, **options)

    if contour:
        cs = plt.contour(X, Y, Z, **options)
        plt.clabel(cs, inline=1, fontsize=10) 
Example #9
Source File: utils.py    From seq2seq-summarizer with MIT License 6 votes vote down vote up
def show_attention_map(src_words, pred_words, attention, pointer_ratio=None):
  fig, ax = plt.subplots(figsize=(16, 4))
  im = plt.pcolormesh(np.flipud(attention), cmap="GnBu")
  # set ticks and labels
  ax.set_xticks(np.arange(len(src_words)) + 0.5)
  ax.set_xticklabels(src_words, fontsize=14)
  ax.set_yticks(np.arange(len(pred_words)) + 0.5)
  ax.set_yticklabels(reversed(pred_words), fontsize=14)
  if pointer_ratio is not None:
    ax1 = ax.twinx()
    ax1.set_yticks(np.concatenate([np.arange(0.5, len(pred_words)), [len(pred_words)]]))
    ax1.set_yticklabels('%.3f' % v for v in np.flipud(pointer_ratio))
    ax1.set_ylabel('Copy probability', rotation=-90, va="bottom")
  # let the horizontal axes labelling appear on top
  ax.tick_params(top=True, bottom=False, labeltop=True, labelbottom=False)
  # rotate the tick labels and set their alignment
  plt.setp(ax.get_xticklabels(), rotation=-45, ha="right", rotation_mode="anchor") 
Example #10
Source File: test_axes.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pcolormesh_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolormesh(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolormesh(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolormesh(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example #11
Source File: logistic_regression.py    From Machine-Learning-Algorithms-Second-Edition with MIT License 6 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 #12
Source File: 1logistic_regression.py    From Machine-Learning-Algorithms with MIT License 6 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 #13
Source File: vis.py    From bird-species-classification with MIT License 6 votes vote down vote up
def plot_sound_class_by_decending_accuracy(experiment_path):
    config_parser = configparser.ConfigParser()
    config_parser.read(os.path.join(experiment_path, "conf.ini"))
    model_name = config_parser['MODEL']['ModelName']
    y_trues, y_scores = load_predictions(experiment_path)

    y_true = [np.argmax(y_t) for y_t in y_trues]
    y_pred = [np.argmax(y_s) for y_s in y_scores]

    confusion_matrix = metrics.confusion_matrix(y_true, y_pred)

    accuracies = []
    (nb_rows, nb_cols) = confusion_matrix.shape
    for i in range(nb_rows):
        accuracy = confusion_matrix[i][i] / np.sum(confusion_matrix[i,:])
        accuracies.append(accuracy)

    fig = plt.figure()
    plt.title("Sound Class ranked by Accuracy ({})".format(model_name))
    plt.plot(sorted(accuracies, reverse=True))
    plt.ylabel("Accuracy")
    plt.xlabel("Rank")
    # plt.pcolormesh(confusion_matrix, cmap=cmap)
    fig.savefig(os.path.join(experiment_path, "descending_accuracy.png")) 
Example #14
Source File: plotter.py    From plastering with MIT License 6 votes vote down vote up
def plot_colormap_upgrade(data, figSizeIn, xlabel, ylabel, cbarlabel, cmapIn, ytickRange, ytickTag, xtickRange=None, xtickTag=None, title=None, xmin=None, xmax=None, xgran=None, ymin=None, ymax=None, ygran=None):
    if xmin != None:
        y, x = np.mgrid[slice(ymin, ymax + ygran, ygran),
                slice(xmin, xmax + xgran, xgran)]
        fig = plt.figure(figsize = figSizeIn)
#       plt.pcolor(data, cmap=cmapIn)
        plt.pcolormesh(x, y, data, cmap=cmapIn)
        plt.grid(which='major',axis='both')
        plt.axis([x.min(), x.max(), y.min(), y.max()])
    else:
        plt.pcolor(data, cmap=cmapIn)

    cbar = plt.colorbar()
    cbar.set_label(cbarlabel, labelpad=-0.1)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
#   if xtickTag:
#       plt.xticks(xtickRange, xtickTag, fontsize=10)
#
#   plt.yticks(ytickRange, ytickTag, fontsize=10)
    plt.tight_layout()
    if title:
        plt.title(title)
    plt.show()
    return fig 
Example #15
Source File: visualize_flow.py    From ffjord with MIT License 6 votes vote down vote up
def plt_potential_func(potential, ax, npts=100, title="$p(x)$"):
    """
    Args:
        potential: computes U(z_k) given z_k
    """
    xside = np.linspace(LOW, HIGH, npts)
    yside = np.linspace(LOW, HIGH, npts)
    xx, yy = np.meshgrid(xside, yside)
    z = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])

    z = torch.Tensor(z)
    u = potential(z).cpu().numpy()
    p = np.exp(-u).reshape(npts, npts)

    plt.pcolormesh(xx, yy, p)
    ax.invert_yaxis()
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    ax.set_title(title) 
Example #16
Source File: feature_axis.py    From transparent_latent_gan with MIT License 6 votes vote down vote up
def plot_feature_correlation(feature_direction, feature_name=None):
    import matplotlib.pyplot as plt

    len_z, len_y = feature_direction.shape
    if feature_name is None:
        feature_name = range(len_y)

    feature_correlation = np.corrcoef(feature_direction.transpose())

    c_lim_abs = np.max(np.abs(feature_correlation))

    plt.pcolormesh(np.arange(len_y+1), np.arange(len_y+1), feature_correlation,
                   cmap='coolwarm', vmin=-c_lim_abs, vmax=+c_lim_abs)
    plt.gca().invert_yaxis()
    plt.colorbar()
    # plt.axis('square')
    plt.xticks(np.arange(len_y) + 0.5, feature_name, fontsize='x-small', rotation='vertical')
    plt.yticks(np.arange(len_y) + 0.5, feature_name, fontsize='x-small')
    plt.show() 
Example #17
Source File: visualize.py    From StackedDAE with Apache License 2.0 6 votes vote down vote up
def make_2d_hist(data, name):
    f = plt.figure()
    X,Y = np.meshgrid(range(data.shape[0]), range(data.shape[1]))
    im = plt.pcolormesh(X,Y,data.transpose(), cmap='seismic')
    plt.colorbar(im, orientation='vertical')
#     plt.hexbin(data,data)
#     plt.show()
    f.savefig(pjoin(FLAGS.output_dir, name + '.png'))
    plt.close()
    
# def make_2d_hexbin(data, name):
#     f = plt.figure()
#     X,Y = np.meshgrid(range(data.shape[0]), range(data.shape[1]))
#     plt.hexbin(X, data)
# #     plt.show()
#     f.savefig(pjoin(FLAGS.output_dir, name + '.png')) 
Example #18
Source File: som.py    From som with MIT License 6 votes vote down vote up
def plot_distance_map(self, colormap='Oranges', filename=None):
        """ Plot the distance map after training.

        :param colormap: {str} colormap to use, select from matplolib sequential colormaps
        :param filename: {str} optional, if given, the plot is saved to this location
        :return: plot shown or saved if a filename is given
        """
        if np.mean(self.distmap) == 0.:
            self.distance_map()
        fig, ax = plt.subplots(figsize=self.shape)
        plt.pcolormesh(self.distmap, cmap=colormap, edgecolors=None)
        plt.colorbar()
        plt.xticks(np.arange(.5, self.x + .5), range(self.x))
        plt.yticks(np.arange(.5, self.y + .5), range(self.y))
        plt.title("Distance Map", fontweight='bold', fontsize=28)
        ax.set_aspect('equal')
        if filename:
            plt.savefig(filename)
            plt.close()
            print("Distance map plot done!")
        else:
            plt.show() 
Example #19
Source File: visualize_flow.py    From UMNN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plt_flow(transform, ax, npts=300, title="$q(x)$", device="cpu"):
    """
    Args:
        transform: computes z_k and log(q_k) given z_0
    """
    side = np.linspace(LOW, HIGH, npts)
    xx, yy = np.meshgrid(side, side)
    x = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])
    with torch.no_grad():
        logqx, z = transform(torch.tensor(x).float().to(device))

    #xx = z[:, 0].cpu().numpy().reshape(npts, npts)
    #yy = z[:, 1].cpu().numpy().reshape(npts, npts)
    qz = np.exp(logqx.cpu().numpy()).reshape(npts, npts)

    plt.pcolormesh(xx, yy, qz)
    ax.set_xlim(LOW, HIGH)
    ax.set_ylim(LOW, HIGH)
    cmap = matplotlib.cm.get_cmap(None)
    ax.set_facecolor(cmap(0.))
    ax.invert_yaxis()
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    ax.set_title(title) 
Example #20
Source File: visualize_flow.py    From UMNN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plt_potential_func(potential, ax, npts=100, title="$p(x)$"):
    """
    Args:
        potential: computes U(z_k) given z_k
    """
    xside = np.linspace(LOW, HIGH, npts)
    yside = np.linspace(LOW, HIGH, npts)
    xx, yy = np.meshgrid(xside, yside)
    z = np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])

    z = torch.Tensor(z)
    u = potential(z).cpu().numpy()
    p = np.exp(-u).reshape(npts, npts)

    plt.pcolormesh(xx, yy, p)
    ax.invert_yaxis()
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    ax.set_title(title) 
Example #21
Source File: test_axes.py    From ImageFusion with MIT License 6 votes vote down vote up
def test_pcolormesh_datetime_axis():
    fig = plt.figure()
    fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
    base = datetime.datetime(2013, 1, 1)
    x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
    y = np.arange(21)
    z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
    z = z1 * z2
    plt.subplot(221)
    plt.pcolormesh(x[:-1], y[:-1], z)
    plt.subplot(222)
    plt.pcolormesh(x, y, z)
    x = np.repeat(x[np.newaxis], 21, axis=0)
    y = np.repeat(y[:, np.newaxis], 21, axis=1)
    plt.subplot(223)
    plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z)
    plt.subplot(224)
    plt.pcolormesh(x, y, z)
    for ax in fig.get_axes():
        for label in ax.get_xticklabels():
            label.set_ha('right')
            label.set_rotation(30) 
Example #22
Source File: test_axes.py    From ImageFusion with MIT License 6 votes vote down vote up
def test_pcolormesh():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Qx = np.cos(Y) - np.cos(X)
    Qz = np.sin(Y) + np.sin(X)
    Qx = (Qx + 1.1)
    Z = np.sqrt(X**2 + Y**2)/5
    Z = (Z - Z.min()) / (Z.max() - Z.min())

    # The color array can include masked values:
    Zm = ma.masked_where(np.fabs(Qz) < 0.5*np.amax(Qz), Z)

    fig = plt.figure()
    ax = fig.add_subplot(131)
    ax.pcolormesh(Qx, Qz, Z, lw=0.5, edgecolors='k')

    ax = fig.add_subplot(132)
    ax.pcolormesh(Qx, Qz, Z, lw=2, edgecolors=['b', 'w'])

    ax = fig.add_subplot(133)
    ax.pcolormesh(Qx, Qz, Z, shading="gouraud") 
Example #23
Source File: logistic_regression.py    From Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition with MIT License 6 votes vote down vote up
def plot_classification(classification, a , b):

	a_min, a_max = min(a[:, 0]) - 1.0, max(a[:, 0]) + 1.0
	b_min, b_max = min(a[:, 1]) - 1.0, max(a[:, 1]) + 1.0

	step_size = 0.01

	a_values, b_values = np.meshgrid(np.arange(a_min, a_max, step_size), np.arange(b_min, b_max, step_size))

	mesh_output1 = classification.predict(np.c_[a_values.ravel(), b_values.ravel()])

	mesh_output2 = mesh_output1.reshape(a_values.shape)

	plt.figure()

	plt.pcolormesh(a_values, b_values, mesh_output2, cmap=plt.cm.gray)

	plt.scatter(a[:, 0], a[:, 1], c=b , s=80, edgecolors='black', linewidth=1,cmap=plt.cm.Paired)
	# specify the boundaries of the figure
	plt.xlim(a_values.min(), a_values.max())
	plt.ylim(b_values.min(), b_values.max())
	# specify the ticks on the X and Y axes
	plt.xticks((np.arange(int(min(a[:, 0])-1), int(max(a[:, 0])+1), 1.0)))
	plt.yticks((np.arange(int(min(a[:, 1])-1), int(max(a[:, 1])+1), 1.0)))
	plt.show() 
Example #24
Source File: Building_Naive_Bayes_classifier.py    From Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition with MIT License 6 votes vote down vote up
def plot_classification(classification_gaussiannb, a , b):

	a_min, a_max = min(a[:, 0]) - 1.0, max(a[:, 0]) + 1.0
	b_min, b_max = min(a[:, 1]) - 1.0, max(a[:, 1]) + 1.0

	step_size = 0.01

	a_values, b_values = np.meshgrid(np.arange(a_min, a_max, step_size), np.arange(b_min, b_max, step_size))

	mesh_output1 = classification_gaussiannb.predict(np.c_[a_values.ravel(), b_values.ravel()])

	mesh_output2 = mesh_output1.reshape(a_values.shape)

	plt.figure()

	plt.pcolormesh(a_values, b_values, mesh_output2, cmap=plt.cm.gray)

	plt.scatter(a[:, 0], a[:, 1], c=b , s=80, edgecolors='black', linewidth=1,cmap=plt.cm.Paired)
	# specify the boundaries of the figure
	plt.xlim(a_values.min(), a_values.max())
	plt.ylim(b_values.min(), b_values.max())
	# specify the ticks on the X and Y axes
	plt.xticks((np.arange(int(min(a[:, 0])-1), int(max(a[:, 0])+1), 1.0)))
	plt.yticks((np.arange(int(min(a[:, 1])-1), int(max(a[:, 1])+1), 1.0)))
	plt.show() 
Example #25
Source File: plotter.py    From plastering with MIT License 6 votes vote down vote up
def plot_colormap_upgrade(data, figSizeIn, xlabel, ylabel, cbarlabel, cmapIn, ytickRange, ytickTag, xtickRange=None, xtickTag=None, title=None, xmin=None, xmax=None, xgran=None, ymin=None, ymax=None, ygran=None):
    if xmin != None:
        y, x = np.mgrid[slice(ymin, ymax + ygran, ygran),
                slice(xmin, xmax + xgran, xgran)]
        fig = plt.figure(figsize = figSizeIn)
#       plt.pcolor(data, cmap=cmapIn)
        plt.pcolormesh(x, y, data, cmap=cmapIn)
        plt.grid(which='major',axis='both')
        plt.axis([x.min(), x.max(), y.min(), y.max()])
    else:
        plt.pcolor(data, cmap=cmapIn)

    cbar = plt.colorbar()
    cbar.set_label(cbarlabel, labelpad=-0.1)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
#   if xtickTag:
#       plt.xticks(xtickRange, xtickTag, fontsize=10)
#
#   plt.yticks(ytickRange, ytickTag, fontsize=10)
    plt.tight_layout()
    if title:
        plt.title(title)
    plt.show()
    return fig 
Example #26
Source File: Main_GUI.py    From CNNArt with Apache License 2.0 5 votes vote down vote up
def change_layer(self, value):
        num = int(value.find(")"))
        print(value)
        current_mrt_layer = 0
        if num == 2:
            current_mrt_layer = int(self.layer.get()[1:2]) - 1
        elif num == 3:
            current_mrt_layer = int(self.layer.get()[1:3]) - 1

        ArrayDicom = self.mrt_layer_set[current_mrt_layer].get_Dicom_array()
        plt.cla()
        plt.xlim(0, self.mrt_layer_set[current_mrt_layer].get_mrt_width())
        plt.ylim(self.mrt_layer_set[current_mrt_layer].get_mrt_height(), 0)
        plt.pcolormesh(self.mrt_layer_set[current_mrt_layer].get_x_arange(),
                       self.mrt_layer_set[current_mrt_layer].get_y_arange(), np.rot90(
                ArrayDicom[:, :, 0]))
        self.number_mrt_label.config(text=str("1/" + str(self.mrt_layer_set[current_mrt_layer].get_number_mrt())))
        loadFile = shelve.open("mark_mrt_layer.slv")
        number_Patch = 0
        if loadFile.has_key(self.mrt_layer_set[current_mrt_layer].get_model_name()):
            layer_name = self.mrt_layer_set[current_mrt_layer].get_model_name()
            layer = loadFile[layer_name]
            while layer.has_key(str(self.mrt_layer_set[current_mrt_layer].get_current_Number()) + "_" + str(
                    number_Patch)):
                num_str = str(self.mrt_layer_set[current_mrt_layer].get_current_Number()) + "_" + str(number_Patch)
                p = loadFile[layer_name][num_str]
                patch = None
                if self.chooseArtefact.get() == self.artefact_list[0]:
                    patch = patches.PathPatch(p, fill=False, edgecolor='red', lw=2)
                elif self.chooseArtefact.get() == self.artefact_list[1]:
                    patch = patches.PathPatch(p, fill=False, edgecolor='green', lw=2)
                elif self.chooseArtefact.get() == self.artefact_list[2]:
                    patch = patches.PathPatch(p, fill=False, edgecolor='blue', lw=2)
                self.ax.add_patch(patch)
                number_Patch += 1
        self.fig.canvas.draw_idle() 
Example #27
Source File: test_colors.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_cmap_and_norm_from_levels_and_colors():
    data = np.linspace(-2, 4, 49).reshape(7, 7)
    levels = [-1, 2, 2.5, 3]
    colors = ['red', 'green', 'blue', 'yellow', 'black']
    extend = 'both'
    cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend=extend)

    ax = plt.axes()
    m = plt.pcolormesh(data, cmap=cmap, norm=norm)
    plt.colorbar(m)

    # Hide the axes labels (but not the colorbar ones, as they are useful)
    for lab in ax.get_xticklabels() + ax.get_yticklabels():
        lab.set_visible(False) 
Example #28
Source File: test_axes.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_pcolorargs():
    n = 12
    x = np.linspace(-1.5, 1.5, n)
    y = np.linspace(-1.5, 1.5, n*2)
    X, Y = np.meshgrid(x, y)
    Z = np.sqrt(X**2 + Y**2)/5

    _, ax = plt.subplots()
    assert_raises(TypeError, ax.pcolormesh, y, x, Z)
    assert_raises(TypeError, ax.pcolormesh, X, Y, Z.T)
    assert_raises(TypeError, ax.pcolormesh, x, y, Z[:-1, :-1],
                  shading="gouraud")
    assert_raises(TypeError, ax.pcolormesh, X, Y, Z[:-1, :-1],
                  shading="gouraud") 
Example #29
Source File: statistic.py    From mtl with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save_latest_example(self, ind, example_labelsID, example_Disparity, example_InstanceID):
        scipy.misc.imsave(os.path.join(FLAGS.example_preds, "example_%08d_latest_label.png" % (ind)), example_labelsID)
        scipy.misc.imsave(os.path.join(FLAGS.example_preds, "example_%08d_latest_disp.png" % (ind)), example_Disparity.squeeze())
        if (self.epoch_num + 1) % FLAGS.example_OPTICS_epoch == 0:
            scipy.misc.imsave(os.path.join(FLAGS.example_preds, "example_%08d_latest_instance.png" % (ind)), example_InstanceID[0])
        plt.clf()
        plt.pcolormesh(example_InstanceID[3], cmap='jet')
        plt.gca().invert_yaxis()
        plt.savefig(os.path.join(FLAGS.example_preds, 'instance', "y_reg", "example_%08d_latest.png" % (ind)))
        plt.clf()
        plt.pcolormesh(example_InstanceID[4], cmap='jet')
        plt.gca().invert_yaxis()
        plt.savefig(os.path.join(FLAGS.example_preds, 'instance', "x_reg", "example_%08d_latest.png" % (ind)))
        np.save(os.path.join(FLAGS.example_preds, 'instance', "y_reg", "example_%08d_latest" % (ind)), example_InstanceID[3])
        np.save(os.path.join(FLAGS.example_preds, 'instance', "x_reg", "example_%08d_latest" % (ind)), example_InstanceID[4]) 
Example #30
Source File: modules_v2.py    From Transformer-in-generating-dialogue with Apache License 2.0 5 votes vote down vote up
def positional_encoding(seq_len, num_units, visualization=False):
	"""
	Positional_Encoding for a given tensor.

	Args:
		:param inputs: [Tensor], A tensor contains the ids to be search from the lookup table, shape = [batch_size, seq_len]
		:param num_units: [Int], Hidden size of embedding
		:param visualization: [Boolean], If True, it will plot the graph of position encoding
		:return: [Tensor] A tensor with shape [1, seq_len, num_units]
	"""
	def __get_angles(pos, i, d_model):
		angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_model))
		return pos * angle_rates

	angle_rads = __get_angles(np.arange(seq_len)[:, np.newaxis],
							  np.arange(num_units)[np.newaxis, :],
							  num_units)

	sine = np.sin(angle_rads[:, 0::2])
	cosine = np.cos(angle_rads[:, 1::2])

	pos_encoding = np.concatenate([sine, cosine], axis=-1)
	pos_encoding = pos_encoding[np.newaxis, ...]

	if visualization:
		plt.figure(figsize=(12, 8))
		plt.pcolormesh(pos_encoding[0], cmap='RdBu')
		plt.xlabel('Depth')
		plt.xlim((0, num_units))
		plt.ylabel('Position')
		plt.colorbar()
		plt.show()

	return tf.cast(pos_encoding, tf.float32)