我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pylab.gcf()。
def plot_rgb(image, name, label=None, label_color='w', label_size='large'): """ This will plot the r,g,b channels of an *image* of shape (N,M,3) or (N,M,4). *name* is the prefix of the file name, which will be supplemented with "_rgb.png." *label*, *label_color* and *label_size* may also be specified. """ import pylab Nvec = image.shape[0] image[np.isnan(image)] = 0.0 if image.shape[2] >= 4: image = image[:,:,:3] pylab.clf() pylab.gcf().set_dpi(100) pylab.gcf().set_size_inches((Nvec/100.0, Nvec/100.0)) pylab.gcf().subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.0, hspace=0.0) pylab.imshow(image, interpolation='nearest') if label is not None: pylab.text(20, 20, label, color = label_color, size=label_size) pylab.savefig("%s_rgb.png" % name) pylab.clf()
def on_epoch_end(self, epoch, logs={}): self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % epoch)) self.show_edit_distance(256) word_batch = next(self.text_img_gen)[0] res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words]) for i in range(self.num_display_words): pylab.subplot(self.num_display_words, 1, i + 1) if K.image_dim_ordering() == 'th': the_input = word_batch['the_input'][i, 0, :, :] else: the_input = word_batch['the_input'][i, :, :, 0] pylab.imshow(the_input, cmap='Greys_r') pylab.xlabel('Truth = \'%s\' Decoded = \'%s\'' % (word_batch['source_str'][i], res[i])) fig = pylab.gcf() fig.set_size_inches(10, 12) pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % epoch)) pylab.close() # Input Parameters
def on_epoch_end(self, epoch, logs={}): self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch))) self.show_edit_distance(256) word_batch = next(self.text_img_gen)[0] res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words]) if word_batch['the_input'][0].shape[0] < 256: cols = 2 else: cols = 1 for i in range(self.num_display_words): pylab.subplot(self.num_display_words // cols, cols, i + 1) if K.image_dim_ordering() == 'th': the_input = word_batch['the_input'][i, 0, :, :] else: the_input = word_batch['the_input'][i, :, :, 0] pylab.imshow(the_input.T, cmap='Greys_r') pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i])) fig = pylab.gcf() fig.set_size_inches(10, 13) pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch))) pylab.close()
def drawState(fruitRow, fruitColumn, basket): global gridSize # column is the x axis fruitX = fruitColumn # Invert matrix style points to coordinates fruitY = (gridSize - fruitRow + 1) statusTitle = "Wins: " + str(winCount) + " Losses: " + str(loseCount) + " TotalGame: " + str(numberOfGames) axis.set_title(statusTitle, fontsize=30) for p in [ patches.Rectangle( ((ground - 1), (ground)), 11, 10, facecolor="#000000" # Black ), patches.Rectangle( (basket - 1, ground), 2, 0.5, facecolor="#FF0000" # No background ), patches.Rectangle( (fruitX - 0.5, fruitY - 0.5), 1, 1, facecolor="#FF0000" # red ), ]: axis.add_patch(p) display.clear_output(wait=True) display.display(pl.gcf())
def tile_images(image_batch, image_width=28, image_height=28, image_channel=1, dir=None, filename="images"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) pylab.imshow(image_batch[m].reshape((image_width, image_height)), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def scatter_labeled_z(z_batch, label_batch, filename="labeled_z"): fig = pylab.gcf() fig.set_size_inches(20.0, 16.0) pylab.clf() colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"] for n in range(z_batch.shape[0]): result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none') classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] recs = [] for i in range(0, len(colors)): recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i])) ax = pylab.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5)) pylab.xticks(pylab.arange(-4, 5)) pylab.yticks(pylab.arange(-4, 5)) pylab.xlabel("z1") pylab.ylabel("z2") pylab.savefig(filename)
def despine(fig=None, ax=None, top=True, right=True, left=False, bottom=False): """Remove the top and right spines from plot(s). fig : matplotlib figure figure to despine all axes of, default uses current figure ax : matplotlib axes specific axes object to despine top, right, left, bottom : boolean if True, remove that spine """ if fig is None and ax is None: axes = plt.gcf().axes elif fig is not None: axes = fig.axes elif ax is not None: axes = [ax] for ax_i in axes: for side in ["top", "right", "left", "bottom"]: ax_i.spines[side].set_visible(not locals()[side])
def visualize_reconstruction(xp, model, x, visualization_dir, epoch, gpu=False): x_variable = chainer.Variable(xp.asarray(x)) _x = model.decode(model.encode(x_variable), test=True) _x.to_cpu() _x = _x.data fig = pylab.gcf() fig.set_size_inches(8.0, 8.0) pylab.clf() pylab.gray() for m in range(50): i = m / 10 j = m % 10 pylab.subplot(10, 10, 20 * i + j + 1, xticks=[], yticks=[]) pylab.imshow(x[m].reshape((28, 28)), interpolation="none") pylab.subplot(10, 10, 20 * i + j + 10 + 1, xticks=[], yticks=[]) pylab.imshow(_x[m].reshape((28, 28)), interpolation="none") # pylab.imshow(np.clip((_x_batch.data[m] + 1.0) / 2.0, 0.0, 1.0).reshape( # (config.img_channel, config.img_width, config.img_width)), interpolation="none") pylab.axis("off") pylab.savefig("{}/reconstruction_{}.png".format(visualization_dir, epoch)) # pylab.show()
def show_chains(rbm, state, dataset, num_particles=20, num_samples=20, show_every=10, display=True, figname='Gibbs chains', figtitle='Gibbs chains'): samples = gnp.zeros((num_particles, num_samples, state.v.shape[1])) state = state[:num_particles, :, :] for i in range(num_samples): samples[:, i, :] = rbm.vis_expectations(state.h) for j in range(show_every): state = rbm.step(state) npix = dataset.num_rows * dataset.num_cols rows = [vm.hjoin([samples[i, j, :npix].reshape((dataset.num_rows, dataset.num_cols)).as_numpy_array() for j in range(num_samples)], normalize=False) for i in range(num_particles)] grid = vm.vjoin(rows, normalize=False) if display: pylab.figure(figname) pylab.matshow(grid, cmap='gray', fignum=False) pylab.title(figtitle) pylab.gcf().canvas.draw() return grid
def plot_kde(data, dir=None, filename="kde", color="Greens"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() bg_color = sns.color_palette(color, n_colors=256)[0] ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2) ax.set_axis_bgcolor(bg_color) kde = ax.get_figure() pylab.xlim(-4, 4) pylab.ylim(-4, 4) kde.savefig("{}/{}.png".format(dir, filename))
def plot_kde(data, dir=None, filename="kde", color="Greens"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() bg_color = sns.color_palette(color, n_colors=256)[0] ax = sns.kdeplot(data[:, 0], data[:,1], shade=True, cmap=color, n_levels=30, clip=[[-4, 4]]*2) ax.set_axis_bgcolor(bg_color) kde = ax.get_figure() pylab.xlim(-4, 4) pylab.ylim(-4, 4) kde.savefig("{}/{}".format(dir, filename))
def tile_binary_images(x, dir=None, filename="x", row=10, col=10): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(col * 2, row * 2) pylab.clf() pylab.gray() for m in range(row * col): pylab.subplot(row, col, m + 1) pylab.imshow(np.clip(x[m], 0, 1), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def tile_binary_images(x, dir=None, filename="x"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) pylab.imshow(np.clip(x[m], 0, 1), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def plot_z(z, dir=None, filename="z", xticks_range=None, yticks_range=None): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() for n in xrange(z.shape[0]): result = pylab.scatter(z[n, 0], z[n, 1], s=40, marker="o", edgecolors='none') pylab.xlabel("z1") pylab.ylabel("z2") if xticks_range is not None: pylab.xticks(pylab.arange(-xticks_range, xticks_range + 1)) if yticks_range is not None: pylab.yticks(pylab.arange(-yticks_range, yticks_range + 1)) pylab.savefig("{}/{}.png".format(dir, filename))
def visualize_x(reconstructed_x_batch, image_width=28, image_height=28, image_channel=1, dir=None): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() if image_channel == 1: pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) if image_channel == 1: pylab.imshow(reconstructed_x_batch[m].reshape((image_width, image_height)), interpolation="none") elif image_channel == 3: pylab.imshow(reconstructed_x_batch[m].reshape((image_channel, image_width, image_height)), interpolation="none") pylab.axis("off") pylab.savefig("%s/reconstructed_x.png" % dir)
def visualize_labeled_z(z_batch, label_batch, dir=None): fig = pylab.gcf() fig.set_size_inches(20.0, 16.0) pylab.clf() colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"] for n in xrange(z_batch.shape[0]): result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none') classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] recs = [] for i in range(0, len(colors)): recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i])) ax = pylab.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5)) pylab.xticks(pylab.arange(-4, 5)) pylab.yticks(pylab.arange(-4, 5)) pylab.xlabel("z1") pylab.ylabel("z2") pylab.savefig("%s/labeled_z.png" % dir)
def plot(self): """Visualize the label images (e.g. for debugging) :return: The current figure """ import pylab pylab.imshow(self.image, interpolation='nearest') return pylab.gcf()
def save_plots(self, folder): import pylab as pl pl.gcf().set_size_inches(15, 15) pl.clf() self.homography.plot_original() pl.savefig(join(folder, 'homography-original.jpg')) pl.clf() self.homography.plot_rectified() pl.savefig(join(folder, 'homography-rectified.jpg')) pl.clf() self.driving_layers.plot(overlay_alpha=0.7) pl.savefig(join(folder, 'segnet-driving.jpg')) pl.clf() self.facade_layers.plot(overlay_alpha=0.7) pl.savefig(join(folder, 'segnet-i12-facade.jpg')) pl.clf() self.plot_grids() pl.savefig(join(folder, 'grid.jpg')) pl.clf() self.plot_regions() pl.savefig(join(folder, 'regions.jpg')) pl.clf() pl.gcf().set_size_inches(6, 4) self.plot_facade_cuts() pl.savefig(join(folder, 'facade-cuts.jpg'), dpi=300) pl.savefig(join(folder, 'facade-cuts.svg')) imsave(join(folder, 'walls.png'), self.wall_colors)
def on_epoch_end(self, epoch, logs={}): self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch))) self.show_edit_distance(256) word_batch = next(self.text_img_gen)[0] res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words]) if word_batch['the_input'][0].shape[0] < 256: cols = 2 else: cols = 1 for i in range(self.num_display_words): pylab.subplot(self.num_display_words // cols, cols, i + 1) if K.image_data_format() == 'channels_first': the_input = word_batch['the_input'][i, 0, :, :] else: the_input = word_batch['the_input'][i, :, :, 0] pylab.imshow(the_input.T, cmap='Greys_r') pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i])) fig = pylab.gcf() fig.set_size_inches(10, 13) pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch))) pylab.close()
def generateImages(picklefile, pickledir, filehash, imagedir, pietype): leaf_file = open(os.path.join(pickledir, picklefile), 'rb') (piedata, pielabels) = cPickle.load(leaf_file) leaf_file.close() pylab.figure(1, figsize=(6.5,6.5)) ax = pylab.axes([0.2, 0.15, 0.6, 0.6]) pylab.pie(piedata, labels=pielabels) pylab.savefig(os.path.join(imagedir, '%s-%s.png' % (filehash, pietype))) pylab.gcf().clear() os.unlink(os.path.join(pickledir, picklefile))
def plot_channel(image, name, cmap='gist_heat', log=True, dex=3, zero_factor=1.0e-10, label=None, label_color='w', label_size='large'): """ This function will plot a single channel. *image* is an array shaped like (N,M), *name* is the pefix for the output filename. *cmap* is the name of the colormap to apply, *log* is whether or not the channel should be logged. Additionally, you may optionally specify the minimum-value cutoff for scaling as *dex*, which is taken with respect to the minimum value of the image. *zero_factor* applies a minimum value to all zero-valued elements. Optionally, *label*, *label_color* and *label_size* may be specified. """ import matplotlib import pylab Nvec = image.shape[0] image[np.isnan(image)] = 0.0 ma = image[image>0.0].max() image[image==0.0] = ma*zero_factor if log: mynorm = matplotlib.colors.LogNorm(ma/(10.**dex), ma) pylab.clf() pylab.gcf().set_dpi(100) pylab.gcf().set_size_inches((Nvec/100.0, Nvec/100.0)) pylab.gcf().subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.0, hspace=0.0) mycm = pylab.cm.get_cmap(cmap) if log: pylab.imshow(image,cmap=mycm, norm=mynorm, interpolation='nearest') else: pylab.imshow(image,cmap=mycm, interpolation='nearest') if label is not None: pylab.text(20, 20,label, color = label_color, size=label_size) pylab.savefig("%s_%s.png" % (name,cmap)) pylab.clf()
def zipf(self, message, users): source_user = message.author.name source_user = source_user.strip('@').split('#')[0] target_users = [user.strip('@').split('#')[0] for user in users.split()] if len(users) == 0: target_users = [source_user] if users == '*': if message.server is not None: target_users = [member.name for member in message.server.members] target_users = [user for user in target_users if self.check_nickname_valid(user.lower()) is None] image_file_name = self.quotes_file_name(source_user.lower())[:-4] + '.png' pylab.title('Word frequencies') for user in target_users: quotes_file = codecs.open(self.quotes_file_name(user.lower()), 'r', encoding='utf-8') lines = quotes_file.readlines() quotes_file.close() if len(lines) < 20: continue tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+') tokens = self.filter_to_english_words(tokenizer.tokenize(str(lines))) if len(tokens) < 200: continue freq = nltk.FreqDist(tokens) self.plot_word_frequencies(freq, user) pylab.legend() pylab.savefig(image_file_name) pylab.gcf().clear() await self.client.send_file(message.channel, image_file_name)
def drawTwoDf(pl, df1, df2, title=''): """?????df""" pl.figure pl.rc('font', family='simhei') if title != '': if agl.is_utf8(title): title = title.decode('utf8') fig = pl.gcf() ax1 = fig.add_subplot(211) df1.plot(ax=ax1, title=title) ax2 = fig.add_subplot(212) df2.plot(ax=ax2) pl.show() pl.close()
def gcf(self): return pl.gcf()
def save(self): if len(self.figs) == 0: self.use_figure = True self.figs.append(pl.gcf()) sPid = str(os.getpid()) for i,fig in enumerate(self.figs): fname = self.path + self.name + "_" + sPid + '_' + str(i) +".png" if self.use_figure: fname = self.path + self.name + "_" + sPid + '_' + str(len(self.imgs)) + ".png" self.imgs.append(fname) self.cur_img_fname = fname pl.savefig(fname, dpi=70)
def tight_layout(): from matplotlib import get_backend from pylab import gcf if get_backend().lower() in ['agg', 'macosx']: gcf().set_tight_layout(True) else: plt.tight_layout()
def visualize_10_2d_gaussian_prior(n_z, y_label, visualization_dir=None): z_batch = sample_z_from_n_2d_gaussian_mixture(len(y_label), n_z, y_label, 10, False) z_batch = z_batch.data fig = pylab.gcf() fig.set_size_inches(15, 12) pylab.clf() colors = ["#2103c8", "#0e960e", "#e40402", "#05aaa8", "#ac02ab", "#aba808", "#151515", "#94a169", "#bec9cd", "#6a6551"] for n in xrange(z_batch.shape[0]): result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[y_label[n]], s=40, marker="o", edgecolors='none') classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] recs = [] for i in range(0, len(colors)): recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i])) ax = pylab.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5)) pylab.xticks(pylab.arange(-4, 5)) pylab.yticks(pylab.arange(-4, 5)) pylab.xlabel("z1") pylab.ylabel("z2") if visualization_dir is not None: pylab.savefig("%s/10_2d-gaussian.png" % visualization_dir) pylab.show()
def visualize_labeled_z(xp, model, x, y_label, visualization_dir, epoch, gpu=False): x = chainer.Variable(xp.asarray(x)) z_batch = model.encode(x, test=True) z_batch.to_cpu() z_batch = z_batch.data fig = pylab.gcf() fig.set_size_inches(8.0, 8.0) pylab.clf() colors = ["#2103c8", "#0e960e", "#e40402", "#05aaa8", "#ac02ab", "#aba808", "#151515", "#94a169", "#bec9cd", "#6a6551"] for n in xrange(z_batch.shape[0]): result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[y_label[n]], s=40, marker="o", edgecolors='none') classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] recs = [] for i in range(0, len(colors)): recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i])) ax = pylab.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5)) pylab.xticks(pylab.arange(-4, 5)) pylab.yticks(pylab.arange(-4, 5)) pylab.xlabel("z1") pylab.ylabel("z2") pylab.savefig("{}/labeled_z_{}.png".format(visualization_dir, epoch)) # pylab.show()
def drawImage(self,ax=None,invert=True): if not ax: ax = plt.gca() if self.config['data']['survey']=='sdss': # Optical Image im = ugali.utils.plotting.getSDSSImage(**self.image_kwargs) # Flipping JPEG: # https://github.com/matplotlib/matplotlib/issues/101 im = im[::-1] ax.annotate("SDSS Image",**self.label_kwargs) else: im = ugali.utils.plotting.getDSSImage(**self.image_kwargs) im = im[::-1,::-1] ax.annotate("DSS Image",**self.label_kwargs) size=self.image_kwargs.get('radius',1.0) # Celestial coordinates x = np.linspace(-size,size,im.shape[0]) y = np.linspace(-size,size,im.shape[1]) xx, yy = np.meshgrid(x,y) #kwargs = dict(cmap='gray',interpolation='none') kwargs = dict(cmap='gray',coord='C') im = drawProjImage(xx,yy,im,**kwargs) try: plt.gcf().delaxes(ax.cax) except AttributeError: pass return im
def drawMembersSpatial(self,data): ax = plt.gca() if isinstance(data,basestring): filename = data data = pyfits.open(filename)[1].data xmin, xmax = -0.25,0.25 ymin, ymax = -0.25,0.25 xx,yy = np.meshgrid(np.linspace(xmin,xmax),np.linspace(ymin,ymax)) x_prob, y_prob = sphere2image(self.ra, self.dec, data['RA'], data['DEC']) sel = (x_prob > xmin)&(x_prob < xmax) & (y_prob > ymin)&(y_prob < ymax) sel_prob = data['PROB'][sel] > 5.e-2 index_sort = numpy.argsort(data['PROB'][sel][sel_prob]) plt.scatter(x_prob[sel][~sel_prob], y_prob[sel][~sel_prob], marker='o', s=2, c='0.75', edgecolor='none') sc = plt.scatter(x_prob[sel][sel_prob][index_sort], y_prob[sel][sel_prob][index_sort], c=data['PROB'][sel][sel_prob][index_sort], marker='o', s=10, edgecolor='none', cmap='jet', vmin=0., vmax=1.) # Spectral_r drawProjImage(xx,yy,None,coord='C') #ax.set_xlim(xmax, xmin) #ax.set_ylim(ymin, ymax) #plt.xlabel(r'$\Delta \alpha_{2000}\,(\deg)$') #plt.ylabel(r'$\Delta \delta_{2000}\,(\deg)$') plt.xticks([-0.2, 0., 0.2]) plt.yticks([-0.2, 0., 0.2]) divider = make_axes_locatable(ax) ax_cb = divider.new_horizontal(size="7%", pad=0.1) plt.gcf().add_axes(ax_cb) pylab.colorbar(sc, cax=ax_cb, orientation='vertical', ticks=[0, 0.2, 0.4, 0.6, 0.8, 1.0], label='Membership Probability') ax_cb.yaxis.tick_right()
def plot(self): if self.vis is not None: pylab.figure('log probs') pylab.clf() plot_objfn(self.fe_info['main'], self.log_Z_info['main'], 'b', label='Raw') plot_objfn(self.fe_info['avg'], self.log_Z_info['avg'], 'r', label='Averaged') pylab.title('log probs') pylab.legend(loc='lower right') pylab.gcf().canvas.draw() pylab.figure('log probs (zoomed)') pylab.clf() plot_objfn(self.fe_info['main'], self.log_Z_info['main'], 'b', zoom=True, label='Raw') plot_objfn(self.fe_info['avg'], self.log_Z_info['avg'], 'r', label='Averaged') pylab.title('log probs (zoomed)') pylab.legend(loc='lower right') pylab.gcf().canvas.draw() if self.target_moments is not None: pylab.figure('moment matching objective') pylab.clf() plot_objfn(self.dp_info['main'], self.log_Z_info['main'], 'b', label='Raw') plot_objfn(self.dp_info['avg'], self.log_Z_info['avg'], 'r', label='Averaged') pylab.title('moment matching objective') pylab.legend(loc='lower right') pylab.gcf().canvas.draw() pylab.figure('moment matching objective (zoomed)') pylab.clf() plot_objfn(self.dp_info['main'], self.log_Z_info['main'], 'b', zoom=True, label='Raw') plot_objfn(self.dp_info['avg'], self.log_Z_info['avg'], 'r', label='Averaged') pylab.title('moment matching objective (zoomed)') pylab.legend(loc='lower right') pylab.gcf().canvas.draw()
def after_step(self, rbm, trainer, i): it = i + 1 save = it in self.expt.save_after display = it in self.expt.show_after if save: if self.expt.save_particles: storage.dump(trainer.fantasy_particles, self.expt.pcd_particles_file(it)) storage.dump(rbm, self.expt.rbm_file(it)) if hasattr(trainer, 'avg_rbm'): storage.dump(trainer.avg_rbm, self.expt.avg_rbm_file(it)) storage.dump(time.time() - self.t0, self.expt.time_file(it)) if 'particles' in self.subset and (save or display): fig = rbm_vis.show_particles(rbm, trainer.fantasy_particles, self.expt.dataset, display=display, figtitle='PCD particles ({} updates)'.format(it)) if display: pylab.gcf().canvas.draw() if save: misc.save_image(fig, self.expt.pcd_particles_figure_file(it)) if 'gibbs_chains' in self.subset and (save or display): fig = diagnostics.show_chains(rbm, trainer.fantasy_particles, self.expt.dataset, display=display, figtitle='Gibbs chains (iteration {})'.format(it)) if save: misc.save_image(fig, self.expt.gibbs_chains_figure_file(it)) if 'objective' in self.subset: self.log_prob_tracker.update(rbm, trainer.fantasy_particles) if display: pylab.gcf().canvas.draw()
def plot_scatter(data, dir=None, filename="scatter", color="blue"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() pylab.scatter(data[:, 0], data[:, 1], s=20, marker="o", edgecolors="none", color=color) pylab.xlim(-4, 4) pylab.ylim(-4, 4) pylab.savefig("{}/{}.png".format(dir, filename))
def plot_scatter(data, dir=None, filename="scatter", color="blue"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() pylab.scatter(data[:, 0], data[:, 1], s=20, marker="o", edgecolors="none", color=color) pylab.xlim(-4, 4) pylab.ylim(-4, 4) pylab.savefig("{}/{}".format(dir, filename))
def tile_rgb_images(x, dir=None, filename="x"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() for m in range(100): pylab.subplot(10, 10, m + 1) pylab.imshow(np.clip(x[m], 0, 1), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def visualize_z(z_batch, dir=None): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(20.0, 16.0) pylab.clf() for n in xrange(z_batch.shape[0]): result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], s=40, marker="o", edgecolors='none') pylab.xlabel("z1") pylab.ylabel("z2") pylab.savefig("%s/latent_code.png" % dir)
def plot_rels(data, labels=None, colors=None, outfile="rels", latent=None, alpha=0.8): ns, n = data.shape if labels is None: labels = list(map(str, range(n))) ncol = 5 # ncol = 4 nrow = int(np.ceil(float(n * (n - 1) / 2) / ncol)) #nrow=1 #pylab.rcParams.update({'figure.autolayout': True}) fig, axs = pylab.subplots(nrow, ncol) fig.set_size_inches(5 * ncol, 5 * nrow) #fig.set_canvas(pylab.gcf().canvas) pairs = list(combinations(range(n), 2)) #[:4] pairs = sorted(pairs, key=lambda q: q[0]**2+q[1]**2) # Puts stronger relationships first if colors is not None: colors = (colors - np.min(colors)) / (np.max(colors) - np.min(colors)).clip(1e-7) for ax, pair in zip(axs.flat, pairs): if latent is None: ax.scatter(data[:, pair[0]], data[:, pair[1]], marker='.', edgecolors='none', alpha=alpha) else: # cs = 'rgbcmykrgbcmyk' markers = 'x+.o,<>^^<>,+x.' for j, ind in enumerate(np.unique(latent)): inds = (latent == ind) ax.scatter(data[inds, pair[0]], data[inds, pair[1]], c=colors[inds], cmap=pylab.get_cmap("jet"), marker=markers[j], alpha=0.5, edgecolors='none', vmin=0, vmax=1) ax.set_xlabel(shorten(labels[pair[0]])) ax.set_ylabel(shorten(labels[pair[1]])) for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]: ax.scatter(data[:, 0], data[:, 1], marker='.') pylab.rcParams['font.size'] = 12 #6 pylab.draw() #fig.set_tight_layout(True) fig.tight_layout() for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]: ax.set_visible(False) filename = outfile + '.png' if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) fig.savefig(outfile + '.png') #df') pylab.close('all') return True
def plot_analogy(): dataset_train, dataset_test = chainer.datasets.get_mnist() images_train, labels_train = dataset_train._datasets images_test, labels_test = dataset_test._datasets dataset_indices = np.arange(0, len(images_test)) np.random.shuffle(dataset_indices) model = Model() assert model.load("model.hdf5") # normalize images_train = (images_train - 0.5) * 2 images_test = (images_test - 0.5) * 2 num_analogies = 10 pylab.gray() batch_indices = dataset_indices[:num_analogies] x_batch = images_test[batch_indices] y_batch = labels_test[batch_indices] y_onehot_batch = onehot(y_batch) with chainer.no_backprop_mode() and chainer.using_config("train", False): z_batch = model.encode_x_yz(x_batch)[1].data # plot original image on the left x_batch = (x_batch + 1.0) / 2.0 for m in range(num_analogies): pylab.subplot(num_analogies, 10 + 2, m * 12 + 1) pylab.imshow(x_batch[m].reshape((28, 28)), interpolation="none") pylab.axis("off") all_y = np.identity(10, dtype=np.float32) for m in range(num_analogies): # copy z_batch as many as the number of classes fixed_z = np.repeat(z_batch[m].reshape(1, -1), 10, axis=0) gen_x = model.decode_yz_x(all_y, fixed_z).data gen_x = (gen_x + 1.0) / 2.0 # plot images generated from each label for n in range(10): pylab.subplot(num_analogies, 10 + 2, m * 12 + 3 + n) pylab.imshow(gen_x[n].reshape((28, 28)), interpolation="none") pylab.axis("off") fig = pylab.gcf() fig.set_size_inches(num_analogies, 10) pylab.savefig("analogy.png")
def plot_analogy(): dataset_train, dataset_test = chainer.datasets.get_mnist() images_train, labels_train = dataset_train._datasets images_test, labels_test = dataset_test._datasets dataset_indices = np.arange(0, len(images_test)) np.random.shuffle(dataset_indices) model = Model() assert model.load("model.hdf5") # normalize images_train = (images_train - 0.5) * 2 images_test = (images_test - 0.5) * 2 num_analogies = 10 pylab.gray() batch_indices = dataset_indices[:num_analogies] x_batch = images_test[batch_indices] y_batch = labels_test[batch_indices] y_onehot_batch = onehot(y_batch) with chainer.no_backprop_mode() and chainer.using_config("train", False): z_batch = model.encode_x_yz(x_batch)[1].data # plot original image on the left x_batch = (x_batch + 1.0) / 2.0 for m in range(num_analogies): pylab.subplot(num_analogies, 10 + 2, m * 12 + 1) pylab.imshow(x_batch[m].reshape((28, 28)), interpolation="none") pylab.axis("off") all_y = np.identity(10, dtype=np.float32) for m in range(num_analogies): # copy z_batch as many as the number of classes fixed_z = np.repeat(z_batch[m].reshape(1, -1), 10, axis=0) representation = model.encode_yz_representation(all_y, fixed_z) gen_x = model.decode_representation_x(representation).data gen_x = (gen_x + 1.0) / 2.0 # plot images generated from each label for n in range(10): pylab.subplot(num_analogies, 10 + 2, m * 12 + 3 + n) pylab.imshow(gen_x[n].reshape((28, 28)), interpolation="none") pylab.axis("off") fig = pylab.gcf() fig.set_size_inches(num_analogies, 10) pylab.savefig("analogy.png")
def plot_analogy(): dataset_train, dataset_test = chainer.datasets.get_mnist() images_train, labels_train = dataset_train._datasets images_test, labels_test = dataset_test._datasets dataset_indices = np.arange(0, len(images_test)) np.random.shuffle(dataset_indices) model = Model() assert model.load("model.hdf5") # normalize images_train = (images_train - 0.5) * 2 images_test = (images_test - 0.5) * 2 num_analogies = 10 pylab.gray() batch_indices = dataset_indices[:num_analogies] x_batch = images_test[batch_indices] y_batch = labels_test[batch_indices] y_onehot_batch = onehot(y_batch) with chainer.no_backprop_mode() and chainer.using_config("train", False): z_batch = model.encode_x_z(x_batch).data # plot original image on the left x_batch = (x_batch + 1.0) / 2.0 for m in range(num_analogies): pylab.subplot(num_analogies, 10 + 2, m * 12 + 1) pylab.imshow(x_batch[m].reshape((28, 28)), interpolation="none") pylab.axis("off") all_y = np.identity(10, dtype=np.float32) for m in range(num_analogies): # copy z_batch as many as the number of classes fixed_z = np.repeat(z_batch[m].reshape(1, -1), 10, axis=0) gen_x = model.decode_yz_x(all_y, fixed_z).data gen_x = (gen_x + 1.0) / 2.0 # plot images generated from each label for n in range(10): pylab.subplot(num_analogies, 10 + 2, m * 12 + 3 + n) pylab.imshow(gen_x[n].reshape((28, 28)), interpolation="none") pylab.axis("off") fig = pylab.gcf() fig.set_size_inches(num_analogies, 10) pylab.savefig("analogy.png")
def plot_clusters(): dataset_train, dataset_test = chainer.datasets.get_mnist() images_train, labels_train = dataset_train._datasets images_test, labels_test = dataset_test._datasets dataset_indices = np.arange(0, len(images_test)) np.random.shuffle(dataset_indices) model = Model() assert model.load("model.hdf5") # normalize images_train = (images_train - 0.5) * 2 images_test = (images_test - 0.5) * 2 num_clusters = model.ndim_y num_plots_per_cluster = 11 image_width = 28 image_height = 28 ndim_x = image_width * image_height pylab.gray() with chainer.no_backprop_mode() and chainer.using_config("train", False): # plot cluster head head_y = np.identity(model.ndim_y, dtype=np.float32) zero_z = np.zeros((model.ndim_y, model.ndim_z), dtype=np.float32) head_x = model.decode_yz_x(head_y, zero_z).data head_x = (head_x + 1.0) / 2.0 for n in range(num_clusters): pylab.subplot(num_clusters, num_plots_per_cluster + 2, n * (num_plots_per_cluster + 2) + 1) pylab.imshow(head_x[n].reshape((image_width, image_height)), interpolation="none") pylab.axis("off") # plot elements in cluster counts = [0 for i in range(num_clusters)] indices = np.arange(len(images_test)) np.random.shuffle(indices) batchsize = 500 i = 0 x_batch = np.zeros((batchsize, ndim_x), dtype=np.float32) for n in range(len(images_test) // batchsize): for b in range(batchsize): x_batch[b] = images_test[indices[i]] i += 1 y_batch = model.encode_x_yz(x_batch)[0].data labels = np.argmax(y_batch, axis=1) for m in range(labels.size): cluster = int(labels[m]) counts[cluster] += 1 if counts[cluster] <= num_plots_per_cluster: x = (x_batch[m] + 1.0) / 2.0 pylab.subplot(num_clusters, num_plots_per_cluster + 2, cluster * (num_plots_per_cluster + 2) + 2 + counts[cluster]) pylab.imshow(x.reshape((image_width, image_height)), interpolation="none") pylab.axis("off") fig = pylab.gcf() fig.set_size_inches(num_plots_per_cluster, num_clusters) pylab.savefig("clusters.png")