我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.matshow()。
def render(self, plt_delay=1.0): plt.matshow(self.model_state[0].T, cmap=plt.get_cmap('Greys'), fignum=1) for i in range(self.pursuer_layer.n_agents()): x, y = self.pursuer_layer.get_position(i) plt.plot(x, y, "r*", markersize=12) if self.train_pursuit: ax = plt.gca() ofst = self.obs_range / 2.0 ax.add_patch( Rectangle((x - ofst, y - ofst), self.obs_range, self.obs_range, alpha=0.5, facecolor="#FF9848")) for i in range(self.evader_layer.n_agents()): x, y = self.evader_layer.get_position(i) plt.plot(x, y, "b*", markersize=12) if not self.train_pursuit: ax = plt.gca() ofst = self.obs_range / 2.0 ax.add_patch( Rectangle((x - ofst, y - ofst), self.obs_range, self.obs_range, alpha=0.5, facecolor="#009ACD")) plt.pause(plt_delay) plt.clf()
def showAttention(input_sentence, output_words, attentions): # Set up figure with colorbar fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(attentions.numpy(), cmap='bone') fig.colorbar(cax) # Set up axes ax.set_xticklabels([''] + input_sentence.split(' ') + ['<EOS>'], rotation=90) ax.set_yticklabels([''] + output_words) # Show label at every tick ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.show()
def plot_confusion_matrix(cm, clf_target_names, title='Confusion matrix', cmap=plt.cm.jet): target_names = map(lambda key: key.replace('_','-'), clf_target_names) for idx in range(len(cm)): cm[idx,:] = (cm[idx,:] * 100.0 / np.sum(cm[idx,:])).astype(np.int) plt.imshow(cm, interpolation='nearest', cmap=cmap) # plt.matshow(cm) plt.title(title) plt.colorbar() tick_marks = np.arange(len(clf_target_names)) plt.xticks(tick_marks, target_names, rotation=45) plt.yticks(tick_marks, target_names) # plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
def display_confusion_matrix(test_data, test_labels, save=False): """ Plot a matrix representing the choices made by the network on a testing batch. X axis are the predicted values, Y axis are the expected values. If the flag save is set to True, the output will be saved in a .png image. """ expected = test_labels predicted = mnist.predict(test_data) cm = confusion_matrix(expected, predicted) plt.matshow(cm) plt.title('Confusion matrix') plt.colorbar() plt.ylabel('Expected label') plt.xlabel('Predicted label') plt.show() if save is True: plt.savefig("../results/mnist/confusion_matrix.png")
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
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
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
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
def plot_attention(tokens1, tokens2, attention): """ Print a colormap showing attention values from tokens 1 to tokens 2. """ len1 = len(tokens1) len2 = len(tokens2) extent = [0, len2, 0, len1] pl.matshow(attention, extent=extent, aspect='auto') ticks1 = np.arange(len1) + 0.5 ticks2 = np.arange(len2) + 0.5 pl.xticks(ticks2, tokens2, rotation=45) pl.yticks(ticks1, reversed(tokens1)) ax = pl.gca() ax.xaxis.set_ticks_position('bottom') pl.colorbar() pl.title('Alignments') pl.show(block=False)
def main(): parser = argparse.ArgumentParser(description='') parser.add_argument('--transform') parser.add_argument('--out') args = parser.parse_args() infile1 = h5py.File(args.transform, 'r') resolutions = infile1['resolutions'][...] chroms = infile1['chromosomes'][...] data1 = load_data(infile1, chroms, resolutions) infile1.close() ''' #for now, don't plot this for resolution in data1.keys(): for chromo in chroms: N = data1[resolution][chromo][1].shape[0] full=numpy.empty((N,N)) #full=full/0 for i in range(100): temp1 = numpy.arange(N - i - 1) temp2 = numpy.arange(i+1, N) full[temp1, temp2] = data1[resolution][chromo][1][temp1, i] full[temp2, temp1] = full[temp1, temp2] x=0.8 plt.matshow(full,cmap='seismic',vmin=-x,vmax=x) plt.colorbar() plt.show() plt.savefig(args.out+'.res'+str(resolution)+'.chr'+chromo+'.pdf') '''
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()
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()
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)
def _discrete_matshow_adaptive(data, labels_names=[], title=""): """Displays segmentation results using colormap that is adapted to a number of classes. Uses labels_names to write class names aside the color label. Used as a helper function for visualize_segmentation_adaptive() function. Parameters ---------- data : 2d numpy array (width, height) Array with integers representing class predictions labels_names : list List with class_names """ fig_size = [7, 6] plt.rcParams["figure.figsize"] = fig_size #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=15, fontweight='bold') plt.show()
def plot_confusion_matrix(cls_pred, iter_num): # This is called from print_test_accuracy() below. # 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.test.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.title('Confusion Matrix at iter: ' + str(iter_num)) plt.text(0.5, 0, 'Iter: ' + str(iter_num), verticalalignment='bottom') file_name = plt_dir + '/Confusion_Matrix_iter_' + str(iter_num) + '.png' plt.show() plt.savefig(file_name, format='png', bbox_inches='tight') # Split the data-set in batches of this size to limit RAM usage.
def plot(self): mean=np.flipud(np.nanmean(self.loaded['data'], 0)*365*8) ax = plt.matshow(mean) plt.colorbar(ax) plt.show(block=True)
def plot_confusion_matrix(cls_pred): # This is called from print_test_accuracy() below. # 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.test.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() # ### Helper-functions for calculating classifications # # This function calculates the predicted classes of images and also returns a boolean array whether the classification of each image is correct. # # The calculation is done in batches because it might use too much RAM otherwise. If your computer crashes then you can try and lower the batch-size. # In[35]: # Split the data-set in batches of this size to limit RAM usage.
def lvlEnergy(signal, n=N, r=TINY): "For each set of coefficients in a same level, return its /energy/, or square root of the sum of squares" projections = project(signal, n, r) averages = projections[0] # take the first component, which should be the same as all the others length = signal.size - n levels = log2int(n) lvlEnergy = np.empty([levels, length]) for j in xrange(levels): lvlEnergy[j] = np.linalg.norm(projections[2**j:2*2**j], axis=0) return averages, lvlEnergy #thing = lvlEnergy(wav[1000:2256], n=256)[1] #plt.matshow(thing, origin='upper', aspect='auto'); plt.colorbar(); plt.show()
def draw(xy_matrix, info='<None>'): """Draw an XY matrix and attach some info""" from matplotlib import pyplot pyplot.copper() pyplot.matshow(xy_matrix) pyplot.xlabel(info, color="red") pyplot.show() # native function not assigned to particular interpreter
def show_conf_mat(confusion_matrix): """ Show a windows with a color image for a confusion matrix Args: confusion_matrix (NumPy Array): The matrix to be shown. Returns: void """ plt.matshow(confusion_matrix) plt.title('Confusion Matrix') plt.colorbar() plt.show()
def plot_corr(df,size=10): '''Function plots a graphical correlation matrix for each pair of columns in the dataframe. Input: df: pandas DataFrame size: vertical and horizontal size of the plot''' corr = df.corr() # fig, ax = plt.subplots(figsize=(size, size)) # cax = ax.matshow(corr, interpolation='nearest') # plt.xticks(range(len(corr.columns)), corr.columns, rotation=90) # plt.yticks(range(len(corr.columns)), corr.columns) # fig.colorbar(cax) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(size, size)) # Draw the heatmap using seaborn sns.heatmap(corr, vmax=1.0, square=True) # Use matplotlib directly to emphasize known networks # networks = corrmat.columns.get_level_values("network") # for i, network in enumerate(networks): # if i and network != networks[i - 1]: # ax.axhline(len(networks) - i, c="w") # ax.axvline(i, c="w") # f.tight_layout() # # fig = plt.figure() # data_nasdaq_top_100_mkt_cap_symbology_corr = data_nasdaq_top_100_mkt_cap_symbology.corr() # # plt.matshow(data_nasdaq_top_100_mkt_cap_symbology_corr) # # plt.colorbar(data_nasdaq_top_100_mkt_cap_symbology_corr) # labels = data_nasdaq_top_100_mkt_cap_symbology_corr.columns # # print labels # ax = fig.add_subplot(111) # cax = ax.matshow(data_nasdaq_top_100_mkt_cap_symbology_corr, interpolation='nearest') # fig.colorbar(cax)
def plot_confusion_matrix(conf_mat): cm = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis] plt.matshow(cm, cmap='gray_r', vmin=0, vmax=1) # text portion ind_array = np.arange(cm.shape[0]) x, y = np.meshgrid(ind_array, ind_array) for i, j in zip(x.flatten(), y.flatten()): c = 'k' if cm[i, j] <= 0.5 else 'w' plt.text(j, i, '{}'.format(conf_mat[i, j]), color=c, va='center', ha='center') plt.xticks([]) plt.yticks([])
def main(): argparser = argparse.ArgumentParser() argparser.add_argument( "-N", "--grid_size", type=int, default=100 ) argparser.add_argument( "-T", "--time_steps", type=int, default=100 ) argparser.add_argument( "-d", "--display", action='store_true' ) args = argparser.parse_args() # Starting grid read = np.zeros( ( args.grid_size+2, args.grid_size+2 ) ) # Make it 'hot; on the [0,_] side and cold on the [_,0] side and 'warm' on the [i,N-i] line for i in range(args.grid_size+2): read[0,i] = 100.0; read[i,0] = -100.0; read[i,args.grid_size+1-i] = 50.0 # Write grid write = copy.deepcopy( read ) if args.display: plt.matshow( read ) timer = Timer() timer.start() # Outer time-stepping loop for t in range( args.time_steps ): jacobi( read, write, args.grid_size ) # flip the read and write array write, read = read, write timer.stop() print( "Elapsed: {}s".format( timer.elapsed() ) ) if args.display: plt.matshow( read ) plt.show()
def main(): argparser = argparse.ArgumentParser() argparser.add_argument( "-N", "--grid_size", type=int, default=100 ) argparser.add_argument( "-T", "--time_steps", type=int, default=100 ) argparser.add_argument( "-d", "--display", action='store_true' ) args = argparser.parse_args() # Starting grid read = [ [ 0.0 for _ in range(args.grid_size+2)] for _ in range(args.grid_size+2)] # Make it 'hot; on the [0][_] side and cold on the [_][0] side and 'warm' on the [i][N-i] line for i in range(args.grid_size+2): read[0][i] = 100.0; read[i][0] = -100.0; read[i][args.grid_size+1-i] = 50.0 # Write grid write = copy.deepcopy( read ) if args.display: plt.matshow( read ) timer = Timer() timer.start() # Outer time-stepping loop for t in range( args.time_steps ): jacobi( read, write, args.grid_size ) # flip the read and write array write, read = read, write timer.stop() print( "Elapsed: {}s".format( timer.elapsed() ) ) if args.display: plt.matshow( read ) plt.show()
def main(): argparser = argparse.ArgumentParser() argparser.add_argument( "-N", "--grid_size", type=int, default=100 ) argparser.add_argument( "-T", "--time_steps", type=int, default=100 ) argparser.add_argument( "-d", "--display", action='store_true' ) args = argparser.parse_args() # Starting grid read = [ [ 0.0 for _ in range(args.grid_size+2)] for _ in range(args.grid_size+2)] # Make it 'hot; on the [0][_] side and cold on the [_][0] side and 'warm' on the [i][N-i] line for i in range(args.grid_size+2): read[0][i] = 100.0; read[i][0] = -100.0; read[i][args.grid_size+1-i] = 50.0 # Write grid write = copy.deepcopy( read ) if args.display: plt.matshow( read ) timer = Timer() timer.start() # Outer time-stepping loop for t in range( args.time_steps ): jacobi_iteration( read, write, args.grid_size ) # flip the read and write array write, read = read, write timer.stop() print( "Elapsed: {}s".format( timer.elapsed() ) ) if args.display: plt.matshow( read ) plt.show()
def confusionMatrix(dataSet, saveFolder=None): testPercent = .2 labels, instances = dataSet.getLabelsAndInstances2() scaledInstances = normalizeData(instances) # Separate training from test yTrain, yTest, xTrain, xTest = train_test_split( labels, scaledInstances, test_size=testPercent) # Train and predict clf = SVC() clf.fit(xTrain, yTrain) yPred = clf.predict(xTest) cm = confusion_matrix(yTest, yPred) labels, _ = dataSet.getLabelsAndInstances() plt.matshow(cm, aspect="auto") plt.ylabel("True label") plt.xlabel("Predicted label") plt.yticks(range(28), labels) plt.xticks(range(28), labels, rotation=90) plt.colorbar() plt.grid(True) if saveFolder is not None: plt.savefig(saveFolder+"/confussion.png", bbox_inches="tight") plt.show()
def test_qtable(): single_run = True n_episode = 1000000 tMax = 200 env = gym.make('FrozenLake-v0') S = env.observation_space A = env.action_space learning_rate=1e-2 gamma=0.99 policy=epsilon_greedy if single_run: agent = QTable(S, A, learning_rate=learning_rate, gamma=gamma, policy=policy) ave_r = run(env, agent, n_episode, tMax, plot=True, epsilon=0.1) plt.matshow(flQ_table(agent.table)) plt.savefig('qtable_data/policy.png', format='png') else: # Sample learning rates # lrs = 10**np.random.uniform(-4.0, -2, size=10) learning_rates = [lrs[n] for n in xrange(lrs.shape[0]) ] ave_returns = [] for lr in learning_rates: agent = QTable(S, A, learning_rate=lr, gamma=gamma, policy=policy) ave_r = run(env, agent, n_episode, tMax, plot=True) print agent.table ave_returns.append(ave_r) plt.figure() plt.semilogx(learning_rates, ave_returns, 'o') plt.savefig('lr_returns.png'.format(), format='png') plt.xlabel('learning rate') plt.ylabel('average returns')
def draw(self, time=1): """Draw the matrix using MatPlotLib.""" pyplot.clf() pyplot.matshow(self.data, 1, cmap=self.cmap, norm=self.norm) pyplot.pause(time)