我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.ylim()。
def calc_auc(y_pred_proba, labels, exp_run_folder, classifier, fold): auc = roc_auc_score(labels, y_pred_proba) fpr, tpr, thresholds = roc_curve(labels, y_pred_proba) curve_roc = np.array([fpr, tpr]) dataile_id = open(exp_run_folder+'/data/roc_{}_{}.txt'.format(classifier, fold), 'w+') np.savetxt(dataile_id, curve_roc) dataile_id.close() plt.plot(fpr, tpr, label='ROC curve: AUC={0:0.2f}'.format(auc)) plt.xlabel('1-Specificity') plt.ylabel('Sensitivity') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.grid(True) plt.title('ROC Fold {}'.format(fold)) plt.legend(loc="lower left") plt.savefig(exp_run_folder+'/data/roc_{}_{}.pdf'.format(classifier, fold), format='pdf') return auc
def plot_pts(points, values, colorbar=True, subplot_loc=None, mytitle=None, show_axis='on', vmin=None, vmax=None, xlim=(0,1), ylim=(0,1)): if subplot_loc is not None: plt.subplot(subplot_loc) pp = plt.scatter(points[:,0], points[:,1], c=values.get_local(), marker=",", s=20, vmin=vmin, vmax=vmax) plt.axis(show_axis) if colorbar: plt.colorbar(pp, fraction=.1, pad=0.2) else: plt.gca().set_aspect('equal') if mytitle is not None: plt.title(mytitle, fontsize=20) if xlim is not None: plt.xlim(xlim) if ylim is not None: plt.ylim(ylim) return pp
def plot_ROC(test_labels, test_predictions): fpr, tpr, thresholds = metrics.roc_curve( test_labels, test_predictions, pos_label=1) auc = "%.2f" % metrics.auc(fpr, tpr) title = 'ROC Curve, AUC = '+str(auc) with plt.style.context(('ggplot')): fig, ax = plt.subplots() ax.plot(fpr, tpr, "#000099", label='ROC curve') ax.plot([0, 1], [0, 1], 'k--', label='Baseline') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(loc='lower right') plt.title(title) return fig
def different_training_sets(): # base+author -> +paraphrasing -> +ifttt -> +generated train = [84.7, 93.2, 90.4, 91.99] test = [3.6, 37.4, 50.94, 55.4] train_recall = [66.6, 88.43, 92.63, 91.21] test_recall = [0.066, 49.05, 50.94, 75.47] #plt.newfigure() X = 1 + np.arange(4) plt.plot(X, train_recall, '--', color='#85c1e5') plt.plot(X, train, '-x', color='#6182a6') plt.plot(X, test_recall, '-o', color='#6182a6') plt.plot(X, test, '-', color='#052548') plt.ylim(0, 100) plt.xlim(0.5, 4.5) plt.xticks(X, ["Base + Author", "+ Paraphrasing", "+ IFTTT", "+ Generated"]) plt.tight_layout() plt.legend(["Train recall", "Train accuracy", "Test recall", "Test accuracy"], loc='lower right') plt.savefig('./figures/training-sets.pdf')
def scatter2d(x,y,title='2dscatterplot',xlabel=None,ylabel=None): fig=plt.figure() plt.scatter(x,y) plt.title(title) if xlabel: plt.xlabel(xlabel) if ylabel: plt.ylabel(ylabel) if not 0<=np.min(x)<=np.max(x)<=1: raise ValueError('summary_scatter2d title:',title,' input x exceeded [0,1] range.\ min:',np.min(x),' max:',np.max(x)) if not 0<=np.min(y)<=np.max(y)<=1: raise ValueError('summary_scatter2d title:',title,' input y exceeded [0,1] range.\ min:',np.min(y),' max:',np.max(y)) plt.xlim([0,1]) plt.ylim([0,1]) return fig
def plot2d_simplex(simplex, ind): fig_dir = "./" plt.cla() n = 1000 x1 = np.linspace(-256, 1024, n) x2 = np.linspace(-256, 1024, n) X, Y = np.meshgrid(x1, x2) Z = np.sqrt(X ** 2 + Y ** 2) plt.contour(X, Y, Z, levels=list(np.arange(0, 1200, 10))) plt.gca().set_aspect("equal") plt.xlim((-256, 768)) plt.ylim((-256, 768)) plt.plot([simplex[0].x[0], simplex[1].x[0]], [simplex[0].x[1], simplex[1].x[1]], color="#000000") plt.plot([simplex[1].x[0], simplex[2].x[0]], [simplex[1].x[1], simplex[2].x[1]], color="#000000") plt.plot([simplex[2].x[0], simplex[0].x[0]], [simplex[2].x[1], simplex[0].x[1]], color="#000000") plt.savefig(os.path.join(fig_dir, "{:03d}.png".format(ind)))
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_multi_err(): """ """ f = open('gzoo1000000_1_2_0.2_pickle.pkl') res = pickle.load(f) sing = res[(0.5, 'single')] multi = res[(0.5, 'multi')] (g1, g2, g3, g4) = load_gold() a = []; b = [] for w in multi: a.append(abs(g2[w][0]- sing[w][0])); b.append(abs(g2[w][0] - multi[w][0])) plt.xlim(0,1); plt.ylim(0,1) plt.scatter(a, b, marker = '.') plt.plot([0, 1], [0, 1], ls="-", c=".5") plt.xlabel('single') plt.ylabel('multi')
def plot_gold(gold): #plt.xlim([0.2,1]) #plt.ylim([0.7,1]) x = [] y = [] for (wid,(sen, spe, n)) in gold.items(): if wid.startswith('S'): x.append(sen) y.append(spe) plt.scatter(x,y, c = 'r', marker = 'o', label = 'Novice') x = []; y = [] for (wid,(sen, spe, n)) in gold.items(): if wid.startswith('E'): x.append(sen) y.append(spe) plt.scatter(x,y, c = 'b', marker = 'x', label = 'Expert') plt.legend(loc = 'lower left') plt.xlabel("Sensitivity") plt.ylabel("Specificity")
def __init__(self,to_plot = True): self.state = np.array([0,0]) self.observation_shape = np.shape(self.get_state())[0] if to_plot: plt.ion() fig = plt.figure() ax1 = fig.add_subplot(111,aspect='equal') #ax1.axis('off') plt.xlim([-0.5,5.5]) plt.ylim([-0.5,5.5]) self.g1 = ax1.add_artist(plt.Circle((self.state[0],self.state[1]),0.1,color='red')) self.fig = fig self.ax1 = ax1 self.fig.canvas.draw() self.fig.canvas.flush_events()
def show(self): keys = [] values = [] for (k, v) in self.letter_db.iteritems(): total = v['total'] right = v['right'] keys.append(k) values.append(100 * float(right / float(total))) groups = len(self.letter_db) index = np.arange(groups) width = 0.5 opacity = 0.4 plt.bar(index, values, linewidth = width, alpha = opacity, color = 'b', label = 'right rate') plt.xlabel('letter') plt.ylabel('predict rgith rate (%)') plt.title('Writer identify: letter right rate') plt.xticks(index + width, keys) plt.ylim(0, 100) plt.legend() plt.show()
def plot_histogram(counter, label, plot=None): import matplotlib.pyplot as plt plt.figure() nums = list(counter.keys()) counts = list(counter.values()) indices = range(len(counts)) bars = plt.bar(indices, counts, align="center") plt.xticks(indices, nums) top = 1.06 * max(counts) plt.ylim(min(counts), top) plt.xlabel("number of %s" % label) plt.ylabel("count") for bar in bars: count = bar.get_height() plt.text(bar.get_x() + bar.get_width() / 2., count, "%.1f%%" % (100.0 * count / sum(counts)), ha="center", va="bottom") if plot: plt.savefig(plot + "histogram_" + label + ".png") else: plt.show()
def save_fft(fil,audio_in): samples = len(audio_in) fft_size = 2**int(floor(log(samples)/log(2.0))) freq = fft(audio_in[0:fft_size]) s_data = numpy.zeros(fft_size/2) x_data = numpy.zeros(fft_size/2) peak = 0; for j in xrange(fft_size/2): if (abs(freq[j]) > peak): peak = abs(freq[j]) for j in xrange(fft_size/2): x_data[j] = log(2.0*(j+1.0)/fft_size); if (x_data[j] < -10): x_data[j] = -10 s_data[j] = 10.0*log(abs(freq[j])/peak)/log(10.0) plt.ylim([-50,0]) plt.plot(x_data,s_data) plt.title('fft log power') plt.grid() fields = fil.split('.') plt.savefig(fields[0]+'_fft.png', bbox_inches="tight") plt.clf() plt.close()
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 accuracy(data): fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot(data['train_acc']) ax1.plot(data['test_acc']) ax2.plot(data['train_loss']) ax2.plot(data['test_loss']) ax1.set_title('accuracy') ax1.set_xlabel('epoch') ax2.set_title('loss') ax2.set_xlabel('epoch') plt.ylim((0, 1)) fig.set_size_inches(20, 5) fig.savefig('train.png', dpi=300, bbox_inches='tight') fig.show()
def main(): #First we train the classifier to get the correct weights w = Perceptron(data_two) for x in data_two: #Get the responses with the correct weights y = x[0]*w[0]+x[1]*w[1] if y >= 0: y = 1 else: y = -1 if y == 1: plt.plot(x[0],x[1],'xb') else: plt.plot(x[0],x[1],'or') #Setting the range of the plot plt.ylim(-2, 2) plt.xlim(-2, 2) plt.show()
def __plot_canvas(self, show, save): if self.x is None: raise Exception("Please run fit() method first") else: plt.close() plt.plot(self.x.real, self.x.imag, '-', color='blue') plt.xlim((0, self.canvas)) plt.ylim((0, self.canvas)) if show and save: plt.savefig(self.path_to_save) plt.show() elif save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') plt.savefig(self.path_to_save) elif show: plt.show()
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_learning_curve(_, history, folder, debug=True): arr = np.asarray( map(lambda k: [k['epoch'], k['train_loss'], k['valid_loss']], history)) plt.figure() plt.plot(arr[:, 0], arr[:, 1], 'r', marker='o', label='Training loss', linewidth=2.0) plt.plot(arr[:, 0], arr[:, 2], 'b', marker='o', label='Validation loss', linewidth=2.0) plt.xlabel('Epochs') plt.ylabel('Loss') plt.ylim([0.0, np.max(arr[:, 1:]) * 1.3]) plt.title('Learning curve') plt.legend() if not debug: plt.savefig('%s/learning_curve.png' % folder, bbox_inches='tight') plt.close()
def display_pr_curve(precision, recall): # following examples from sklearn # TODO: f1 operating point import pylab as plt # Plot Precision-Recall curve plt.clf() plt.plot(recall, precision, label='Precision-Recall curve') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Precision-Recall example: Max f1={0:0.2f}'.format(max_f1)) plt.legend(loc="lower left") 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 plot_graph(cls, date_time, price, graph=None): """ Plot the graph :param graph: MatPlotLibGraph :param date_time: Date time :param price: Price """ date_time = (date_time - datetime.datetime(1970, 1, 1)).total_seconds() if graph is None: graph = plt.scatter([date_time], [price]) plt.xlim([date_time, date_time + 60 * 60 * 24]) # plt.ylim([float(price) * 0.95, float(price) * 1.05]) plt.draw() plt.pause(0.1) else: array = graph.get_offsets() array = np.append(array, [date_time, price]) graph.set_offsets(array) # plt.xlim([array[::2].min() - 0.5, array[::2].max() + 0.5]) plt.ylim([float(array[1::2].min()) - 0.5, float(array[1::2].max()) + 0.5]) plt.draw() plt.pause(0.1) return graph
def set_plot_vsurf(self): ''' Plots the surface velocity vs model number ''' m=self.run_historydata figure(55) i=0 for case in m: plt.figure(55) model=case.get("model_number") vdiv=case.get("v_div_csound_surf") plt.plot(model,vdiv,label=self.run_label[i]) plt.legend() plt.figure(i) plt.plot(model,vdiv,label=self.run_label[i]) plt.legend() i += 1 legend(loc=2) xlabel('model number') ylabel('v_div_csound_surf') ylim(-10.,10.)
def plot(self, ylim=None): import matplotlib.patches as mpatches import matplotlib.pyplot as plt from pylab import subplot number_of_subplots=len(self.scores.keys()) colors = ['blue', 'green', 'orange'] patches = [] for plot_idx, metric in enumerate(self.scores): for i, set_name in enumerate(self.scores[metric].keys()): data = self.scores[metric][set_name][0] time = self.scores[metric][set_name][1] patches.append(mpatches.Patch(color=colors[i], label='{0} {1}'.format(set_name, metric))) ax1 = subplot(number_of_subplots,1,plot_idx+1) ax1.plot(time,data, label='{0}'.format(metric), color=colors[i]) if ylim != None: plt.ylim(ymin=ylim[0]) plt.ylim(ymax=ylim[1]) plt.xlabel('iter') plt.ylabel('{0} {1}'.format(set_name, metric)) ax1.legend(handles=patches) plt.show()
def sample(self, filename, save_samples): gan = self.gan generator = gan.generator.sample sess = gan.session config = gan.config x_v, z_v = sess.run([gan.inputs.x, gan.encoder.z]) sample = sess.run(generator, {gan.inputs.x: x_v, gan.encoder.z: z_v}) plt.clf() fig = plt.figure(figsize=(3,3)) plt.scatter(*zip(*x_v), c='b') plt.scatter(*zip(*sample), c='r') plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.ylabel("z") fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) #plt.savefig(filename) self.plot(data, filename, save_samples) return [{'image': filename, 'label': '2d'}]
def _set_limits(nodes, labels, margin=0.1): xmin = min([ p[0] for _, p in nodes.items() ]) xmax = max([ p[0] for _, p in nodes.items() ]) ymin = min([ p[1] for _, p in nodes.items() ]) ymax = max([ p[1] for _, p in labels.items() ]) plt.xlim([ xmin - margin * abs(xmax - xmin), xmax + margin * abs(xmax - xmin) ]) plt.ylim([ ymin - margin * abs(ymax - ymin), ymax + margin * abs(ymax - ymin) ]) return
def init_plot(self): # Interactive mode plt.ion() # Chart size and margins plt.figure(figsize = (20, 10)) plt.subplots_adjust(hspace = 0.05, top = 0.95, bottom = 0.1, left = 0.05, right = 0.95) # Setup axis labels and ranges plt.title('Pico Technology TC-08') plt.xlabel('Time [s]') plt.ylabel('Temperature [' + self.unit_text + ']') plt.xlim(0, self.duration) self.plotrangemin = 19 self.plotrangemax = 21 plt.ylim(self.plotrangemin, self.plotrangemax) # Enable a chart line for each channel self.lines = [] for i in CHANNEL_CONFIG: if CHANNEL_CONFIG.get(i) != ' ': self.lines.append(line(plt, CHANNEL_NAME.get(i))) else: self.lines.append(line(plt, 'Channel {:d} OFF'.format(i))) # Plot the legend plt.legend(loc = 'best', fancybox = True, framealpha = 0.5) plt.draw()
def process_data(self, channel, samples): if DEBUG: print 'Processing %i samples of channel %i.' % (samples, channel) if samples > 0: time_data = [] temp_data = [] for i in range(0, samples): time_data.append(self.timebuffer[i] / 1000.0) temp_data.append(self.tempbuffer[i]) new_data = OrderedDict(zip(time_data, temp_data)) self.data[channel].update(new_data) self.lines[channel].add(new_data) if min(new_data.values()) < self.plotrangemin: self.plotrangemin = max(new_data.values()) if max(new_data.values()) > self.plotrangemax: self.plotrangemax = max(new_data.values()) plt.ylim(self.plotrangemin * 0.95, self.plotrangemax * 1.05) return max(time_data) return 0
def plot_svd(sigma_full, sigma_dls, k, plot_loc): """ Plot the variance explained by different principal components :param n_components: Number of components to show the variance :param ylim: y-axis limits :param fig: matplotlib Figure object :param ax: matplotlib Axis object :return: fig, ax """ fig, ax = plt.subplots() ax.scatter(range(len(sigma_full)),sigma_full,c='red',s=36,edgecolors='gray', lw = 0.5, label='TCC singular values') ax.scatter(range(len(sigma_dls)),sigma_dls,c='blue',s=36,edgecolors='gray', lw = 0.5, label='TCC_dls singular values') ax.legend(loc='upper right',bbox_to_anchor=(1.05, 1)) ax.set_xlabel('Components') ax.set_ylabel('Singular Values') plt.title('TCC Distribution Singular Values') fig.tight_layout() plt.savefig(plot_loc+ 'plot_pca_variance_explained_' +str(k) +'.pdf')
def tru_plot9(X,labels,t,plot_suffix,clust_names,clust_color, plot_loc): """ From clustering_on_transcript_compatibility_counts, see github for MIT license """ unique_labels = np.unique(labels) plt.figure(figsize=(15,10)) for i in unique_labels: ind = np.squeeze(labels == i) plt.scatter(X[ind,0],X[ind,1],c=clust_color[i],s=36,edgecolors='gray', lw = 0.5, label=clust_names[i]) plt.legend(loc='upper right',bbox_to_anchor=(1.1, 1)) plt.legend(loc='upper right',bbox_to_anchor=(1.19, 1.01)) plt.title(t) plt.xlim([-20,20]) plt.ylim([-20,20]) plt.axis('off') plt.savefig(plot_loc+ 't-SNE_plot_tru_plot9_'+ plot_suffix +'.pdf', bbox_inches='tight') # Plot function with Zeisel's colors corresponding to labels
def phase_diagram_mesh(points, values, title="Phase diagram", xlabel="Pulse Duration (s)", ylabel="Pulse Amplitude (V)", shading="flat", voronoi=False, **kwargs): # fig = plt.figure() if voronoi: from scipy.spatial import Voronoi, voronoi_plot_2d points[:,0] *= 1e9 vor = Voronoi(points) cmap = mpl.cm.get_cmap('RdGy') # colorize for pr, v in zip(vor.point_region, values): region = vor.regions[pr] if not -1 in region: polygon = [vor.vertices[i] for i in region] plt.fill(*zip(*polygon), color=cmap(v)) else: mesh = scaled_Delaunay(points) xs = mesh.points[:,0] ys = mesh.points[:,1] plt.tripcolor(xs,ys,mesh.simplices.copy(),values, cmap="RdGy",shading=shading,**kwargs) plt.xlim(min(xs),max(xs)) plt.ylim(min(ys),max(ys)) plt.title(title, size=18) plt.xlabel(xlabel, size=16) plt.ylabel(ylabel, size=16) cb = plt.colorbar() cb.set_label("Probability",size=16) return mesh
def __init__(self, file_path, fig_path=""): self.fig_params = {"figure_path": "./", "figure_name": "Test-Acc", "label": "ResNet20", "xlabel": "epoch", "ylabel": "testing error (%)", "title": "", "line_width": 2, "line_style": "-", "xlim": [], "ylim": [], "inverse": True, "figure_format": "pdf"} self.file_path = file_path self.fig_path = fig_path split_str = self.fig_path.split("/") label_str = split_str[-2] split_label_str = label_str.split("_") label_str = "" for i in range(len(split_label_str)-2): label_str += "-" + split_label_str[i+1] self.fig_params["label"] = label_str
def plot_benchmark(scores_arr, algorithms_arr, filename): colors = ['#FF6600', '#009933', '#2244AA', '#552299', '#11BBDD'] linestyles = ['-', '--', ':'] passes = len(scores_arr[0]) x = range(1, passes+1) title = "Benchmark Result" plt.figure(1, figsize=(8,8)) plt.title(title, size=20, color='#333333') plt.xlim(1, passes) plt.ylim(0.97, 1.001) plt.ylabel('Score', size=16, color='#333333') plt.xlabel('Validation pass (sorted by score)', size=16, color='#333333') for i in xrange(len(scores_arr)): plt.plot(x, scores_arr[i], color = colors[i%5], label=algorithms_arr[i], alpha=0.5, linewidth=2, linestyle = linestyles[i%3]) plt.legend(loc='lower left') plt.savefig(filename) plt.close(1)
def test_k1(self): mbtr = MBTR([1, 8], k=[1], periodic=False, flatten=False) desc = mbtr.create(H2O) x1 = mbtr._axis_k1 imap = mbtr.index_to_atomic_number smap = {} for index, number in imap.items(): smap[index] = numbers_to_symbols(number) # Visually check the contents # mpl.plot(y) # mpl.ylim(0, y.max()) # mpl.show() # mpl.plot(x1, desc[0][0, :], label="{}".format(smap[0])) # mpl.plot(x1, desc[0][1, :], linestyle=":", linewidth=3, label="{}".format(smap[1])) # mpl.ylabel("$\phi$ (arbitrary units)", size=20) # mpl.xlabel("Inverse distance (1/angstrom)", size=20) # mpl.legend() # mpl.show()
def plot_ROC(self): """ Plot the receiver operating characteristic curve :returns: ROC curve :rtype: matplotlib figure """ fpr = self.subset_metrics('pct', 'false_pos_rate')['value'] tpr = self.subset_metrics('pct', 'recall')['value'] thresholds = np.arange(.01, 1.01, .01) with plt.style.context(('ggplot')): fig, ax = plt.subplots() ax.plot(fpr, tpr, "#000099", label='ROC curve') ax.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(loc='lower right') plt.title('Receiver operating characteristic') return(fig)
def generate_plot(plot_dir, iteration, data_in, output_g, output_d, train_data, args): data_in = data_in.squeeze() generated = output_g['generated'] plt.plot(data_in[0], data_in[1], 'gx') plt.plot(generated[0], generated[1], 'r.') plt.xlim([-2, 2]) plt.ylim([-2, 2]) plt.gca().set_aspect('equal', adjustable='box') plt.axis('off') title = 'Iteration {} \n Gen. Cost {:.2E} Disc. Cost {:.2E}'.format( iteration, float(output_g['batch_cost']), float(output_d['batch_cost'])) plt.title(title) plt.savefig(plot_dir + '/' + str(iteration) + 'Generated.png') plt.clf() # plot and save loss and gradients for key in train_data.keys(): data = np.array(train_data[key]).T plt.plot(data[0], data[1]) plt.title(key + ' for ' + args.loss_type) plt.xlabel('Iterations') plt.ylabel(key) plt.savefig(plot_dir + '/' + key + '.png') plt.clf()
def show_scatter(df, xlim=(-5, 105), ylim=(-5, 105), color="black", marker="o", reg_fit=False): """Create a scatter plot of the data Args: df (pd.DataFrame): The data set to plot xlim ((float, float)): The x-axis limits ylim ((float, float)): The y-axis limits color (str): The color of the scatter points marker (str): The marker style for the scatter points reg_fit (bool): Whether to plot a linear regression on the graph """ sns.regplot( x="x", y="y", data=df, ci=None, fit_reg=reg_fit, marker=marker, scatter_kws={"s": 50, "alpha": 0.7, "color": color}, line_kws={"linewidth": 4, "color": "red"}) plt.xlim(xlim) plt.ylim(ylim) plt.tight_layout()
def plot_spikepattern(spike_trains, sim_time): """Plot set of spike trains (spike pattern)""" plt.ioff() plt.figure() for i in xrange(len(spike_trains)): spike_times = spike_trains[i].value plt.plot(spike_times, np.full(len(spike_times), i, dtype=np.int), 'k.') plt.xlim((0.0, sim_time)) plt.ylim((0, len(spike_trains))) plt.xlabel('Time (ms)') plt.ylabel('Neuron index') plt.show() plt.ion()
def plot_spiker(record, spike_trains_target, neuron_index=0): """Plot spikeraster and target timings for given neuron index""" plt.ioff() spike_trains = [np.array(i.spiketrains[neuron_index]) for i in record.segments] n_segments = record.size['segments'] plt.figure() for i in xrange(len(spike_trains)): plt.plot(spike_trains[i], np.full(len(spike_trains[i]), i + 1, dtype=np.int), 'k.') target_timings = spike_trains_target[neuron_index].value plt.plot(target_timings, np.full(len(target_timings), 1.025 * n_segments), 'kx', markersize=8, markeredgewidth=2) plt.xlim((0., np.float(record.segments[0].t_stop))) plt.ylim((0, np.int(1.05 * n_segments))) plt.xlabel('Time (ms)') plt.ylabel('Trials') plt.title('Output neuron {}'.format(neuron_index)) plt.show() plt.ion()
def plot_streamlines(self, both=False, Hbot=None, Htop=None, R=None, **params): R = self.params.R if R is None else R Htop = self.params.Htop if Htop is None else Htop Hbot = self.params.Hbot if Hbot is None else Hbot #ax = plt.axes(xlim=(-R, R), ylim=(-Hbot, Htop)) dolfin.parameters["allow_extrapolation"] = True if both: Fel, Fdrag = fields.get_functions("force_pointsize", "Fel", "Fdrag", **self.sim_params) streamlines(patches=[self.polygon_patches(), self.polygon_patches()], R=R, Htop=Htop, Hbot=Hbot, Nx=100, Ny=100, Fel=Fel, Fdrag=Fdrag, **params) else: streamlines(patches=[self.polygon_patches()], R=R, Htop=Htop, Hbot=Hbot, Nx=100, Ny=100, F=self.F, **params) dolfin.parameters["allow_extrapolation"] = False # for p in patches: # p.set_zorder(100) # plt.gca().add_patch(p) plt.xlim(-R, R) plt.ylim(-Hbot, Htop)
def plot_test_function(orderx,ordery): s = PseudoSpectralDiscretization2D(orderx,XMIN,XMAX, ordery,YMIN,YMAX) X,Y = s.get_x2d() f_ana = f(X,Y) plt.pcolor(X,Y,f_ana) plt.xlabel('x',fontsize=16) plt.ylabel('y',fontsize=16) plt.xlim(XMIN,XMAX) plt.ylim(YMIN,YMAX) cb = plt.colorbar() cb.set_label(label=r'$\cos(x)\sin(2 y)$',fontsize=16) for postfix in ['.png','.pdf']: name = 'test_function'+postfix if USE_FIGS_DIR: name = 'figs/' + name plt.savefig(name, bbox_inches='tight') plt.clf()
def correct_function(): # order is para-prim, para-comp, cheat-prim, cheat-comp, scenario-prim, scenario-comp SEMPRE = [85.04, 66.98, 77.5, 49.01, 60, 33] DEEP_SEMPRE = [95.23, 75.64, 50, 47.05, 42.85, 16.66] X = np.arange(3) width = (0.8-0.1)/4 s_p = [SEMPRE[0], SEMPRE[2], SEMPRE[4]] s_c = [SEMPRE[1], SEMPRE[3], SEMPRE[5]] d_p = [DEEP_SEMPRE[0], DEEP_SEMPRE[2], DEEP_SEMPRE[4]] d_c = [DEEP_SEMPRE[1], DEEP_SEMPRE[3], DEEP_SEMPRE[5]] plt.bar(X, s_p, width=width, color='#85c1e5') plt.bar(X+width, d_p, width=width, color='#254e7b') plt.bar(X+2*width+0.1, s_c, width=width, color='#85c1e5') plt.bar(X+3*width+0.1, d_c, width=width, color='#254e7b') width = (0.8-0.1)/4 plt.xticks(np.array([width, 3*width+0.1, 1+width, 1+3*width+0.1, 2+width, 2+3*width+0.1]), ["Prim.", "Comp.", "Prim.", "Comp.", "Prim.", "Comp."]) plt.text(0.4, -10, "Paraphrasing", ha='center', fontsize=18) plt.text(1.4, -10, "Scenarios", ha='center', fontsize=18) plt.text(2.4, -10, "Composition", ha='center', fontsize=18) plt.ylim(0, 100) plt.xlim(-0.1, 2.9) #plt.tight_layout() plt.legend(["SEMPRE", "Neural Net"], loc ="upper right") plt.savefig('./figures/correct-function.pdf')
def accuracy_against_sempre(): # order is para-prim, para-comp, cheat-prim, cheat-comp, scenario-prim, scenario-comp SEMPRE = [71.4, 50.2, 67.5, 33.3, 34.28, 30.5] DEEP_SEMPRE = [89.11, 55.27, 47.5, 29.4, 34.28, 16.66] X = np.arange(3) width = (0.8-0.1)/4 s_p = [SEMPRE[0], SEMPRE[2], SEMPRE[4]] s_c = [SEMPRE[1], SEMPRE[3], SEMPRE[5]] d_p = [DEEP_SEMPRE[0], DEEP_SEMPRE[2], DEEP_SEMPRE[4]] d_c = [DEEP_SEMPRE[1], DEEP_SEMPRE[3], DEEP_SEMPRE[5]] plt.bar(X, s_p, width=width, color='#85c1e5') plt.bar(X+width, d_p, width=width, color='#254e7b') plt.bar(X+2*width+0.1, s_c, width=width, color='#85c1e5') plt.bar(X+3*width+0.1, d_c, width=width, color='#254e7b') width = (0.8-0.1)/4 plt.xticks(np.array([width, 3*width+0.1, 1+width, 1+3*width+0.1, 2+width, 2+3*width+0.1]), ["Prim.", "Comp.", "Prim.", "Comp.", "Prim.", "Comp."]) plt.text(0.4, -10, "Paraphrasing", ha='center', fontsize=18) plt.text(1.4, -10, "Scenarios", ha='center', fontsize=18) plt.text(2.4, -10, "Composition", ha='center', fontsize=18) plt.ylim(0, 100) plt.xlim(-0.1, 2.9) #plt.tight_layout() plt.legend(["SEMPRE", "Neural Net"], loc ="upper right") plt.savefig('./figures/accuracy-combined.pdf')
def extensibility(): # order is new device acc, new device recall, new domain acc, new domain recall SEMPRE = [100 * 117./214., 100 * (10.+63.)/(15.+104.), 100 * (42.+232.)/(535.+75.), 100 * (32.+136.)/(286.+48.)] DEEP_SEMPRE = [38, 47, 55, 74] X = np.arange(2) width = (0.8-0.1)/4 s_a = [SEMPRE[0], SEMPRE[2]] s_r = [SEMPRE[1], SEMPRE[3]] d_a = [DEEP_SEMPRE[0], DEEP_SEMPRE[2]] d_r = [DEEP_SEMPRE[1], DEEP_SEMPRE[3]] plt.bar(X, s_a, width=width, color='#85c1e5') plt.bar(X+width, d_a, width=width, color='#254e7b') plt.bar(X+2*width+0.1, s_r, width=width, color='#85c1e5') plt.bar(X+3*width+0.1, d_r, width=width, color='#254e7b') width = (0.8-0.1)/4 plt.xticks(np.array([width, 3*width+0.1, 1+width, 1+3*width+0.1, 2+width, 2+3*width+0.1]), ["Accuracy", "Recall", "Accuracy", "Recall"]) plt.text(0.4, -10, "New Device", ha='center', fontsize=18) plt.text(1.4, -10, "New Domain", ha='center', fontsize=18) plt.ylim(0, 100) plt.xlim(-0.1, 1.9) #plt.tight_layout() plt.legend(["SEMPRE", "Neural Net"], loc ="upper right") plt.savefig('./figures/extensibility.pdf')
def recall(): # order is para-prim, para-comp, cheat-prim, cheat-comp, scenario-prim, scenario-comp SEMPRE = [81.06, 55.33, 65.38, 34.69, 40.0, 38.46] DEEP_SEMPRE = [93.75, 65.93, 60.0, 30.61, 58.33, 22.72] X = np.arange(3) width = (0.8-0.1)/4 s_p = [SEMPRE[0], SEMPRE[2], SEMPRE[4]] s_c = [SEMPRE[1], SEMPRE[3], SEMPRE[5]] d_p = [DEEP_SEMPRE[0], DEEP_SEMPRE[2], DEEP_SEMPRE[4]] d_c = [DEEP_SEMPRE[1], DEEP_SEMPRE[3], DEEP_SEMPRE[5]] plt.bar(X, s_p, width=width, color='#85c1e5') plt.bar(X+width, d_p, width=width, color='#254e7b') plt.bar(X+2*width+0.1, s_c, width=width, color='#85c1e5') plt.bar(X+3*width+0.1, d_c, width=width, color='#254e7b') width = (0.8-0.1)/4 plt.xticks(np.array([width, 3*width+0.1, 1+width, 1+3*width+0.1, 2+width, 2+3*width+0.1]), ["Prim.", "Comp.", "Prim.", "Comp.", "Prim.", "Comp."]) plt.text(0.4, -10, "Paraphrasing", ha='center', fontsize=18) plt.text(1.4, -10, "Scenarios", ha='center', fontsize=18) plt.text(2.4, -10, "Composition", ha='center', fontsize=18) plt.ylim(0, 100) plt.xlim(-0.1, 2.9) #plt.tight_layout() plt.legend(["SEMPRE", "Neural Net"], loc ="upper right") plt.savefig('./figures/recall.pdf')
def dataset_train(): # 0 param, 1 param, 2 param, 3+ param base = [1388, 1285, 977, 307] paraphrasing = [1185, 2277, 1471, 900] ifttt = [1525, 645, 414, 2607] generated = [569, 2098, 2723, 4610] data = np.array([base, paraphrasing, ifttt, generated]) p_0 = data[:,0] p_1 = data[:,1] p_2 = data[:,2] p_3 = data[:,3] width = 0.7 X = np.arange(4) plt.bar(X, p_3, width=width, color='#ffffff', bottom=p_0+p_1+p_2) plt.bar(X, p_2, width=width, color='#cde6f4', bottom=p_0+p_1) plt.bar(X, p_1, width=width, color='#85c1e5', bottom=p_0) plt.bar(X, p_0, width=width, color='#254e7b') plt.xticks(X + width/2, ["Base +\n Author", "Paraphrasing", "IFTTT", "Generated"]) plt.xlim(-0.3, 4) plt.ylim(0, 11000) plt.tight_layout() plt.legend(["3+ Params", "2 Params", "1 Param", "0 Params"], loc='upper left') plt.savefig('./figures/dataset-train.pdf')
def learning(): with open('./data/train-stats.json', 'r') as fp: data = np.array(json.load(fp), dtype=np.float32) loss = data[:,0] train_acc = 100*data[:,1] dev_acc = 100*data[:,2] dev_mov_avg = movingaverage(dev_acc, 3) X = 1 + np.arange(len(data)) plt.xlim(0, len(data)+1) #plt.plot(X, loss) #plt.ylabel('Loss') plt.xlabel('Training epoch', fontsize=20) #plt.gca().twinx() plt.plot(X, train_acc) plt.plot(X, dev_acc) plt.plot(X[1:-1], dev_mov_avg, '--') #plt.ylabel('Accuracy') plt.ylim(0, 100) plt.tight_layout() plt.legend(["Train Accuracy", "Dev Accuracy"], loc="lower right") plt.savefig('./figures/learning.pdf')
def plot_precision_recall(y_score, y_test, clf_target_ids, clf_target_names, title='Precision-Recall curve'): # Get multilabel precision recall curve precision, recall, average_precision = multilabel_precision_recall(y_score, y_test, clf_target_ids, clf_target_names) # Plot Precision-Recall curve for each class plt.clf() plt.plot(recall["average"], precision["average"], label='Average', linewidth=3) # label='Average (area = {0:0.2f})' # ''.format(average_precision["micro"])) plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.0]) plt.xlim([0.0, 1.0]) plt.legend(loc="lower left") plt.show() for name in clf_target_names: if name not in recall: continue plt.plot(recall[name], precision[name], # label='{}'.format(name.title().replace('_', ' '))) label='{0} (AP = {1:0.2f})' ''.format(name.title().replace('_', ' '), average_precision[name])) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.xlabel('Recall') plt.ylabel('Precision') plt.title(title) plt.legend(loc="lower left") plt.show(block=False)
def plot_roc_curve(test_target, pred_score): # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() fpr['micro'], tpr['micro'], _ = metrics.roc_curve(test_target, np.max(pred_score, axis=1)) roc_auc['micro'] = metrics.auc(fpr['micro'], tpr['micro']) # Plot of a ROC curve for a specific class plt.figure() plt.plot(fpr['micro'], tpr['micro'], label='micro-average ROC curve (area = {0:0.2f})' ''.format(metrics.roc_auc['micro'])) # plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % metrics.auc(fpr, tpr)) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show(block=True) # for i in range(n_classes): # fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) # roc_auc[i] = auc(fpr[i], tpr[i]) # python metrics.py --classifier ~/data/results/plot/classifier.h5
def plot_precision_recall(indir, gts_file, outdir): groundtruths = read_item_tag(gts_file) plt.figure(1) indir = utils.abs_path_dir(indir) for item in os.listdir(indir): if ".csv" in item: isrcs = read_preds(indir + "/" + item) test_groundtruths = [] predictions = [] for isrc in isrcs: if isrc in groundtruths: test_groundtruths.append(groundtruths[isrc]) predictions.append(isrcs[isrc]) test_groundtruths = [tag=="s" for tag in test_groundtruths] precision, recall, _ = precision_recall_curve(test_groundtruths, predictions) plt.plot(recall, precision, label=item[:-4] + " (" + str(round(average_precision_score(test_groundtruths, predictions), 3)) + ")") plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([-0.05, 1.05]) plt.title('Precision-Recall curve for Algo (AUC)') plt.legend(loc='best') plt.savefig(outdir + "precision_recall.png", dpi=200, bbox_inches="tight") # plt.show() plt.close() utils.print_success("Precision-Recall curve created in " + outdir)