def generate_image_grid(sess, op):
"""
Generates a grid of images by passing a set of numbers to the decoder and getting its output.
:param sess: Tensorflow Session required to get the decoder output
:param op: Operation that needs to be called inorder to get the decoder output
:return: None, displays a matplotlib window with all the merged images.
"""
x_points = np.arange(0, 1, 1.5).astype(np.float32)
y_points = np.arange(0, 1, 1.5).astype(np.float32)
nx, ny = len(x_points), len(y_points)
plt.subplot()
gs = gridspec.GridSpec(nx, ny, hspace=0.05, wspace=0.05)
for i, g in enumerate(gs):
z = np.concatenate(([x_points[int(i / ny)]], [y_points[int(i % nx)]]))
z = np.reshape(z, (1, 2))
x = sess.run(op, feed_dict={decoder_input: z})
ax = plt.subplot(g)
img = np.array(x.tolist()).reshape(28, 28)
ax.imshow(img, cmap='gray')
ax.set_xticks([])
ax.set_yticks([])
ax.set_aspect('auto')
plt.show()
python类GridSpec()的实例源码
adversarial_autoencoder.py 文件源码
项目:Adversarial_Autoencoder
作者: Naresh1318
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def generate_image_grid(sess, op):
"""
Generates a grid of images by passing a set of numbers to the decoder and getting its output.
:param sess: Tensorflow Session required to get the decoder output
:param op: Operation that needs to be called inorder to get the decoder output
:return: None, displays a matplotlib window with all the merged images.
"""
x_points = np.arange(-10, 10, 1.5).astype(np.float32)
y_points = np.arange(-10, 10, 1.5).astype(np.float32)
nx, ny = len(x_points), len(y_points)
plt.subplot()
gs = gridspec.GridSpec(nx, ny, hspace=0.05, wspace=0.05)
for i, g in enumerate(gs):
z = np.concatenate(([x_points[int(i / ny)]], [y_points[int(i % nx)]]))
z = np.reshape(z, (1, 2))
x = sess.run(op, feed_dict={decoder_input: z})
ax = plt.subplot(g)
img = np.array(x.tolist()).reshape(28, 28)
ax.imshow(img, cmap='gray')
ax.set_xticks([])
ax.set_yticks([])
ax.set_aspect('auto')
plt.show()
def plot_gendata():
"""Plot artificial data with n_confounders=[0, 1, 6, 12].
This program is used to check artificial data.
"""
n_samples = 200
rng = np.random.RandomState(0)
plt.figure(figsize=(10, 10))
gs = gridspec.GridSpec(2, 2)
# ---- Loop over the number of confonders ----
for i, n_confounders in enumerate([0, 1, 6, 12]):
# ---- Generate samples ----
xs = gendata_latents(n_confounders, n_samples, rng)
# ---- Plot samples ----
ax = plt.subplot(gs[i])
ax.scatter(xs[:, 0], xs[:, 1])
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
ax.set_title('n_confounders=%d' % n_confounders)
return
def plot_pred_vs_image(img,preds_df,out_name):
# function to plot predictions vs image
f, axarr = plt.subplots(2, 1)
plt.suptitle("ResNet50- PreTrained on ImageNet")
axarr[0].imshow(img)
sns.set_style("whitegrid")
pl = sns.barplot(data = preds_df, x='Score', y='Species')
axarr[1] = sns.barplot(data = preds_df, x='Score', y='Species',)
axarr[0].autoscale(enable=False)
axarr[0].get_xaxis().set_ticks([])
axarr[0].get_yaxis().set_ticks([])
axarr[1].autoscale(enable=False)
gs = gridspec.GridSpec(2,1, width_ratios=[1],height_ratios=[1,0.1])
plt.tight_layout()
plt.savefig(out_name + '.png')
#########################
# Models
#########################
# load model
def bot_demo():
steps = 100
mc_simulations = 1
ssm = BearingsOnlyTracking(dt=0.1)
x, z = ssm.simulate(steps, mc_sims=mc_simulations)
# plt.plot(x[0, ...], color='b', alpha=0.15, label='state trajectory')
# plt.plot(z[0, ...], color='k', alpha=0.25, ls='None', marker='.', label='measurements')
plt.figure()
g = gridspec.GridSpec(4, 1)
plt.subplot(g[:2, 0])
for i in range(mc_simulations):
plt.plot(x[0, :, i], x[2, :, i], alpha=0.85, color='b')
plt.subplot(g[2, 0])
plt.plot(x[0, :, 0])
plt.subplot(g[3, 0])
plt.plot(x[2, :, 0])
plt.show()
def _get_axes(self,fig):
# TODO is attaching these to the figure a good idea? why not save them
# here and reuse them if we recognize the figure being passed in
sz = self._fig_sz
if hasattr(fig,'_feature_ax') and hasattr(fig,'_stateseq_axs'):
return fig._feature_ax, fig._stateseq_axs
else:
if len(self.states_list) <= 2:
gs = GridSpec(sz+len(self.states_list),1)
feature_ax = plt.subplot(gs[:sz,:])
stateseq_axs = [plt.subplot(gs[sz+idx]) for idx in range(len(self.states_list))]
else:
gs = GridSpec(1,2)
sgs = GridSpecFromSubplotSpec(len(self.states_list),1,subplot_spec=gs[1])
feature_ax = plt.subplot(gs[0])
stateseq_axs = [plt.subplot(sgs[idx]) for idx in range(len(self.states_list))]
for ax in stateseq_axs:
ax.grid('off')
fig._feature_ax, fig._stateseq_axs = feature_ax, stateseq_axs
return feature_ax, stateseq_axs
def plot_main(cds_start,cds_end,psites_array,orf_tstart,orf_tstop,outname):
"""
the main plot function
"""
plt.figure(figsize=(8,4))
if cds_start is not None:
gs = gridspec.GridSpec(3,1,height_ratios=[10,1,1],hspace=0.6,left=0.2,right=0.95)
else:
gs = gridspec.GridSpec(2,1,height_ratios=[11,1],hspace=0.6,left=0.2,right=0.95)
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
plot_ORF(ax1,psites_array,orf_tstart)
plot_annotation(ax2,psites_array.size,orf_tstart,orf_tstop,"Predicted","#3994FF")
if cds_start is not None:
ax3 = plt.subplot(gs[2])
plot_annotation(ax3,psites_array.size,cds_start,cds_end,"Annotated","#006DD5")
# plt.tight_layout()
plt.savefig(outname + ".pdf")
def plot_alpha(alpha, x, y):
f, (a0, a1) = plt.subplots(2)
gs = grd.GridSpec(2,1, wspace=0.01) #, height_ratios=[1, 4])
a0 = plt.subplot(gs[0])
a0.matshow(x.T, cmap=plt.cm.Greys_r) #, aspect='auto')
probs = np.zeros_like(alpha)
for i in range(len(alpha)):
probs[i] = np.convolve(
alpha[i], np.ones((2,))/2., mode='same')
a1.matshow(alpha, interpolation='none', aspect='auto')
xticks = np.argmax(probs, axis=1)
a1.set_xticks(xticks)
a1.set_xticklabels(y, fontsize=16)
a1.grid(which='both')
plt.subplots_adjust(top=None, bottom=None, wspace=0.05, hspace=0.05)
plt.show()
def make_figure():
gs = gridspec.GridSpec(5, 1,
height_ratios=[3, 1, 2, 3, 1],
hspace=0)
data, Z, D = get_random_data(100, 0)
order = leaves_list(Z)
runtime, opt_Z = run_polo(Z, D)
opt_order = leaves_list(opt_Z)
fig = plt.figure(figsize=(5,5))
axd1 = fig.add_subplot(gs[0,0])
axd1.set_title("Random numbers, clustered using Ward's criterion, default linear ordering.", fontsize=9)
dendrogram(Z, ax=axd1, link_color_func=lambda k: 'k')
axd1.set_xticklabels(data[order].reshape(-1))
axd1.set_xticks([])
axd1.set_yticks([])
axh1 = fig.add_subplot(gs[1,0])
axh1.matshow(data[order].reshape((1,-1)), aspect='auto', cmap='RdBu', vmin=0, vmax=10000)
axh1.set_xticks([])
axh1.set_yticks([])
axd2 = fig.add_subplot(gs[3,0])
axd2.set_title("The same hierarchical clustering, arranged for optimal linear ordering.", fontsize=9)
dendrogram(opt_Z, ax=axd2, link_color_func=lambda k: 'k')
axd2.set_xticklabels(data[opt_order].reshape(-1))
axd2.set_xticks([])
axd2.set_yticks([])
axh2 = fig.add_subplot(gs[4,0])
axh2.matshow(data[opt_order].reshape((1,-1)), aspect='auto', cmap='RdBu', vmin=0, vmax=10000)
axh2.set_xticks([])
axh2.set_yticks([])
fig.savefig('data/demo.png', dpi=130)
def plot_images_and_clusters(images, clusters, epoch, save_path, ncol=10):
'''use multiple images'''
fig = plt.figure()#facecolor='black')
images = np.squeeze(images, -1)
nrow = int(np.ceil(images.shape[0] / float(ncol)))
gs = gridspec.GridSpec(nrow, ncol,
width_ratios=[1]*ncol, height_ratios=[1]*nrow,
# wspace=0.01, hspace=0.001,
# top=0.95, bottom=0.05,
# left=0.05, right=0.95
)
gs.update(wspace=0, hspace=0)
n = 0
for i in range(10):
images_i = images[clusters==i, :, :]
if images_i.shape[0] == 0:
continue
for j in range(images_i.shape[0]):
ax = plt.subplot(gs[n])
n += 1
plt.imshow(images_i[j,:], cmap='gray')
plt.axis('off')
ax.set_aspect('auto')
plt.savefig(os.path.join(save_path, 'plot_gmvae_epoch_{}.png'.format(epoch)), dpi=fig.dpi)
def plot1D_mat(a, b, M, title=''):
""" Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source distribution
b : np.array, shape (nb,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot
"""
na, nb = M.shape
gs = gridspec.GridSpec(3, 3)
xa = np.arange(na)
xb = np.arange(nb)
ax1 = pl.subplot(gs[0, 1:])
pl.plot(xb, b, 'r', label='Target distribution')
pl.yticks(())
pl.title(title)
ax2 = pl.subplot(gs[1:, 0])
pl.plot(a, xa, 'b', label='Source distribution')
pl.gca().invert_xaxis()
pl.gca().invert_yaxis()
pl.xticks(())
pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
pl.imshow(M, interpolation='nearest')
pl.axis('off')
pl.xlim((0, nb))
pl.tight_layout()
pl.subplots_adjust(wspace=0., hspace=0.2)
def plot_concept_list(constellation, fig=None, **kwargs):
"""Vertically stack a constellation's concept plots (uses `plot_concept`).
Examples:
>>> big_mip = pyphi.compute.big_mip(sub)
>>> plot_concept_list(big_mip.unpartitioned_constellation,
title_fmt='MP', state_fmt='1')
>>> matplotlib.pyplot.show()
Args:
constellation (list(pyphi.models.Concept)): A list of concepts to plot.
Keyword args:
fig (matplotlib.Figure): A figure on which to plot. If *None*, a new
figure is created and used. Default *None*.
Any unmatched kwargs are passed to `plot_concept`.
"""
DEFAULT_WIDTH = 8 # in inches
DEFAULT_CONCEPT_HEIGHT = 1.75 # in inches
n_concepts = len(constellation)
if fig is None:
fig = plt.figure(1, (DEFAULT_WIDTH, DEFAULT_CONCEPT_HEIGHT * n_concepts))
gs = gridspec.GridSpec(n_concepts, 1)
for concept_idx in range(n_concepts):
plot_concept(constellation[concept_idx],
fig=fig,
subplot_spec=gs[concept_idx, 0],
**kwargs)
fig.tight_layout()
def _plot(samples):
fig = plt.figure(figsize=(10, 10))
gs = gridspec.GridSpec(10, 10)
gs.update(wspace=0.05, hspace=0.05)
for i, sample in enumerate(samples):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.imshow(sample.reshape(28, 28), cmap='Greys_r')
return fig
def __enter__(self):
if not self.skip:
self.fig = plt.figure(figsize=self.figsize,
dpi=self.dpi,
**self.kwargs)
self.fig.npl_gs = gridspec.GridSpec(nrows=self.nrows,
ncols=self.ncols)
self.ax = np.array([self.fig.add_subplot(ss) for ss in self.fig.npl_gs])
# self.fig, self.ax = plt.subplots(nrows=self.nrows,
# ncols=self.ncols,
# figsize=self.figsize,
# tight_layout=self.tight_layout,
# dpi=self.dpi,
# **self.kwargs)
if len(self.ax) == 1:
self.ax = self.ax[0]
if self.tight_layout:
self.fig.npl_gs.tight_layout(self.fig)
# gs1.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
if self.fig != plt.gcf():
self.clear()
raise RuntimeError('Figure does not match active mpl figure')
return self.fig, self.ax
return -1, -1
def rastercountplot(spiketrain, nbins=50, **kwargs):
fig = plt.figure(figsize=(14, 6))
gs = gridspec.GridSpec(2, 1, hspace=0.01, height_ratios=[0.2,0.8])
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
color = kwargs.get('color', None)
if color is None:
color = '0.4'
ds = (spiketrain.support.stop - spiketrain.support.start)/nbins
flattened = spiketrain.bin(ds=ds).flatten()
steps = np.squeeze(flattened.data)
stepsx = np.linspace(spiketrain.support.start, spiketrain.support.stop, num=flattened.n_bins)
# ax1.plot(stepsx, steps, drawstyle='steps-mid', color='none');
ax1.set_ylim([-0.5, np.max(steps)+1])
rasterplot(spiketrain, ax=ax2, **kwargs)
utils.clear_left_right(ax1)
utils.clear_top_bottom(ax1)
utils.clear_top(ax2)
ax1.fill_between(stepsx, steps, step='mid', color=color)
utils.sync_xlims(ax1, ax2)
return ax1, ax2
def newfig(width):
plt.clf()
fig = plt.figure(figsize=figsize(width))
gs = gridspec.GridSpec(2, 2,
width_ratios=[1,4],
height_ratios=[4,1]
)
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[3])
return fig, (ax1, ax2, ax3)
def __init__(self, gridspec, figure, positions=None):
"""Create a grid layout specifier using the given gridspec and the given figure.
Args:
gridspec (GridSpec): the gridspec to use
figure (Figure): the figure to generate subplots for
positions (:class:`list`): if given, a list with grid spec indices for every requested axis
can be logical indices or (x, y) coordinate indices (choose one and stick with it).
"""
self.gridspec = gridspec
self.figure = figure
self.positions = positions
def get_gridspec(self, figure, nmr_plots):
rows, cols = self._get_square_size(nmr_plots)
return GridLayoutSpecifier(GridSpec(rows, cols, **self.spacings), figure)
def get_gridspec(self, figure, nmr_plots):
rows, columns, positions = self._get_size_and_position(nmr_plots)
return GridLayoutSpecifier(GridSpec(rows, columns, **self.spacings), figure, positions=positions)
def get_gridspec(self, figure, nmr_plots):
return GridLayoutSpecifier(GridSpec(nmr_plots, 1, **self.spacings), figure)