Python matplotlib.pyplot.matshow() Examples

The following are code examples for showing how to use matplotlib.pyplot.matshow(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: PyTorch-tutorials-kr-0.4   Author: 9bow   File: seq2seq_translation_tutorial.py    BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def showAttention(input_sentence, output_words, attentions):
    # colorbar로 그림 설정
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(attentions.numpy(), cmap='bone')
    fig.colorbar(cax)

    # 축 설정
    ax.set_xticklabels([''] + input_sentence.split(' ') +
                       ['<EOS>'], rotation=90)
    ax.set_yticklabels([''] + output_words)

    # 매 틱마다 라벨 보여주기
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

    plt.show() 
Example 2
Project: jr-tools   Author: kingjr   File: test_clf.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def show_circular_data():
    import matplotlib.pyplot as plt
    epochs, angles = make_circular_data()
    coefs = list()
    sel_time = 1  # select only one time point
    for ii in np.unique(angles):
        # select each trial
        sel_y = np.where(angles == ii)[0]
        # get mean effect
        coef = np.mean(epochs._data[sel_y, :, sel_time], axis=0)
        # square image
        coef = np.reshape(coef, [np.sqrt(len(coef))] * 2)
        coefs.append()
    for coef in coefs:
        plt.matshow(coef[:, 1])
    plt.show() 
Example 3
Project: MiaSeg   Author: jajenQin   File: Miaimshow.py    GNU General Public License v3.0 6 votes vote down vote up
def discrete_matshow(data, labels_names=[], title=""):
    # get discrete colormap
    cmap = plt.get_cmap('Paired', np.max(data) - np.min(data) + 1)
    # set limits .5 outside true range
    mat = plt.matshow(data,
                      cmap=cmap,
                      vmin=np.min(data) - .5,
                      vmax=np.max(data) + .5)
    # tell the colorbar to tick at integers
    cax = plt.colorbar(mat,
                       ticks=np.arange(np.min(data), np.max(data) + 1))

    # The names to be printed aside the colorbar
    if labels_names:
        cax.ax.set_yticklabels(labels_names)

    if title:
        plt.suptitle(title, fontsize=14, fontweight='bold') 
Example 4
Project: Deep-Learning-with-TensorFlow-Second-Edition   Author: PacktPublishing   File: denoising_autoencoder.py    MIT License 6 votes vote down vote up
def plotresult(org_vec,noisy_vec,out_vec):
    plt.matshow(np.reshape(org_vec, (28, 28)), cmap=plt.get_cmap('gray'))
    plt.title("Original Image")
    plt.colorbar()

    plt.matshow(np.reshape(noisy_vec, (28, 28)), cmap=plt.get_cmap('gray'))
    plt.title("Input Image")
    plt.colorbar()
    
    outimg = np.reshape(out_vec, (28, 28))
    plt.matshow(outimg, cmap=plt.get_cmap('gray'))
    plt.title("Reconstructed Image")
    plt.colorbar()
    plt.show()

# NETOWRK PARAMETERS 
Example 5
Project: Deep-Learning-with-TensorFlow-Second-Edition   Author: PacktPublishing   File: deconvolutional_autoencoder.py    MIT License 6 votes vote down vote up
def plotresult(org_vec,noisy_vec,out_vec):
    plt.matshow(np.reshape(org_vec, (28, 28)), cmap=plt.get_cmap('gray'))
    plt.title("Original Image")
    plt.colorbar()

    plt.matshow(np.reshape(noisy_vec, (28, 28)), cmap=plt.get_cmap('gray'))
    plt.title("Input Image")
    plt.colorbar()
    
    outimg = np.reshape(out_vec, (28, 28))
    plt.matshow(outimg, cmap=plt.get_cmap('gray'))
    plt.title("Reconstructed Image")
    plt.colorbar()
    plt.show()

# NETOWORK PARAMETERS 
Example 6
Project: PyTorch-tutorials-kr-0.4   Author: 9bow   File: seq2seq_translation_tutorial.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def showAttention(input_sentence, output_words, attentions):
    # colorbar로 그림 설정
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(attentions.numpy(), cmap='bone')
    fig.colorbar(cax)

    # 축 설정
    ax.set_xticklabels([''] + input_sentence.split(' ') +
                       ['<EOS>'], rotation=90)
    ax.set_yticklabels([''] + output_words)

    # 매 틱마다 라벨 보여주기
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

    plt.show() 
Example 7
Project: PyTorch-tutorials-kr-0.4   Author: 9bow   File: seq2seq_translation_tutorial.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def showAttention(input_sentence, output_words, attentions):
    # colorbar로 그림 설정
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(attentions.numpy(), cmap='bone')
    fig.colorbar(cax)

    # 축 설정
    ax.set_xticklabels([''] + input_sentence.split(' ') +
                       ['<EOS>'], rotation=90)
    ax.set_yticklabels([''] + output_words)

    # 매 틱마다 라벨 보여주기
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

    plt.show() 
Example 8
Project: hdnet   Author: team-hdnet   File: visualization.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_matrix_whole_canvas(matrix, **kwargs):
    """
    Missing documentation

    Parameters
    ----------
    matrix : Type
        Description
    kwargs : Type
        Description

    Returns
    -------
    Value : Type
        Description
    """
    ax = plt.axes([0, 0, 1, 1])
    ax.matshow(matrix, **kwargs)
    plt.axis('off')
    return ax 
Example 9
Project: Food-Volume-Estimation   Author: KaiwenZha   File: visualization.py    MIT License 6 votes vote down vote up
def _discrete_matshow_adaptive(data, labels_names=[], title=""):

    fig_size = [7, 6]
    plt.rcParams["figure.figsize"] = fig_size
    cmap = plt.get_cmap('Paired', np.max(data)-np.min(data)+1)
    mat = plt.matshow(data,
                      cmap=cmap,
                      vmin = np.min(data)-.5,
                      vmax = np.max(data)+.5)

    cax = plt.colorbar(mat,
                       ticks=np.arange(np.min(data),np.max(data)+1))

    if labels_names:
        cax.ax.set_yticklabels(labels_names)
    
    if title:
        plt.suptitle(title, fontsize=15, fontweight='bold')

    fig = plt.gcf()
    fig.savefig('data/tmp.jpg', dpi=300)
    img = cv2.imread('data/tmp.jpg')
    return img 
Example 10
Project: stock_img_clf   Author: ernest222   File: someplots.py    MIT License 6 votes vote down vote up
def plot_heatmaps(self,con2dlayer_name,con2dlayer_channel): # 打印某层的热力图
        model = load_model(self.model_path)
        predict_result=self.predict()
        shape_output = model.output[:, predict_result]
        last_conv_layer = model.get_layer(con2dlayer_name)
        grads = K.gradients(shape_output, last_conv_layer.output)[0]
        pooled_grads = K.mean(grads, axis=(0, 1, 2))
        iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])
        pooled_grads_value, conv_layer_output_value = iterate([self.img_to_tensor()])
        for i in range(con2dlayer_channel):
            conv_layer_output_value[:, :, i] *= pooled_grads_value[i]
        heatmap = np.mean(conv_layer_output_value, axis=-1)
        heatmap = np.maximum(heatmap, 0)
        heatmap /= np.max(heatmap)
        # print(heatmap)
        plt.matshow(heatmap)
        plt.show()
        plt.matshow(heatmap)
        img = cv2.imread(self.img_path)
        heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
        heatmap = np.uint8(255 * heatmap)
        heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
        superimposed_img = heatmap * 0.9 + img
        cv2.imwrite(result_dir+os.sep+str(predict_result)+'_heatmap.jpg', superimposed_img) 
Example 11
Project: ANYstructure   Author: audunarn   File: compartment_window.py    GNU General Public License v3.0 6 votes vote down vote up
def draw_grid(self):
        '''
        Drawing grid
        EMPTY = yellow
        FULL = red
        :return:
        '''
        # TODO make a better plot of the tanks
        def discrete_matshow(data):
            # get discrete colormap
            cmap = plt.get_cmap('RdBu', np.max(data) - np.min(data) + 1)
            # set limits .5 outside true range
            mat = plt.matshow(data, cmap=cmap, vmin=np.min(data) - .5, vmax=np.max(data) + .5)
            # tell the colorbar to tick at integers
            cax = plt.colorbar(mat, ticks=np.arange(np.min(data), np.max(data) + 1))
        # # generate data
        # a = np.random.randint(1, 20, size=(10, 10))
        discrete_matshow(self.grid.get_matrix())
        plt.suptitle('Tanks defined by numbers from 2 and up.')
        return plt
        #plt.show() 
Example 12
Project: pgn   Author: yobibyte   File: sort.py    MIT License 6 votes vote down vote up
def plot_test(model, length, cuda=False):

    unsorted = np.random.uniform(size=length)
    test_g = graph_data_from_list(unsorted)

    test_g = list(batch_data([test_g]))
    if cuda and torch.cuda.is_available():
        test_g[0] = test_g[0].to("cuda")
        for k in test_g[1]:
            test_g[1][k] = test_g[1][k].to("cuda")
            test_g[2][k] = test_g[2][k].to("cuda")

    g = model(*test_g)[1]["default"]
    conn = test_g[2]["default"]

    # evaluate and plot
    mx = np.zeros((len(unsorted), len(unsorted)))
    for eid in range(g.shape[0]):
        mx[conn[0, eid].item()][conn[1, eid].item()] = g[eid, 0].item()

    sort_indices = np.argsort(unsorted)
    plt.matshow(mx[sort_indices][:, sort_indices], cmap="viridis")
    plt.grid(False)
    plt.savefig("pgn_sorting_output.png") 
Example 13
Project: PyTorch-tutorials-kr-0.3.1   Author: 9bow   File: seq2seq_translation_tutorial.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def showAttention(input_sentence, output_words, attentions):
    # colorbar로 그림 설정
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(attentions.numpy(), cmap='bone')
    fig.colorbar(cax)

    # 축 설정
    ax.set_xticklabels([''] + input_sentence.split(' ') +
                       ['<EOS>'], rotation=90)
    ax.set_yticklabels([''] + output_words)

    # 매 틱마다 라벨 보여주기
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

    plt.show() 
Example 14
Project: fiction   Author: tedunderwood   File: methodological_experiment.py    MIT License 5 votes vote down vote up
def first_experiment():

    sourcefolder = '../data/'
    metadatapath = '../metadata/mastermetadata.csv'
    vocabpath = '../modeloutput/experimentalvocab.txt'
    tags4positive = {'fantasy_loc', 'fantasy_oclc'}
    tags4negative = {'sf_loc', 'sf_oclc'}
    sizecap = 200

    metadata, masterdata, classvector, classdictionary, orderedIDs, authormatches, vocablist = versatiletrainer2.get_simple_data(sourcefolder, metadatapath, vocabpath, tags4positive, tags4negative, sizecap)

    c_range = [.004, .012, 0.3, 0.8, 2]
    featurestart = 3000
    featureend = 4400
    featurestep = 100
    modelparams = 'logistic', 10, featurestart, featureend, featurestep, c_range

    matrix, maxaccuracy, metadata, coefficientuples, features4max, best_regularization_coef = versatiletrainer2.tune_a_model(metadata, masterdata, classvector, classdictionary, orderedIDs, authormatches, vocablist, tags4positive, tags4negative, modelparams, 'first_experiment', '../modeloutput/first_experiment.csv')

    plt.rcParams["figure.figsize"] = [9.0, 6.0]
    plt.matshow(matrix, origin = 'lower', cmap = plt.cm.YlOrRd)
    plt.show() 
Example 15
Project: it-net   Author: wentaoyuan   File: visu_util.py    MIT License 5 votes vote down vote up
def plot_conf(figpath, conf):
    plt.figure(figsize=(6, 6))
    plt.matshow(conf)
    plt.colorbar()
    plt.xlabel('Ground truth', verticalalignment='top')
    plt.ylabel('Prediction')
    plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.savefig(figpath) 
Example 16
Project: ludwig   Author: uber   File: visualization_utils.py    Apache License 2.0 5 votes vote down vote up
def confusion_matrix_plot(
        confusion_matrix,
        labels=None,
        output_feature_name=None,
        filename=None
):
    mpl.rcParams.update({'figure.autolayout': True})
    fig, ax = plt.subplots()

    ax.invert_yaxis()
    ax.xaxis.tick_top()
    ax.xaxis.set_label_position('top')

    cax = ax.matshow(confusion_matrix, cmap='viridis')

    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.set_xticklabels([''] + labels, rotation=45, ha='left')
    ax.set_yticklabels([''] + labels)
    ax.grid(False)
    ax.tick_params(axis='both', which='both', length=0)
    fig.colorbar(cax, ax=ax, extend='max')
    ax.set_xlabel('Predicted {}'.format(output_feature_name))
    ax.set_ylabel('Actual {}'.format(output_feature_name))

    plt.tight_layout()
    ludwig.contrib.contrib_command("visualize_figure", plt.gcf())
    if filename:
        plt.savefig(filename)
    else:
        plt.show() 
Example 17
Project: ludwig   Author: uber   File: visualization_utils.py    Apache License 2.0 5 votes vote down vote up
def plot_matrix(
        matrix,
        cmap='hot',
        filename=None
):
    plt.matshow(matrix, cmap=cmap)
    ludwig.contrib.contrib_command("visualize_figure", plt.gcf())
    if filename:
        plt.savefig(filename)
    else:
        plt.show() 
Example 18
Project: SpecPatConv3D-Network   Author: custom-computing-ic   File: helper.py    Apache License 2.0 5 votes vote down vote up
def GroundTruthVisualise(data, dataset, original=True):
    from matplotlib.pyplot import imshow, show, colorbar, set_cmap, clim
    import matplotlib.pyplot as plt
    import numpy as np

    labels = []

    if dataset == 'Indian_pines':
        if original:
            labels = ['Unlabelled','Corn-notil', 'Corn-mintill','Corn', 'Grass-pasture','Grass-trees','Hay-windrowed','Soybean-notil','Soybean-mintil','Soybean-clean','Woods','BGTD']
        else:
            labels = []

    elif dataset == 'Salinas':        
        labels = ['Unlabelled', 'Brocoli green weeds 1', 'Brocoli green weeds 2', 'Fallow', 'Fallow rough plow', 'Fallow smooth', 'Stubble', 'Celery','Grapes untrained', 'Soil vinyard develop', 'Corn senesced green weeds', 'Lettuce romaine 4wk', 'Lettuce romaine 5wk', 'Lettuce romaine 6wk', 'Lettuce romaine 7wk', 'Vinyard untrained', 'Vunyard vertical trellis']

    elif dataset == 'KSC':
        labels = ['Unlabelled','Scrub','Williw swamp','SP hammock','Slash pine','Oak/Broadleaf','Hardwood','Swamp','Gramminoid marsh','Spartina marsh','Cattail marsh','Salt marsh','Mud flats','Water']

    def discrete_matshow(data):
        #get discrete colormap
        cmap = plt.get_cmap('tab20', np.max(data)-np.min(data)+1)
        # set limits .5 outside true range
        mat = plt.matshow(data, cmap=cmap, vmin=np.min(data)-0.5, vmax=np.max(data)+0.5)
        #tell the colorbar to tick at integers
        cax = plt.colorbar(mat, ticks=np.arange(np.min(data),np.max(data)+1))

        cax.ax.set_yticklabels(labels)

    imshow(data)
    discrete_matshow(data)
    show()

# Arguement: data = 3D image in size (h,w,bands) 
Example 19
Project: FaceDetection   Author: GeekLiB   File: testProject.py    MIT License 5 votes vote down vote up
def func():
        assert False
        pyplot.matshow(self.image)
        pylab.show() 
Example 20
Project: FaceDetection   Author: GeekLiB   File: image.py    MIT License 5 votes vote down vote up
def show(image = None):
        if image == None:
            return
        pyplot.matshow(image)
        pylab.show() 
Example 21
Project: analyze_roots   Author: eichblatt   File: analizo.py    GNU General Public License v3.0 5 votes vote down vote up
def spectral_cluster(dataframe,n_clusters=(30,30),show_plots=False):
  model = SpectralBiclustering(n_clusters=n_clusters, method='log',random_state=0)
  data=dataframe.fillna(0.0).values
  model.fit(data)

  fit_data = data[np.argsort(model.row_labels_)]
  fit_data = fit_data[:, np.argsort(model.column_labels_)]

  if show_plots:
    plt.matshow(fit_data, cmap=plt.cm.Blues)
    plt.title("After biclustering; rearranged to show biclusters")
    plt.matshow(np.outer(np.sort(model.row_labels_) + 1, np.sort(model.column_labels_) + 1), cmap=plt.cm.Blues)
    plt.title("Checkerboard structure of rearranged data")
  
  return model 
Example 22
Project: analyze_roots   Author: eichblatt   File: gettexts.py    GNU General Public License v3.0 5 votes vote down vote up
def spectral_cluster(dataframe,n_clusters=(30,30),show_plots=False):
  model = SpectralBiclustering(n_clusters=n_clusters, method='log',random_state=0)
  data=dataframe.fillna(0.0).values
  model.fit(data)

  fit_data = data[np.argsort(model.row_labels_)]
  fit_data = fit_data[:, np.argsort(model.column_labels_)]

  if show_plots:
    plt.matshow(fit_data, cmap=plt.cm.Blues)
    plt.title("After biclustering; rearranged to show biclusters")
    plt.matshow(np.outer(np.sort(model.row_labels_) + 1, np.sort(model.column_labels_) + 1), cmap=plt.cm.Blues)
    plt.title("Checkerboard structure of rearranged data")
  
  return model 
Example 23
Project: chicago-crime   Author: thekingofkings   File: LinearModel.py    MIT License 5 votes vote down vote up
def dynamicLR(features, Y, S, eta = 1):
    """
    dimensions of each variables
    
        features: N x c
        Y: N x 1
        S: N x N
        W: (N+1) x c
    """
    assert len(Y) == features.shape[0]
    N = len(Y)
    c = features.shape[1]
    W = rnd.rand(N+1, c)
    # append the all 0 w_N
    W[N,] = 0
    S = np.vstack( (S, np.ones(N)) )
    S = np.hstack( (S, np.ones((N+1,1))) )
    
    import sys
    er_prev = sys.maxint
    er = dynamicLR_error(W, features, Y, S, eta)
    
    while (abs(er_prev - er) / er > 0.0001 ):
#        print er
        # update W
        for i in range(N):
            W[i,] = update_wi(features[i,], S[i,], Y[i], W, i, eta)
        er_prev = er
        er = dynamicLR_error(W, features, Y, S, eta)
    
#    print "dynamic LR training finished"
    
#    plt.matshow(W)
    return W 
Example 24
Project: chicago-crime   Author: thekingofkings   File: plotMat.py    MIT License 5 votes vote down vote up
def plot_flowType_CrimeCount():
    xlabels = ['ARSON', 'ASSAULT', 'BATTERY', 'BURGLARY', 'CRIM SEXUAL ASSAULT', 
        'CRIMINAL DAMAGE', 'CRIMINAL TRESPASS', 'DECEPTIVE PRACTICE', 
        'GAMBLING', 'HOMICIDE', 'INTERFERENCE WITH PUBLIC OFFICER', 
        'INTIMIDATION', 'KIDNAPPING', 'LIQUOR LAW VIOLATION', 'MOTOR VEHICLE THEFT', 
        'NARCOTICS', 'OBSCENITY', 'OFFENSE INVOLVING CHILDREN', 'OTHER NARCOTIC VIOLATION',
        'OTHER OFFENSE', 'PROSTITUTION', 'PUBLIC INDECENCY', 'PUBLIC PEACE VIOLATION',
        'ROBBERY', 'SEX OFFENSE', 'STALKING', 'THEFT', 'WEAPONS VIOLATION', 'total']
    x = range(len(xlabels))
    
    ylabels = ['#jobs age under 29', 
    '#jobs age from 30 to 54', 
    '#jobs above 55', 
    '#jobs earning under \$1250/month', 
    '#jobs earnings from \$1251 to \$3333/month', 
    '#jobs above \$3333/month',
    '#jobs in goods producing', 
    '#jobs in trade transportation', 
    '#jobs in other services']
    y = range(len(ylabels))
        
        
    type_tag = 'mre2'
    
    d = np.loadtxt('{0}.array'.format(type_tag))
    for i in range(d.shape[0]):
        for j in range(d.shape[1]):
            if abs(d[i,j]) > 1:
                d[i,j] /= abs(d[i,j])
    
    plt.figure(num=1, figsize=(16,8))
    img = plt.matshow(d, fignum=1)
    plt.colorbar(img)
    plt.xticks(x, xlabels, rotation='vertical')
    plt.yticks(y, ylabels)
    plt.savefig('{0}.png'.format(type_tag), format='png') 
Example 25
Project: Neural-Network-in-Python-using-Numpy   Author: IAmSuyogJadhav   File: train.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    """
    Used to plot confusion matrix.
    """
    
    plt.matshow(df_confusion, cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)
    plt.show() 
Example 26
Project: Neural-Network-Programming-with-TensorFlow   Author: PacktPublishing   File: cnn_dogs_cats.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(cls_pred, data):
    # cls_pred is an array of the predicted class-number for
    # all images in the test-set.

    # Get the true classifications for the test-set.
    cls_true = data.valid.cls
    
    # Get the confusion matrix using sklearn.
    cm = confusion_matrix(y_true=cls_true,
                          y_pred=cls_pred)

    # Print the confusion matrix as text.
    print(cm)

    # Plot the confusion matrix as an image.
    plt.matshow(cm)

    # Make various adjustments to the plot.
    plt.colorbar()
    tick_marks = np.arange(num_classes)
    plt.xticks(tick_marks, range(num_classes))
    plt.yticks(tick_marks, range(num_classes))
    plt.xlabel('Predicted')
    plt.ylabel('True')

    # Ensure the plot is shown correctly with multiple plots
    # in a single Notebook cell.
    plt.show() 
Example 27
Project: hdnet   Author: team-hdnet   File: visualization.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_all_matrices(matrices, file_names, cmap='gray', colorbar=True, vmin=None, vmax=None):
    """
    Missing documentation

    Parameters
    ----------
    matrices : Type
        Description
    file_names : Type
        Description
    cmap : str, optional
        Description (default 'gray')
    colorbar : bool, optional
        Description (default True)
    vmin : Type, optional
        Description (default None)
    vmax : Type, optional
        Description (default None)

    Returns
    -------
    Value : Type
        Description
    """
    # plot all matrices to files specified
    kwargs = {
        'cmap': cmap
    }
    if vmin is not None:
        kwargs['vmin'] = vmin
    if vmax is not None:
        kwargs['vmax'] = vmax
    for m, fn in zip(matrices, file_names):
        plt.figure()
        plt.matshow(m, **kwargs)
        if colorbar:
            plt.colorbar()
        plt.savefig(fn)
        plt.close() 
Example 28
Project: hdnet   Author: team-hdnet   File: visualization.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_network(network, filename = 'Jtheta.png', cmap = 'jet', axis = False, colorbar = True, overwrite = False):
    if os.path.exists(filename) and not overwrite:
        hdlog.error('plot_network: file name exists: {}, pass overwrite = True to overwrite'.format(filename))
        return

    plt.figure()
    mat = network.J.copy()
    mat[np.diag_indices(mat.shape[0])] = network.theta.ravel()
    plt.matshow(mat, cmap = cmap)
    if colorbar:
        plt.colorbar()
    if not axis:
        plt.axis('off')
    plt.savefig(filename)
    plt.close() 
Example 29
Project: hdnet   Author: team-hdnet   File: visualization.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_hopfield_patterns(patterns, path, format = 'png', window_size = 1, memories = True, mtas = True, overwrite = False):
    if os.path.exists(path):
        if not overwrite:
            hdlog.error('plot_overview_hofield_patterns: path exists: {}, pass overwrite = True to overwrite'.format(path))
            return
    else:
        os.makedirs(path)

    def _save_mat(fn, mat):
        plt.figure()
        ax = plt.axes([0, 0, 1, 1])
        ax.matshow(mat, cmap = 'gray')
        ax.axes.get_xaxis().set_ticks([])
        ax.axes.get_yaxis().set_ticks([])
        plt.savefig(fn)
        plt.close()

    npats = len(patterns.patterns)
    digits = int(np.ceil(np.log10(npats))) + 1
    suffix  = '{{0:0>{}d}}.{}'.format(digits, format)
    if memories:
        fn = 'memory' + suffix
        for i in range(npats):
            pat = patterns.pattern_to_binary_matrix(i)
            patmat = pat.reshape((len(pat) // window_size, window_size))
            _save_mat(os.path.join(path, fn.format(i)), patmat)

    if mtas:
        fn = 'mta' + suffix
        for i in range(npats):
            pat = patterns.pattern_to_mta_matrix(i)
            patmat = pat.reshape((len(pat) // window_size, window_size))
            _save_mat(os.path.join(path, fn.format(i)), patmat)


# end of source 
Example 30
Project: ipynb   Author: OpenBookProjects   File: pidigits.py    MIT License 5 votes vote down vote up
def plot_two_digit_freqs(f2):
    """
    Plot two digits frequency counts using matplotlib.
    """
    f2_copy = f2.copy()
    f2_copy.shape = (10,10)
    ax = plt.matshow(f2_copy)
    plt.colorbar()
    for i in range(10):
        for j in range(10):
            plt.text(i-0.2, j+0.2, str(j)+str(i))
    plt.ylabel('First digit')
    plt.xlabel('Second digit')
    return ax 
Example 31
Project: citemap   Author: ai-se   File: model.py    The Unlicense 5 votes vote down vote up
def make_heatmap(arr, row_labels, column_labels, title, figname):
  plt.figure(figsize=(4, 3))
  df = pd.DataFrame(arr, columns=column_labels, index=row_labels)
  cax = plt.matshow(df, interpolation='nearest', cmap='hot_r')
  plt.colorbar(cax)
  plt.xticks(np.arange(len(list(df.columns))), list(df.columns), rotation="vertical")
  plt.yticks(np.arange(len(list(df.index))), list(df.index))
  plt.title("Topics to Conference Distribution for %s" % title, y=1.2)
  plt.savefig(figname, bbox_inches='tight')
  plt.clf() 
Example 32
Project: citemap   Author: ai-se   File: scrutinize.py    The Unlicense 5 votes vote down vote up
def desk_rejects():
  papers = read_papers()
  vectorize(papers)
  submissions = format_conf_acceptance(papers)
  for conf_id, papers in submissions.items():
    a_topics, a_count = np.array([0] * N_TOPICS), 0
    r_topics, r_count = np.array([0] * N_TOPICS), 0
    da_topics, da_count = np.array([0] * N_TOPICS), 0
    dr_topics, dr_count = np.array([0] * N_TOPICS), 0
    for paper in papers:
      if paper.raw_decision == 'pre-reject':
        dr_topics = np.add(dr_topics, paper.transformed)
        dr_count += 1
      elif paper.raw_decision == 'pre-accept':
        da_topics = np.add(da_topics, paper.transformed)
        da_count += 1
      elif paper.decision == 'reject':
        r_topics = np.add(r_topics, paper.transformed)
        r_count += 1
      elif paper.decision == 'accept':
        a_topics = np.add(a_topics, paper.transformed)
        a_count += 1

    if dr_count > 0: dr_topics = dr_topics / float(dr_count)
    if da_count > 0: da_topics = da_topics / float(da_count)
    if r_count > 0: r_topics = r_topics / float(r_count)
    if a_count > 0: a_topics = a_topics / float(a_count)
    col_labels = TOPICS
    row_labels = ["Accept - Desk Rejects"]
    heatmap_arr = np.array([[int(round(100 * (a - dr), 0)) for dr, a in zip(dr_topics, a_topics)]], np.int)
    cmap = mpl.colors.ListedColormap(['red', 'lightsalmon', 'white', 'palegreen', 'lime'])
    bounds = [-10, -8, -2, 2, 8, 10]
    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
    cax = plt.matshow(heatmap_arr, interpolation='nearest', cmap=cmap, norm=norm)
    for (i, j), z in np.ndenumerate(heatmap_arr):
      plt.text(j, i, abs(z), ha='center', va='center', fontsize=11)
    ticks = [-20, -10, 0, 10, 20]
    plt.colorbar(cax, cmap=cmap, norm=norm, boundaries=bounds, ticks=ticks)
    plt.xticks(np.arange(len(list(col_labels))), list(col_labels), rotation="vertical")
    plt.yticks(np.arange(len(list(row_labels))), list(row_labels))
    plt.savefig("classify/figs/desks-%s.png" % conf_id, bbox_inches='tight') 
Example 33
Project: citemap   Author: ai-se   File: expts_v3.py    The Unlicense 5 votes vote down vote up
def make_heatmap(arr, row_labels, column_labels, figname, paper_range):
  plt.figure(figsize=(4, 3))
  df = pd.DataFrame(arr, columns=column_labels, index=row_labels)
  cax = plt.matshow(df, interpolation='nearest', cmap='hot_r')
  plt.colorbar(cax)
  plt.xticks(np.arange(len(list(df.columns))), list(df.columns), rotation="vertical")
  plt.yticks(np.arange(len(list(df.index))), list(df.index))
  [tick.set_color("red") if tick.get_text() in CONFERENCES else tick.set_color("green") for tick in plt.gca().get_xticklabels()]
  if paper_range:
    plt.title("Topics to Venue Distribution(%d - %d)" % (paper_range[0], paper_range[-1]), y=1.2)
  else:
    plt.title("Topics to Venue Distribution", y=1.2)
  plt.savefig(figname, bbox_inches='tight')
  plt.clf() 
Example 34
Project: citemap   Author: ai-se   File: expts_v4.py    The Unlicense 5 votes vote down vote up
def make_heatmap(arr, row_labels, column_labels, figname, paper_range):
  plt.figure(figsize=(4, 3))
  df = pd.DataFrame(arr, columns=column_labels, index=row_labels)
  cax = plt.matshow(df, interpolation='nearest', cmap='hot_r')
  plt.colorbar(cax)
  plt.xticks(np.arange(len(list(df.columns))), list(df.columns), rotation="vertical")
  plt.yticks(np.arange(len(list(df.index))), list(df.index))
  [tick.set_color("red") if tick.get_text() in CONFERENCES else tick.set_color("green")
      for tick in plt.gca().get_xticklabels()]
  if paper_range:
    plt.title("Topics to Venue Distribution(%d - %d)" % (paper_range[0], paper_range[-1]), y=1.2)
  else:
    plt.title("Topics to Venue Distribution", y=1.2)
  plt.savefig(figname, bbox_inches='tight')
  plt.clf() 
Example 35
Project: citemap   Author: ai-se   File: ist.py    The Unlicense 5 votes vote down vote up
def make_dendo_heatmap(arr, row_labels, column_labels, figname, settings):
  df = pd.DataFrame(arr, columns=column_labels, index=row_labels)
  # Compute pairwise distances for columns
  col_clusters = linkage(pdist(df.T, metric='euclidean'), method='complete')
  # plot column dendrogram
  fig = plt.figure(figsize=settings.fig_size)
  axd2 = fig.add_axes(settings.col_axes)
  col_dendr = dendrogram(col_clusters, orientation='top',
                         color_threshold=np.inf)  # makes dendrogram black)
  axd2.set_xticks([])
  axd2.set_yticks([])
  # plot row dendrogram
  axd1 = fig.add_axes(settings.row_axes)
  row_clusters = linkage(pdist(df, metric='euclidean'), method='complete')
  row_dendr = dendrogram(row_clusters, orientation='left',
                         count_sort='ascending',
                         color_threshold=np.inf)  # makes dendrogram black
  axd1.set_xticks([])
  axd1.set_yticks([])
  # remove axes spines from dendrogram
  for i, j in zip(axd1.spines.values(), axd2.spines.values()):
    i.set_visible(False)
    j.set_visible(False)
  # reorder columns and rows with respect to the clustering
  df_rowclust = df.ix[row_dendr['leaves'][::-1]]
  df_rowclust.columns = [df_rowclust.columns[col_dendr['leaves']]]
  # plot heatmap
  axm = fig.add_axes(settings.plot_axes)
  cax = axm.matshow(df_rowclust, interpolation='nearest', cmap='hot_r')
  fig.colorbar(cax)
  axm.set_xticks(np.arange(len(list(df_rowclust.columns))))
  axm.set_xticklabels(list(df_rowclust.columns), rotation="vertical")
  axm.set_yticks(np.arange(len(list(df_rowclust.index))))
  axm.set_yticklabels(list(df_rowclust.index))
  plt.savefig(figname, bbox_inches='tight')
  plt.clf() 
Example 36
Project: citemap   Author: ai-se   File: ist.py    The Unlicense 5 votes vote down vote up
def make_heatmap(arr, row_labels, column_labels, figname):
  plt.figure(figsize=(4, 3))
  df = pd.DataFrame(arr, columns=column_labels, index=row_labels)
  cax = plt.matshow(df, interpolation='nearest', cmap='hot_r')
  plt.colorbar(cax)
  plt.xticks(np.arange(len(list(df.columns))), list(df.columns), rotation="vertical")
  plt.yticks(np.arange(len(list(df.index))), list(df.index))
  plt.title("Topics to Conference Distribution", y=1.2)
  plt.savefig(figname, bbox_inches='tight')
  plt.clf() 
Example 37
Project: citemap   Author: ai-se   File: expts_v5.py    The Unlicense 5 votes vote down vote up
def make_heatmap(arr, row_labels, column_labels, figname, paper_range):
  plt.figure(figsize=(4, 3))
  df = pd.DataFrame(arr, columns=column_labels, index=row_labels)
  cax = plt.matshow(df, interpolation='nearest', cmap='hot_r')
  plt.colorbar(cax)
  plt.xticks(np.arange(len(list(df.columns))), list(df.columns), rotation="vertical")
  plt.yticks(np.arange(len(list(df.index))), list(df.index))
  [tick.set_color("red") if tick.get_text() in CONFERENCES else tick.set_color("green")
      for tick in plt.gca().get_xticklabels()]
  if paper_range:
    plt.title("Topics to Venue Distribution(%d - %d)" % (paper_range[0], paper_range[-1]), y=1.2)
  else:
    plt.title("Topics to Venue Distribution", y=1.2)
  plt.savefig(figname, bbox_inches='tight')
  plt.clf() 
Example 38
Project: citemap   Author: ai-se   File: icse.py    The Unlicense 5 votes vote down vote up
def make_heatmap(arr, row_labels, column_labels, figname):
  plt.figure(figsize=(4,3))
  df = pd.DataFrame(arr, columns=column_labels, index=row_labels)
  cax = plt.matshow(df, interpolation='nearest', cmap='hot_r')
  plt.colorbar(cax)
  plt.xticks(np.arange(len(list(df.columns))), list(df.columns), rotation="vertical")
  plt.yticks(np.arange(len(list(df.index))), list(df.index))
  plt.title("Topics to Conference Distribution", y=1.2)
  plt.savefig(figname, bbox_inches='tight')
  plt.clf() 
Example 39
Project: stock_img_clf   Author: ernest222   File: someplots.py    MIT License 5 votes vote down vote up
def plot_onelayer_onechannel(self,layerid,channel_id,layer_before):
        model = load_model(self.model_path)
        layer_outputs = [layer.output for layer in model.layers[:layer_before]]  # layer_before 前多少层,layer_before=5,获取前5层
        activation_model = models.Model(inputs=model.input, outputs=layer_outputs)
        activations = activation_model.predict(self.img_to_tensor())
        choose_layer_activation = activations[layerid]  # layerid=0 查看第一层激活输出
        print(choose_layer_activation.shape)
        plt.matshow(choose_layer_activation[0, :, :, channel_id], cmap='viridis')   # channel_id 查看layerid层的第channel_id通道图片
        plt.show() 
Example 40
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)
    plt.show() 
Example 41
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_conf_matrix(y_actual,y_predict,labels):
    cm = confusion_matrix(y_actual,y_predict,labels)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm)
    pl.title('confusion matrix')
    fig.colorbar(cax)
    ax.set_xticklabels([''] + labels)
    ax.set_yticklabels([''] + labels)
    pl.xlabel('Predicted')
    pl.ylabel('True')
    pl.show() 
Example 42
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)
    plt.show() 
Example 43
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_conf_matrix(y_actual,y_predict,labels):
    cm = confusion_matrix(y_actual,y_predict,labels)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm)
    pl.title('confusion matrix')
    fig.colorbar(cax)
    ax.set_xticklabels([''] + labels)
    ax.set_yticklabels([''] + labels)
    pl.xlabel('Predicted')
    pl.ylabel('True')
    pl.show() 
Example 44
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)
    plt.show() 
Example 45
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)
    plt.show() 
Example 46
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_conf_matrix(y_actual,y_predict,labels):
    cm = confusion_matrix(y_actual,y_predict,labels)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm)
    pl.title('confusion matrix')
    fig.colorbar(cax)
    ax.set_xticklabels([''] + labels)
    ax.set_yticklabels([''] + labels)
    pl.xlabel('Predicted')
    pl.ylabel('True')
    pl.show() 
Example 47
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)
    plt.show() 
Example 48
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_conf_matrix(y_actual,y_predict,labels):
    cm = confusion_matrix(y_actual,y_predict,labels)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm)
    pl.title('confusion matrix')
    fig.colorbar(cax)
    ax.set_xticklabels([''] + labels)
    ax.set_yticklabels([''] + labels)
    pl.xlabel('Predicted')
    pl.ylabel('True')
    pl.show() 
Example 49
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)
    plt.show() 
Example 50
Project: image-classifier   Author: gustavkkk   File: eval.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r):
    plt.matshow(df_confusion, cmap=cmap) # imshow
    #plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(df_confusion.columns))
    plt.xticks(tick_marks, df_confusion.columns, rotation=45)
    plt.yticks(tick_marks, df_confusion.index)
    #plt.tight_layout()
    plt.ylabel(df_confusion.index.name)
    plt.xlabel(df_confusion.columns.name)
    plt.show()