我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.yticks()。
def visualizeLayer(model, img, input_image, layerIndex): layer = model.layers[layerIndex] get_activations = K.function([model.layers[0].input, K.learning_phase()], [layer.output,]) activations = get_activations([input_image, 0])[0] output_image = activations ## If 4 dimensional then take the last dimension value as it would be no of filters if output_image.ndim == 4: # Rearrange dimension so we can plot the result o1 = np.rollaxis(output_image, 3, 1) output_image = np.rollaxis(o1, 3, 1) print "Dumping filter data of layer{} - {}".format(layerIndex,layer.__class__.__name__) filters = len(output_image[0,0,0,:]) fig=plt.figure(figsize=(8,8)) # This loop will plot the 32 filter data for the input image for i in range(filters): ax = fig.add_subplot(6, 6, i+1) #ax.imshow(output_image[img,:,:,i],interpolation='none' ) #to see the first filter ax.imshow(output_image[0,:,:,i],'gray') #ax.set_title("Feature map of layer#{} \ncalled '{}' \nof type {} ".format(layerIndex, # layer.name,layer.__class__.__name__)) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.tight_layout() #plt.show() fig.savefig("img_" + str(img) + "_layer" + str(layerIndex)+"_"+layer.__class__.__name__+".png") #plt.close(fig) else: print "Can't dump data of this layer{}- {}".format(layerIndex, layer.__class__.__name__)
def _create_figure(predictions_dict): """Creates and returns a new figure that visualizes attention scores for for a single model predictions. """ # Find out how long the predicted sequence is target_words = list(predictions_dict["predicted_tokens"]) prediction_len = _get_prediction_length(predictions_dict) # Get source words source_len = predictions_dict["features.source_len"] source_words = predictions_dict["features.source_tokens"][:source_len] # Plot fig = plt.figure(figsize=(8, 8)) plt.imshow( X=predictions_dict["attention_scores"][:prediction_len, :source_len], interpolation="nearest", cmap=plt.cm.Blues) plt.xticks(np.arange(source_len), source_words, rotation=45) plt.yticks(np.arange(prediction_len), target_words, rotation=-45) fig.tight_layout() return fig
def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=plt.cm.Greys, block=True): # Colormaps: jet, Greys cm_normalized = cm.astype(np.float32) / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm_normalized, interpolation='nearest', cmap=cmap) # Show confidences for i, cas in enumerate(cm): for j, c in enumerate(cas): if c > 0: plt.text(j-0.1, i+0.2, c, fontsize=16, fontweight='bold', color='#b70000') f = plt.figure(1) f.clf() plt.title(title) plt.colorbar() tick_marks = np.arange(len(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') plt.show(block=block)
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 plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=plt.cm.Greys): # Colormaps: jet, Greys cm_normalized = cm.astype(np.float32) / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm_normalized, interpolation='nearest', cmap=cmap) # Show confidences for i, cas in enumerate(cm): for j, c in enumerate(cas): if c > 0: plt.text(j-0.1, i+0.2, c, fontsize=16, fontweight='bold', color='#b70000') plt.title(title) plt.colorbar() tick_marks = np.arange(len(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') plt.show(block=True)
def plotTimeMultiHistogram(parseTimes, hashTimes, compileTimes, filename): # times in ms bins = np.linspace(0, 5000, 50) data = np.vstack([parseTimes, hashTimes, compileTimes]).T fig, ax = plt.subplots() plt.hist(data, bins, alpha=0.7, label=['parsing', 'hashing', 'compiling'], color=[parseColor, hashColor, compileColor]) plt.legend(loc='upper right') plt.xlabel('time [ms]') plt.ylabel('#files') fig.savefig(filename) fig, ax = plt.subplots() boxplot_data = [[i/1000 for i in parseTimes], [i/1000 for i in hashTimes], [i/1000 for i in compileTimes]] # times to s plt.boxplot(boxplot_data, 0, 'rs', 0, [5, 95]) plt.xlabel('time [s]') plt.yticks([1, 2, 3], ['parsing', 'hashing', 'compiling']) #lgd = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # legend on the right fig.savefig(filename[:-4] + '_boxplots' + GRAPH_EXTENSION)
def plot_gold(g1, g2, lc, p = 0): """ plot sen/spe of g1 against g2 only consider workers in lc """ mv = crowd_model.mv_model(lc) s1 = []; s2 = [] for w in g1.keys(): if w in g2 and g1[w][p] != None and g2[w][p] != None and w in mv.dic_ss: s1.append(g1[w][p]) s2.append(g2[w][p]) plt.xticks((0, 0.5, 1), ("0", "0.5", "1")) plt.tick_params(labelsize = 25) plt.yticks((0, 0.5, 1), ("0", "0.5", "1")) plt.xlim(0,1) plt.ylim(0,1) plt.scatter(s1, s2, marker = '.', s=50, c = 'black') plt.xlabel('task 1 sen.', fontsize = 25) plt.ylabel('task 2 sen.', fontsize = 25)
def plot_confusion_matrix(cm, col, title, cmap=plt.cm.viridis): plt.imshow(cm, interpolation='nearest', cmap=cmap) for i in range(cm.shape[0]): plt.annotate("%.2f" %cm[i][i],xy=(i,i), horizontalalignment='center', verticalalignment='center') plt.title(title,fontsize=18) plt.colorbar(fraction=0.046, pad=0.04) tick_marks = np.arange(len(col.unique())) plt.xticks(tick_marks, sorted(col.unique()),rotation=90) plt.yticks(tick_marks, sorted(col.unique())) plt.tight_layout() plt.ylabel('True label',fontsize=18) plt.xlabel('Predicted label',fontsize=18) #using flavor network to project recipes from ingredient matrix to flavor matrix
def plot_mean_debye(sol, ax): x = np.log10(sol[0]["data"]["tau"]) x = np.linspace(min(x), max(x),100) list_best_rtd = [100*np.sum([a*(x**i) for (i, a) in enumerate(s["params"]["a"])], axis=0) for s in sol] # list_best_rtd = [s["fit"]["best"] for s in sol] y = np.mean(list_best_rtd, axis=0) y_min = 100*np.sum([a*(x**i) for (i, a) in enumerate(sol[0]["params"]["a"] - sol[0]["params"]["a_std"])], axis=0) y_max = 100*np.sum([a*(x**i) for (i, a) in enumerate(sol[0]["params"]["a"] + sol[0]["params"]["a_std"])], axis=0) ax.errorbar(10**x[(x>-6)&(x<2)], y[(x>-6)&(x<2)], None, None, "-", color='blue',linewidth=2, label="Mean RTD", zorder=10) plt.plot(10**x[(x>-6)&(x<2)], y_min[(x>-6)&(x<2)], color='lightgray', alpha=1, zorder=-1, label="RTD range") plt.plot(10**x[(x>-6)&(x<2)], y_max[(x>-6)&(x<2)], color='lightgray', alpha=1, zorder=-1) plt.fill_between(sol[0]["data"]["tau"], 100*(sol[0]["params"]["m_"]-sol[0]["params"]["m__std"]) , 100*(sol[0]["params"]["m_"]+sol[0]["params"]["m__std"]), color='lightgray', alpha=1, zorder=-1, label="RTD SD") ax.set_xlabel("Relaxation time (s)", fontsize=14) ax.set_ylabel("Chargeability (%)", fontsize=14) plt.yticks(fontsize=14), plt.xticks(fontsize=14) plt.xscale("log") ax.set_xlim([1e-6, 1e1]) ax.set_ylim([0, 5.0]) ax.legend(loc=1, fontsize=12) # ax.set_title(title+" step method", fontsize=14)
def plot_spatial_cluster_fig(data, covar_type_tied_labels_k): """ Creates a 3x2 plot spatial plot using labels as the color """ sns.set(context='talk', style='white') data.columns = [c.lower() for c in data.columns] fig = plt.figure() placement = {'full': {True: 1, False: 4}, 'diag': {True: 2, False: 5}, 'spher': {True: 3, False: 6}} lim_left = data['longitude'].min() lim_right = data['longitude'].max() lim_bottom = data['latitude'].min() lim_top = data['latitude'].max() for covar_type, covar_tied, labels, k in covar_type_tied_labels_k: plt.subplot(2, 3, placement[covar_type][covar_tied]) plt.scatter(data['longitude'], data['latitude'], c=labels, cmap=plt.cm.rainbow, s=10) plt.xlim(left=lim_left, right=lim_right) plt.ylim(bottom=lim_bottom, top=lim_top) plt.xticks([]) plt.yticks([]) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.title('{}-{}, K={}'.format(covar_type.capitalize(), ['Untied', 'Tied'][covar_tied], k)) plt.tight_layout() return fig
def plot_trace(n=0, lg=False): plt.plot(trueC[n], c=col[2], clip_on=False, zorder=5, label='Truth') plt.plot(solution, c=col[0], clip_on=False, zorder=7, label='Estimate') plt.plot(y, c=col[7], alpha=.7, lw=1, clip_on=False, zorder=-10, label='Data') if lg: plt.legend(frameon=False, ncol=3, loc=(.1, .62), columnspacing=.8) spks = np.append(0, solution[1:] - g * solution[:-1]) plt.text(800, 2.2, 'Correlation: %.3f' % (np.corrcoef(trueSpikes[n], spks)[0, 1]), size=24) plt.gca().set_xticklabels([]) simpleaxis(plt.gca()) plt.ylim(0, 2.85) plt.xlim(0, 1500) plt.yticks([0, 2], [0, 2]) plt.xticks([300, 600, 900, 1200], ['', '']) # init params
def plot_heatmaps(data, mis, column_label, cont, topk=30, prefix=''): cmap = sns.cubehelix_palette(as_cmap=True, light=.9) m, nv = mis.shape for j in range(m): inds = np.argsort(- mis[j, :])[:topk] if len(inds) >= 2: plt.clf() order = np.argsort(cont[:,j]) subdata = data[:, inds][order].T subdata -= np.nanmean(subdata, axis=1, keepdims=True) subdata /= np.nanstd(subdata, axis=1, keepdims=True) columns = [column_label[i] for i in inds] sns.heatmap(subdata, vmin=-3, vmax=3, cmap=cmap, yticklabels=columns, xticklabels=False, mask=np.isnan(subdata)) filename = '{}/heatmaps/group_num={}.png'.format(prefix, j) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) plt.title("Latent factor {}".format(j)) plt.yticks(rotation=0) plt.savefig(filename, bbox_inches='tight') plt.close('all') #plot_rels(data[:, inds], map(lambda q: column_label[q], inds), colors=cont[:, j], # outfile=prefix + '/relationships/group_num=' + str(j), latent=labels[:, j], alpha=0.1)
def animpingpong(self): obj=self.Object img=None if not obj.imageFromNode: img = cv2.imread(obj.imageFile) else: print "copy image ..." img = obj.imageNode.ViewObject.Proxy.img.copy() print "cpied" print " loaded" # print (obj.blockSize,obj.ksize,obj.k) # edges = cv2.Canny(img,obj.minVal,obj.maxVal) # color = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) # edges=color # kernel = np.ones((obj.xsize,obj.ysize),np.uint8) opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel, iterations = obj.iterations) if True: print "zeige" cv2.imshow(obj.Label,opening) print "gezeigt" else: from matplotlib import pyplot as plt plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst,cmap = 'gray') plt.title('Corner Image'), plt.xticks([]), plt.yticks([]) plt.show() print "fertig" self.img=opening
def animpingpong(self): obj=self.Object img=None if not obj.imageFromNode: img = cv2.imread(obj.imageFile) else: print "copy image ..." img = obj.imageNode.ViewObject.Proxy.img.copy() print "cpied" print " loaded" # print (obj.blockSize,obj.ksize,obj.k) edges = cv2.Canny(img,obj.minVal,obj.maxVal) color = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) edges=color if True: print "zeige" cv2.imshow(obj.Label,edges) print "gezeigt" else: from matplotlib import pyplot as plt plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst,cmap = 'gray') plt.title('Corner Image'), plt.xticks([]), plt.yticks([]) plt.show() print "fertig" self.img=edges
def animpingpong(self): obj=self.Object img=None if not obj.imageFromNode: img = cv2.imread(obj.imageFile) else: print "copy image ..." img = obj.imageNode.ViewObject.Proxy.img.copy() print "cpied" print " loaded" # print (obj.blockSize,obj.ksize,obj.k) # edges = cv2.Canny(img,obj.minVal,obj.maxVal) # color = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) # edges=color # kernel = np.ones((obj.xsize,obj.ysize),np.uint8) closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel, iterations = obj.iterations) if True: print "zeige" cv2.imshow(obj.Label,closing) print "gezeigt" else: from matplotlib import pyplot as plt plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst,cmap = 'gray') plt.title('Corner Image'), plt.xticks([]), plt.yticks([]) plt.show() print "fertig" self.img=closing
def animpingpong(self): print self print self.Object print self.Object.Name obj=self.Object img = cv2.imread(obj.imageFile) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gray = np.float32(gray) dst = cv2.cornerHarris(gray,3,3,0.00001) dst = cv2.dilate(dst,None) img[dst>0.01*dst.max()]=[0,0,255] from matplotlib import pyplot as plt plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst,cmap = 'gray') plt.title('Corner Image'), plt.xticks([]), plt.yticks([]) plt.show()
def visualize_document_topic_probs(self, outfile): plots = [] height_cumulative = numpy.zeros(self.rows) #fig = pyplot.figure(figsize=(21, 10), dpi=550) for column in range(self.columns): color = pyplot.cm.coolwarm(column/self.columns, 1) if column == 0: p = pyplot.bar(self.ind, self.document_topics_raw[:, column], self.barwidth, color=color) else: p = pyplot.bar(self.ind, self.document_topics_raw[:, column], self.barwidth, bottom=height_cumulative, color=color) height_cumulative += self.document_topics_raw[:, column] plots.append(p) pyplot.ylim((0, 1)) pyplot.ylabel('Topics') pyplot.title('Topic distribution of CLS papers') pyplot.xticks(self.ind+self.barwidth/2, self.document_names, rotation='vertical', size = 10) pyplot.yticks(numpy.arange(0, 1, 10)) pyplot.legend([p[0] for p in plots], self.topic_labels, bbox_to_anchor=(1, 1)) self.fig.tight_layout() pyplot.savefig(outfile)
def update(self, conf_mat, classes, normalize=False): """This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(conf_mat, interpolation='nearest', cmap=self.cmap) plt.title(self.title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: conf_mat = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis] thresh = conf_mat.max() / 2. for i, j in itertools.product(range(conf_mat.shape[0]), range(conf_mat.shape[1])): plt.text(j, i, conf_mat[i, j], horizontalalignment="center", color="white" if conf_mat[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.draw()
def plot_normalized_confusion_matrix_at_depth(self): """ Returns a normalized confusion matrix. :returns: normalized confusion matrix :rtype: matplotlib figure """ cm = metrics.confusion_matrix(self.predictions['label'], self.y_pred) np.set_printoptions(precision = 2) fig = plt.figure() cm_normalized = cm.astype('float') / cm.sum(axis = 1)[:, np.newaxis] plt.imshow(cm_normalized, interpolation = 'nearest', cmap = plt.cm.Blues) plt.title("Normalized Confusion Matrix") plt.colorbar() tick_marks = np.arange(len(self.labels)) plt.xticks(tick_marks, self.labels, rotation = 45) plt.yticks(tick_marks, self.labels) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') return(fig)
def plot_confusion_matrix(cm, names=None, title='Confusion Matrix', cmap=plt.cm.Blues): plt.figure(4) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() # Add labels to confusion matrix: if names is None: names = range(cm.shape[0]) tick_marks = np.arange(len(names)) plt.xticks(tick_marks, names, rotation=45) plt.yticks(tick_marks, names) plt.tight_layout() plt.ylabel('Correct label') plt.xlabel('Predicted label') plt.show() # Generate confusion matrix for Jaffe # results = list of tuples of (correct label, predicted label) # e.g. [ ('HA', 3) ] # categories = list of category names # Returns confusion matrix; rows are correct labels and columns are predictions
def finalize_plot(allticks,handles): plt.locator_params(axis='x', nticks=Noracles,nbins=Noracles) plt.yticks([x[0] for x in allticks], [x[1] for x in allticks]) plt.tick_params( axis='y', # changes apply to the x-axis which='both', # both major and minor ticks are affected left='off', # ticks along the bottom edge are off right='off' # ticks along the top edge are off ) if LEGEND: plt.legend([h[0] for h in handles],seriesnames, loc='upper right',borderaxespad=0., ncol=1,fontsize=10,numpoints=1) plt.gcf().tight_layout() ###################################################### # Data processing
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()
def plot_filters(self, x, y, title, cmap=cm.gray): """Plot the filters after the (convolutional) layer. They are plotted in x by y format. So, for example, if we have 20 filters in the layer, then we can call plot_filters(4, 5, "title") to get a 4 by 5 plot of all layer filters. """ filters = self.w.eval() # Get filter values/weights fig = plt.figure() fig.suptitle(title) for j in range(len(filters)): ax = fig.add_subplot(x, y, j+1) ax.matshow(filters[j][0], cmap=cmap) plt.xticks(np.array([])) plt.yticks(np.array([])) plt.tight_layout() fig.subplots_adjust(top=0.90) plt.show()
def _barplot(self, first: RunData, second: RunData, property: str, size: int, filename: str = None, show_ticks: bool = True) -> str: import matplotlib.pyplot as plt import seaborn as sns filename = filename or self._get_new_figure_filename() self._set_fig_size(size) length = min(len(first[property]), len(second[property])) first_prop = first[property][0:length] second_prop = second[property][0:length] min_xval = min(first_prop + second_prop) max_xval = max(first_prop + second_prop) bins = np.linspace(min_xval, max_xval, math.floor(math.sqrt(length) * size)) sns.distplot(first_prop, bins=bins,label=first.description(), kde=False) sns.distplot(second_prop, bins=bins,label=second.description(), kde=False) if not show_ticks: plt.xticks([]) plt.yticks([]) plt.xlim(min_xval, max_xval) plt.legend() plt.savefig(filename) plt.close() return filename
def dictionary_learn_ex(): patch_shape = (18, 18) n_atoms = 225 n_nonzero_coefs = 2 n_plot_atoms = 100 n_jobs = 8 lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4,color=False) #faces = lfw_people.data n_imgs, h, w = lfw_people.images.shape imgs = [] for i in range(n_imgs): img = lfw_people.images[i, :, :].reshape((h, w)) img /= 255. imgs.append(img) print 'Extracting reference patches...' X = extract_patches(imgs, patch_size=patch_shape[0],scale=False,n_patches=int(1e5),verbose=True,n_jobs=n_jobs) print "number of patches:", X.shape[1] se = sparse_encoder(algorithm='bomp',params={'n_nonzero_coefs': n_nonzero_coefs}, n_jobs=n_jobs) odc = online_dictionary_coder(n_atoms=n_atoms, sparse_coder=se, n_epochs=1, batch_size=1000, non_neg=False, verbose=True, n_jobs=n_jobs) odc.fit(X) D = odc.D n_atoms_plot = 225 plt.figure(figsize=(4.2, 4)) for i in range(n_atoms_plot): plt.subplot(15, 15, i + 1) plt.imshow(D[:, i].reshape(patch_shape), cmap=plt.cm.gray) plt.xticks(()) plt.yticks(()) plt.show()
def _show_plot(x_values, y_values, x_labels=None, y_labels=None): try: import matplotlib.pyplot as plt except ImportError: raise ImportError('The plot function requires matplotlib to be installed.' 'See http://matplotlib.org/') plt.locator_params(axis='y', nbins=3) axes = plt.axes() axes.yaxis.grid() plt.plot(x_values, y_values, 'ro', color='red') plt.ylim(ymin=-1.2, ymax=1.2) plt.tight_layout(pad=5) if x_labels: plt.xticks(x_values, x_labels, rotation='vertical') if y_labels: plt.yticks([-1, 0, 1], y_labels, rotation='horizontal') # Pad margins so that markers are not clipped by the axes plt.margins(0.2) plt.show() #//////////////////////////////////////////////////////////// #{ Parsing and conversion functions #////////////////////////////////////////////////////////////
def plot_images(images, ax, ims_per_row=5, padding=5, digit_dimensions=(28, 28), cmap=matplotlib.cm.binary, vmin=None): """iamges should be a (N_images x pixels) matrix.""" N_images = images.shape[0] N_rows = np.ceil(float(N_images) / ims_per_row) pad_value = np.min(images.ravel()) concat_images = np.full(((digit_dimensions[0] + padding) * N_rows + padding, (digit_dimensions[0] + padding) * ims_per_row + padding), pad_value) for i in range(N_images): cur_image = np.reshape(images[i, :], digit_dimensions) row_ix = i / ims_per_row # Integer division. col_ix = i % ims_per_row row_start = padding + (padding + digit_dimensions[0]) * row_ix col_start = padding + (padding + digit_dimensions[0]) * col_ix concat_images[row_start: row_start + digit_dimensions[0], col_start: col_start + digit_dimensions[0]] \ = cur_image cax = ax.matshow(concat_images, cmap=cmap, vmin=vmin) plt.xticks(np.array([])) plt.yticks(np.array([])) return cax
def plot_20news(X, y, target_names, X_test=None, y_test=None, title=None, legend=False): colorlist = get_colors(len(target_names)) def plot_scatter(X, y, alpha=1): y = np.array(y) for i, l in enumerate(target_names): plt.scatter(X[y == i, 0], X[y == i, 1], c=colorlist[i], alpha=alpha, edgecolors='none', label=l if alpha >= 0.5 else None) # , rasterized=True) # plot scatter plot plt.figure() if (X_test is not None) and (y_test is not None): plot_scatter(X_test, y_test, 0.4) plot_scatter(X, y, 1.) else: plot_scatter(X, y, 0.6) if legend: plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), scatterpoints=1) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title, fontsize=20)
def plot_confusion_matrix(cm, tags, title, filename, cmap=plt.cm.Blues): # temp import matplotlib as mpl norm = mpl.colors.Normalize(vmin=0, vmax=1) # remove diagonal #for i in xrange(len(cm[0])): # cm[i][i] = 0 plt.imshow(cm, interpolation='nearest', cmap=cmap, norm=norm) plt.title(title) plt.colorbar() tick_marks = np.arange(len(tags)) plt.xticks(tick_marks, tags, rotation=90, size='xx-small') plt.yticks(tick_marks, tags, size='xx-small') plt.ylabel('True') plt.xlabel('Predicted') plt.tight_layout() if filename: plt.savefig(filename, bbox_inches='tight')
def matploit(data): plt.figure(figsize=(8,5), dpi=80) plt.subplot(1,1,1) plt.grid() plt.subplots_adjust(top=0.9) X = [i for i in range(len(data))] plt.scatter(X,data,color="r") plt.xlim(0.0,len(data)) #plt.xticks(np.linspace(1.0,4.0,7,endpoint=True)) plt.ylim(0,max(data)+1) #plt.yticks(np.linspace(0.0,18,7,endpoint=True)) plt.xlabel("Link number") plt.ylabel("Similarity") plt.show()
def plot_confusion_matrix(cm, title='Confusion Matrix', target_names=['spiral', 'elliptical', 'uncertain'], cmap=plt.cm.Blues, normed=False): '''plot confusion matrix -- predicted label vs actual label classifications input: confusion matrix, 3 x 3 array output: confusion_matrix.png''' np.set_printoptions(precision=2) if normed: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(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') plt.grid('off') plt.savefig('confusion_matrix.png')
def plot(self, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(self.cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(self.classes)) plt.xticks(tick_marks, self.classes, rotation=45) plt.yticks(tick_marks, self.classes) if normalize: self.cm = self.cm.astype('float') / self.cm.sum(axis=1)[:, np.newaxis] thresh = self.cm.max() / 2. for i, j in itertools.product(range(self.cm.shape[0]), range(self.cm.shape[1])): plt.text(j, i, self.cm[i, j], horizontalalignment="center", color="white" if self.cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show()
def test_distinctive_computations(distinctive_fun=distinctive_fun_diff, fun_name='Rate difference'): """ given a function to compute the "distinctive score" of a word given its true and false positive rate, plot the distribution of scores (2D) corresponding to the different tpr and fpr """ # make a grid of possible tpr and fpr combinations import matplotlib.pyplot as plt x, y = np.linspace(0, 1, 101), np.linspace(1, 0, 101) fpr, tpr = np.meshgrid(x, y) score = distinctive_fun(tpr, fpr) plt.figure() plt.imshow(score, cmap=plt.get_cmap('viridis')) plt.xlabel('FPR$_c(t_i)$') plt.ylabel('TPR$_c(t_i)$') plt.xticks(np.linspace(0, 101, 11), np.linspace(0, 1, 11)) plt.yticks(np.linspace(0, 101, 11), np.linspace(1, 0, 11)) plt.title('Score using %s' % fun_name) plt.colorbar()
def heatmap(src_sent, tgt_sent, att_weights, idx): plt.figure(figsize=(8, 6), dpi=80) att_probs = np.stack(att_weights, axis=1) plt.imshow(att_weights, cmap='gray', interpolation='nearest') #src_sent = [ str(s) for s in src_sent] #tgt_sent = [ str(s) for s in tgt_sent] #plt.xticks(range(0, len(tgt_sent)), tgt_sent, rotation='vertical') #plt.yticks(range(0, len(src_sent)), src_sent) plt.xticks(range(0, len(tgt_sent)),"") plt.yticks(range(0, len(src_sent)),"") plt.axis('off') plt.savefig("att_matrix_"+str(idx), bbox_inches='tight') plt.close()
def plot_img(img, title_str, fignum): plt.plot(fignum), plt.imshow(img, cmap='gray') plt.title(title_str), plt.xticks([]), plt.yticks([]) fignum += 1 # move onto next figure number plt.show() return fignum # read image
def plotHeatMap(df, psize=(8,8), filename='Heatmap'): ax = sns.heatmap(df, vmax=.85, square=True, cbar=False, annot=True) plt.xticks(rotation=40), plt.yticks(rotation=360) fig = ax.get_figure() fig.set_size_inches(psize) fig.savefig(filename) plt.clf()
def plot_sen_spe(dic_sen, dic_spe, vals = None): """ """ label = {'single': 'Single', 'accum': 'Accum', 'multi': 'Multi'} marker = {'single': '.', 'accum': 'x', 'multi': 's'} algo = ['single', 'accum', 'multi'] if vals == None: vals = [64, 323, 1295, 6476] plt.xlim(0,3) plt.ylim(0, 0.3) for a in algo: y = [] for v in vals: x = np.mean(dic_sen[(v, a)]) y.append(x) print a, y plt.plot([0, 1, 2, 3], y, label = label[a], marker = marker[a], markersize = 15, linewidth = 5) plt.xlabel('Percentage of target task labels', fontsize = 25) plt.ylabel('RMSE', fontsize = 30) plt.legend(loc = 'upper right', fontsize = 30) plt.tick_params(labelsize = 25) plt.xticks([0,1,2,3], [1, 5, 20, 100]) plt.yticks((0, 0.15, 0.3), ("0", "0.15", "0.3")) #plt.set_xticklabels(['1','','5','','20','','100'])
def plot_confusion_matrix( cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
def plot_confusion_matrix(cm, classes=np.asarray(['spiced', 'non-spliced']), normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label')
def _plot_det(dets, colors, labels, title, fontsize=10, position=None): if position is None: position = 'upper right' # open new page for current plot figure = pyplot.figure(figsize=(matplotlib.rcParams['figure.figsize'][0], matplotlib.rcParams['figure.figsize'][0] * 0.975)) pyplot.grid(True) # plot the DET curves for i in range(len(dets)): pyplot.plot(dets[i][0], dets[i][1], color=colors[i], label=labels[i]) # change axes accordingly det_list = [0.0002, 0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.7, 0.9, 0.95] ticks = [bob.measure.ppndf(d) for d in det_list] labels = [("%.5f" % d).rstrip('0').rstrip('.') for d in det_list] pyplot.xticks(ticks, [l if i % 2 else "" for i,l in enumerate(labels)]) pyplot.yticks(ticks, labels) pyplot.axis((ticks[0], ticks[-1], ticks[0], ticks[-1])) pyplot.xlabel('FMR') pyplot.ylabel('FNMR') pyplot.legend(loc=position, prop = {'size':fontsize}) pyplot.title(title) return figure
def plot_debye(s, ax): x = np.log10(s["data"]["tau"]) x = np.linspace(min(x), max(x),100) y = 100*np.sum([a*(x**i) for (i, a) in enumerate(s["params"]["a"])], axis=0) # ax.errorbar(10**x[(x>-6)&(x<2)], y[(x>-6)&(x<2)], None, None, "-", color='lightgray',linewidth=1, label="RTD estimations (%d)"%len(sol)) ax.set_xlabel("Relaxation time (s)", fontsize=14) ax.set_ylabel("Chargeability (%)", fontsize=14) plt.yticks(fontsize=14), plt.xticks(fontsize=14) plt.xscale("log") ax.set_xlim([1e-6, 1e1]) ax.set_ylim([0, 5.0])
def savePlot(self, name, width=6, height=4.5): timestamps = [] sentiment = [] tweets = [] for data_point in self.timeSeries: timestamps.append(datetime.strptime(data_point["TIME"], '%Y-%m-%d %H:%M:%S')) sentiment.append(data_point["SENTIMENT"]) tweets.append(data_point["TWEETS"]) # Plot setup ax1 = plt.figure(figsize=(width, height)).add_subplot(111) ax1.spines["top"].set_visible(False) ax1.get_xaxis().tick_bottom() ax1.get_yaxis().tick_left() ax1.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M')) lns1 = ax1.plot(timestamps, sentiment, color="dimgrey", lw=0.75, label="Sentiment") plt.yticks(fontsize=8) plt.ylim(ymin=-1, ymax=1) plt.xticks(rotation=50, fontsize=8) ax2 = ax1.twinx() lns2 = ax2.plot(timestamps, tweets, color="dodgerblue", lw=0.5, label="Tweets") ax2.margins(0.05) plt.yticks(fontsize=8) # Labeling ax1.legend(lns1+lns2, ['Sentiment', 'Tweets'], loc=0, frameon=False, fontsize=6) ax1.set_ylabel("Sentiment", weight="light", rotation=90, fontsize=9, labelpad=1) ax2.set_ylabel("Tweets", weight="light", rotation=-90, fontsize=9, labelpad=15) plt.title("Tweet Sentiment", weight ="light", fontsize=12, y=1.08) plt.ylim(ymin=0) plt.tight_layout() file_name = join(BASE_PATH, "outputs", name+".png") plt.savefig(file_name) print("Saved plot {}".format(file_name))
def showPlot(self): timestamps = [] sentiment = [] tweets = [] for data_point in self.timeSeries: timestamps.append(datetime.strptime(data_point["TIME"], '%Y-%m-%d %H:%M:%S')) sentiment.append(data_point["SENTIMENT"]) tweets.append(data_point["TWEETS"]) # Plot setup ax1 = plt.figure(figsize=(6, 4.5)).add_subplot(111) ax1.spines["top"].set_visible(False) ax1.get_xaxis().tick_bottom() ax1.get_yaxis().tick_left() ax1.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M')) lns1 = ax1.plot(timestamps, sentiment, color="dimgrey", lw=0.75, label="Sentiment") plt.yticks(fontsize=8) plt.ylim(ymin=-1, ymax=1) plt.xticks(rotation=50, fontsize=8) ax2 = ax1.twinx() lns2 = ax2.plot(timestamps, tweets, color="dodgerblue", lw=0.5, label="Tweets") ax2.margins(0.05) plt.yticks(fontsize=8) # Labeling ax1.legend(lns1+lns2, ['Sentiment', 'Tweets'], loc=0, frameon=False, fontsize=6) ax1.set_ylabel("Sentiment", weight="light", rotation=90, fontsize=9, labelpad=1) ax2.set_ylabel("Tweets", weight="light", rotation=-90, fontsize=9, labelpad=15) plt.title("Tweet Sentiment", weight ="light", fontsize=12, y=1.08) plt.ylim(ymin=0) plt.tight_layout() plt.show()
def plot(x, y, x_label, y_label, save_file): ticks = x plt.xticks(range(len(ticks)), ticks, fontsize = 15) plt.yticks(fontsize = 15) new_x = interpolate.interp1d(ticks, range(len(ticks)))(ticks) plt.plot(new_x, y, linestyle='-', alpha=1.0, markersize=12, marker='p', color='b') plt.xlabel(x_label, fontsize=24) plt.ylabel(y_label, fontsize=20) plt.savefig(save_file) plt.show()