def plot_x_y_yhat(x, y, y_hat, xsz, ysz, binz=False):
"""Plot x, y and y_hat side by side."""
plt.close("all")
f = plt.figure(figsize=(15, 10.8), dpi=300)
gs = gridspec.GridSpec(1, 3)
if binz:
y_hat = (y_hat > 0.5) * 1.
ims = [x, y, y_hat]
tils = [
"x:" + str(xsz) + "x" + str(xsz),
"y:" + str(ysz) + "x" + str(ysz),
"yhat:" + str(ysz) + "x" + str(ysz)]
for n, ti in zip([0, 1, 2], tils):
f.add_subplot(gs[n])
if n == 0:
plt.imshow(ims[n], cmap=cm.Greys_r)
else:
plt.imshow(ims[n], cmap=cm.Greys_r)
plt.title(ti)
return f
python类GridSpec()的实例源码
def mfi(df):
df['date'] = pd.to_datetime(df.date)
fig = plt.figure(figsize=(16, 9))
gs = GridSpec(3, 1) # 2 rows, 3 columns
fig.suptitle(df['date'][-1:].values[0])
fig.set_label('MFI')
price = fig.add_subplot(gs[:2, 0])
price.plot(df['date'], df['close'], color='blue')
indicator = fig.add_subplot(gs[2, 0], sharex=price)
indicator.plot(df['date'], df['mfi'], c='pink')
indicator.plot(df['date'], [20.]*len(df['date']), c='green')
indicator.plot(df['date'], [80.]*len(df['date']), c='orange')
price.grid(True)
indicator.grid(True)
plt.tight_layout()
plt.show()
def atr(df):
'''
Average True Range
:param df:
:return:
'''
df['date'] = pd.to_datetime(df.date)
fig = plt.figure(figsize=(16, 9))
gs = GridSpec(3, 1) # 2 rows, 3 columns
fig.suptitle(df['date'][-1:].values[0])
fig.set_label('ATR')
price = fig.add_subplot(gs[:2, 0])
price.plot(df['date'], df['close'], color='blue')
indicator = fig.add_subplot(gs[2, 0], sharex=price)
indicator.plot(df['date'], df['atr'], c='pink')
# indicator.plot(df['date'], [20.]*len(df['date']), c='green')
# indicator.plot(df['date'], [80.]*len(df['date']), c='orange')
price.grid(True)
indicator.grid(True)
plt.tight_layout()
plt.show()
def rocr(df):
'''
Average True Range
:param df:
:return:
'''
df['date'] = pd.to_datetime(df.date)
fig = plt.figure(figsize=(16, 9))
gs = GridSpec(3, 1) # 2 rows, 3 columns
fig.suptitle(df['date'][-1:].values[0])
fig.set_label('ATR')
price = fig.add_subplot(gs[:2, 0])
price.plot(df['date'], df['close'], color='blue')
indicator = fig.add_subplot(gs[2, 0], sharex=price)
indicator.plot(df['date'], df['rocr'], c='pink')
# indicator.plot(df['date'], [20.]*len(df['date']), c='green')
# indicator.plot(df['date'], [80.]*len(df['date']), c='orange')
price.grid(True)
indicator.grid(True)
plt.tight_layout()
plt.show()
def plot_x_x_yhat(x, x_hat):
"""Plot x, y and y_hat side by side."""
plt.close("all")
f = plt.figure() # figsize=(15, 10.8), dpi=300
gs = gridspec.GridSpec(1, 2)
ims = [x, x_hat]
tils = [
"xin:" + str(x.shape[0]) + "x" + str(x.shape[1]),
"xout:" + str(x.shape[1]) + "x" + str(x_hat.shape[1])]
for n, ti in zip([0, 1], tils):
f.add_subplot(gs[n])
plt.imshow(ims[n], cmap=cm.Greys_r)
plt.title(ti)
ax = f.gca()
ax.set_axis_off()
return f
def make_split(ratio, gap=0.12):
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.ticker import MaxNLocator
cax = plt.gca()
box = cax.get_position()
xmin, ymin = box.xmin, box.ymin
xmax, ymax = box.xmax, box.ymax
gs = GridSpec(2, 1, height_ratios=[ratio, 1 - ratio], left=xmin, right=xmax, bottom=ymin, top=ymax)
gs.update(hspace=gap)
ax = plt.subplot(gs[0])
plt.setp(ax.get_xticklabels(), visible=False)
bx = plt.subplot(gs[1], sharex=ax)
return ax, bx
def set_plot_layout(self, layout_spec):
rows, columns = layout_spec['dims']
width = 0.025
ratios = [(1.0 - width) / float(columns)] * columns
ratios.append(width)
grid_spec = gridspec.GridSpec(rows, columns + 1, width_ratios=ratios)
for axes in self._axes:
self.delaxes(axes)
self._axes = [self.add_subplot(grid_spec[sub_spec]) for sub_spec in layout_spec['grid']]
if self._colormap_axes is not None:
self.delaxes(self._colormap_axes)
self._colormap_axes = self.add_subplot(grid_spec[:, columns])
self._current_layout = layout_spec
def _create_figure():
# create the figure with four subplots with different size
# - 1st is for the predominant melody and performed notes
# - 2nd is the pitch distribution and note models, it shares the y
# axis with the 1st
# - 3rd is the melodic progression, it shares the x axis with the 1st
# - 4th is for the sections, it is on top the 3rd
fig = plt.figure()
gs = gridspec.GridSpec(2, 2, width_ratios=[6, 1], height_ratios=[4, 1])
ax1 = fig.add_subplot(gs[0]) # pitch and notes
ax2 = fig.add_subplot(gs[1], sharey=ax1) # pitch dist. and note models
ax4 = fig.add_subplot(gs[2]) # sections
ax5 = fig.add_subplot(gs[3]) # makam, tempo, tonic, ahenk annotations
ax3 = plt.twiny(ax4) # melodic progression
ax1.get_shared_x_axes().join(ax1, ax3)
fig.subplots_adjust(hspace=0, wspace=0)
return fig, ax1, ax2, ax3, ax4, ax5
def plot(samples):
width = min(12,int(np.sqrt(len(samples))))
fig = plt.figure(figsize=(width, width))
gs = gridspec.GridSpec(width, width)
gs.update(wspace=0.05, hspace=0.05)
for ind, sample in enumerate(samples):
if ind >= width*width:
break
ax = plt.subplot(gs[ind])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
sample = sample * 0.5 + 0.5
sample = np.transpose(sample, (1, 2, 0))
plt.imshow(sample)
return fig
def subplots(img,row_count,col_count,crop_img):
gs = gridspec.GridSpec(2, 2, width_ratios=[4, 3])
plt.subplot(gs[0])
imshow(plt, img)
plt.subplot(gs[1])
plt.plot(np.array(row_count))
plt.subplot(gs[2])
plt.plot(np.array(col_count))
plt.subplot(gs[3])
plt.imshow(crop_img)
plt.show()
#crops an image from both dark and light background
#works best on a single color background
def get_gridspec(self, figure, nmr_plots):
rows = self.rows
cols = self.cols
if rows is None and cols is None:
return AutoGridLayout(spacings=self.spacings).get_gridspec(figure, nmr_plots)
if rows is None:
rows = int(np.ceil(nmr_plots / cols))
if cols is None:
cols = int(np.ceil(nmr_plots / rows))
if rows * cols < nmr_plots:
cols = int(np.ceil(nmr_plots / rows))
return GridLayoutSpecifier(GridSpec(rows, cols, **self.spacings), figure)
def SavePloat_Voxels(voxels, path, iteration):
voxels = voxels[:8].__ge__(0.5)
fig = plt.figure(figsize=(32, 16))
gs = gridspec.GridSpec(2, 4)
gs.update(wspace=0.05, hspace=0.05)
for i, sample in enumerate(voxels):
x, y, z = sample.nonzero()
ax = plt.subplot(gs[i], projection='3d')
ax.scatter(x, y, z, zdir='z', c='red')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.savefig(path + '/{}.png'.format(str(iteration).zfill(3)), bbox_inches='tight')
plt.close()
with open(path + '/{}.pkl'.format(str(iteration).zfill(3)), "wb") as f:
pickle.dump(voxels, f, protocol=pickle.HIGHEST_PROTOCOL)
def plot_aged_g2( g2_aged, tau=None,timeperframe=1, ylim=None, xlim=None):
''''A plot of g2 calculated from two-time'''
fig = plt.figure(figsize=(8,10))
age_center = list( sorted( g2_aged.keys() ) )
gs = gridspec.GridSpec(len(age_center),1 )
for n,i in enumerate( age_center):
ax = plt.subplot(gs[n])
if tau is None:
gx= np.arange(len(g2_aged[i])) * timeperframe
else:
gx=tau[i]
marker = markers[n]
c = colors[n]
ax.plot( gx,g2_aged[i], '-%s'%marker, c=c, label=r"$age= %.1f s$"%(i*timeperframe))
ax.set_xscale('log')
ax.legend(fontsize='large', loc='best' )
ax.set_xlabel(r"$\tau $ $(s)$", fontsize=18)
ax.set_ylabel("g2")
if ylim is not None:
ax.set_ylim( ylim )
if xlim is not None:
ax.set_ylim( xlim )
#####################################
#get fout-time
def make_axes_from_grid(fig, gs):
"""Generate 2D array of subplot axes from a gridspec
Args:
- fig(matplotlib.figure.Figure): a matplotlib figure handle
- gs(matplotlib.gridspec.GridSpec): the gridspec
Returns:
- list of lists (2D array) of subplot axes
"""
axes = []
(rows, cols) = gs.get_geometry()
for row in range(rows):
axes.append([])
for col in range(cols):
axes[-1].append(fig.add_subplot(gs[row, col]))
return axes
def _create_figure():
fig = pyplot.figure()
gs = gridspec.GridSpec(3, 1, height_ratios=[2, 2, 1], hspace=0.05)
ax2 = fig.add_subplot(gs[1])
ax1 = fig.add_subplot(gs[0], sharex=ax2)
ax1.xaxis.set_label_position('top')
ax1.xaxis.set_tick_params(labeltop='on', labelbottom='off')
pyplot.setp(ax2.get_xticklabels(), visible=False)
ax1.set_xscale('log')
ax2.set_xscale('log')
ax2.set_yscale('log')
ax1.set_xlabel('Number dofs')
ax1.set_ylabel('Number GMRES iterations')
ax2.set_ylabel('CPU time')
ax1.set_ylim(0, None, auto=True)
ax2.set_ylim(0, None, auto=True)
return fig, (ax1, ax2)
def show_labes(image, probs, lables, true_label):
gs = gridspec.GridSpec(1, 3)
ax1 = plt.subplot(gs[1])
x = list(reversed(lables))
y = list(reversed(probs))
colors = ['#edf8fb', '#ccece6', '#99d8c9', '#66c2a4', '#41ae76']
# colors = ['#624ea7', 'g', 'yellow', 'k', 'maroon']
# colors=list(reversed(colors))
width = 0.4 # the width of the bars
ind = np.arange(len(y)) # the x locations for the groups
ax1.barh(ind, y, width, align='center', color=colors)
ax1.set_yticks(ind + width / 2)
ax1.set_yticklabels(x, minor=False)
for i, v in enumerate(y):
ax1.text(v, i, '%5.2f%%' % v, fontsize=14)
plt.title('Probability Output', fontsize=20)
ax2 = plt.subplot(gs[2])
ax2.axis('off')
ax2.imshow(image)
# fig = plt.gcf()
# fig.set_size_inches(8, 6)
plt.title(true_label, fontsize=20)
plt.show()
cnn_vision_caffe.py 文件源码
项目:CNN_UCMerced-LandUse_Caffe
作者: yangxue0827
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def show_labes(image, probs, lables, true_label):
fig = plt.figure()
gs = gridspec.GridSpec(1, 3)
ax1 = plt.subplot(gs[1])
x = list(reversed(lables))
y = list(reversed(probs))
colors = ['#edf8fb', '#ccece6', '#99d8c9', '#66c2a4', '#41ae76']
# colors = ['#624ea7', 'g', 'yellow', 'k', 'maroon']
# colors=list(reversed(colors))
width = 0.4 # the width of the bars
ind = np.arange(len(y)) # the x locations for the groups
ax1.barh(ind, y, width, align='center', color=colors)
ax1.set_yticks(ind + width / 2)
ax1.set_yticklabels(x, minor=False)
for i, v in enumerate(y):
ax1.text(v + 1, i, '%5.2f%%' % v, fontsize=14)
plt.title('Probability Output', fontsize=20)
ax2 = plt.subplot(gs[2])
ax2.axis('off')
ax2.imshow(image)
plt.title(true_label, fontsize=20)
plt.show()
# if true_label != lables[0]:
# unique_filename = uuid.uuid4()
# fig.savefig('predit_worng/' + str(unique_filename) + '.jpg')
def plot_dist(
main_file, mask_file, xlabel, distribution=None, xlabel2=None,
figsize=DINA4_LANDSCAPE):
data = _get_values_inside_a_mask(main_file, mask_file)
fig = plt.Figure(figsize=figsize)
FigureCanvas(fig)
gsp = GridSpec(2, 1)
ax = fig.add_subplot(gsp[0, 0])
sns.distplot(data.astype(np.double), kde=False, bins=100, ax=ax)
ax.set_xlabel(xlabel)
ax = fig.add_subplot(gsp[1, 0])
sns.distplot(np.array(distribution).astype(np.double), ax=ax)
cur_val = np.median(data)
label = "{0!g}".format(cur_val)
plot_vline(cur_val, label, ax=ax)
ax.set_xlabel(xlabel2)
return fig
def show_labes(image,probs,lables,true_label):
gs = gridspec.GridSpec(1, 2,width_ratios=[1,1],height_ratios=[1,1])
ax1 = plt.subplot(gs[0])
x = list(reversed(lables))
y = list(reversed(probs))
colors=['#edf8fb','#b2e2e2','#66c2a4','#2ca25f','#006d2c']
#colors = ['#624ea7', 'g', 'yellow', 'k', 'maroon']
#colors=list(reversed(colors))
width = 0.4 # the width of the bars
ind = np.arange(len(y)) # the x locations for the groups
ax1.barh(ind, y, width, align='center', color=colors)
ax1.set_yticks(ind+width/2)
ax1.set_yticklabels(x, minor=False)
for i, v in enumerate(y):
ax1.text(v, i, '%5.2f%%' %v,fontsize=14)
plt.title('Probability Output',fontsize=20)
ax2 = plt.subplot(gs[1])
ax2.axis('off')
ax2.imshow(image)
# fig = plt.gcf()
# fig.set_size_inches(8, 6)
plt.title(true_label,fontsize=20)
plt.show()
def plot_images( args, x_sample, dir, file_name, size_x=3, size_y=3):
fig = plt.figure(figsize=(size_x, size_y))
# fig = plt.figure(1)
gs = gridspec.GridSpec(size_x, size_y)
gs.update(wspace=0.05, hspace=0.05)
for i, sample in enumerate(x_sample):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.imshow(sample.reshape(args.input_size[1], args.input_size[2]), cmap='Greys_r')
plt.savefig(dir + file_name + '.png', bbox_inches='tight')
plt.close(fig)
#=======================================================================================================================
def plot_real( args, x_sample, dir, size_x=3, size_y=3):
x_sample = x_sample.data.cpu().numpy()[:size_x*size_y]
fig = plt.figure(figsize=(size_x, size_y))
gs = gridspec.GridSpec(size_x, size_y)
gs.update(wspace=0.05, hspace=0.05)
for i, sample in enumerate(x_sample):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.imshow(sample.reshape(args.input_size[1], args.input_size[2]), cmap='Greys_r')
plt.savefig(dir + 'real.png', bbox_inches='tight')
plt.close(fig)
#=======================================================================================================================
def plot_reconstruction( args, samples, c, dir , size_x=3, size_y=3):
samples = samples.data.cpu().numpy()[:size_x * size_y]
fig = plt.figure(figsize=(size_x, size_y))
gs = gridspec.GridSpec(size_x, size_y)
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(args.input_size[1], args.input_size[2]), cmap='Greys_r')
if not os.path.exists(dir + 'reconstruction/'):
os.makedirs(dir + 'reconstruction/')
plt.savefig(dir + 'reconstruction/{}.png'.format(str(c).zfill(3)), bbox_inches='tight')
plt.close(fig)
#=======================================================================================================================
def plot_generation( args, samples_mean, dir , size_x=3, size_y=3):
# decode
samples = samples_mean.data.cpu().numpy()[:size_x*size_y]
fig = plt.figure(figsize=(size_x, size_y))
gs = gridspec.GridSpec(size_x, size_y)
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(args.input_size[1], args.input_size[2]), cmap='Greys_r')
plt.savefig(dir + 'generation.png', bbox_inches='tight')
plt.close(fig)
#=======================================================================================================================
def plot_int_buf_delay():
fig = plt.figure(figsize=(7.5, 5.225))
gs = gridspec.GridSpec(2, 1, height_ratios=[1, 1])
ax0 = fig.add_subplot(gs[0])
plot_intercepting_path_delays(ax0, shared=False)
x_axis = list(range(1, 7))
labels = ['I (l)', 'III (l)', 'IV (l)', 'I (b)', 'III (b)', 'IV (b)']
plt.xticks(x_axis, labels)
plt.ylabel('Delay, s')
ax1 = fig.add_subplot(gs[1])
plot_intercepting_path_delays(ax1, shared=True)
labels = ['V (l)', 'VII (l)', 'VIII (l)', 'V (b)', 'VII(b)', 'VIII (b)']
plt.xticks(x_axis, labels)
plt.xlabel('Data sets')
plt.ylabel('Delay, s')
plt.show()
def grid_plot2d(Q, P, data_loader, params):
Q.eval()
P.eval()
cuda = params['cuda']
z1 = Variable(torch.from_numpy(np.arange(-10, 10, 1.5).astype('float32')))
z2 = Variable(torch.from_numpy(np.arange(-10, 10, 1.5).astype('float32')))
if cuda:
z1, z2 = z1.cuda(), z2.cuda()
nx, ny = len(z1), len(z2)
plt.subplot()
gs = gridspec.GridSpec(nx, ny, hspace=0.05, wspace=0.05)
for i, g in enumerate(gs):
z = torch.cat((z1[i / ny], z2[i % nx])).resize(1, 2)
x = P(z)
ax = plt.subplot(g)
img = np.array(x.data.tolist()).reshape(28, 28)
ax.imshow(img, )
ax.set_xticks([])
ax.set_yticks([])
ax.set_aspect('auto')
def plot(samples, size, name):
size = int(size)
fig = plt.figure(figsize=(4, 4))
gs = gridspec.GridSpec(4, 4)
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(size, size), cmap='Greys_r')
plt.savefig('out/{}.png'.format(name), bbox_inches='tight')
plt.close(fig)
def plot(samples, size, name):
size = int(size)
fig = plt.figure(figsize=(4, 4))
gs = gridspec.GridSpec(4, 4)
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(size, size), cmap='Greys_r')
plt.savefig('out/{}.png'.format(name), bbox_inches='tight')
plt.close(fig)
def plot(samples, size, name):
size = int(size)
fig = plt.figure(figsize=(4, 4))
gs = gridspec.GridSpec(4, 4)
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(size, size), cmap='Greys_r')
plt.savefig('out/{}.png'.format(name), bbox_inches='tight')
plt.close(fig)
CAE_pytorch.py 文件源码
项目:Contractive_Autoencoder_in_Pytorch
作者: avijit9
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def samples_write(self, x, epoch):
_, samples = self.forward(x)
#pdb.set_trace()
samples = samples.data.cpu().numpy()[:16]
fig = plt.figure(figsize=(4, 4))
gs = gridspec.GridSpec(4, 4)
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')
if not os.path.exists('out/'):
os.makedirs('out/')
plt.savefig('out/{}.png'.format(str(epoch).zfill(3)), bbox_inches='tight')
#self.c += 1
plt.close(fig)
def plot_x_y_yhat(x, y, y_hat, xsz, ysz, binz=False):
"""Plot x, y and y_hat side by side."""
plt.close("all")
f = plt.figure(figsize=(15, 10.8), dpi=300)
gs = gridspec.GridSpec(1, 3)
if binz:
y_hat = (y_hat > 0.5) * 1.
ims = [x, y, y_hat]
tils = [
"x:" + str(xsz) + "x" + str(xsz),
"y:" + str(ysz) + "x" + str(ysz),
"yhat:" + str(ysz) + "x" + str(ysz)]
for n, ti in zip([0, 1, 2], tils):
f.add_subplot(gs[n])
if n == 0:
plt.imshow(ims[n], cmap=cm.Greys_r)
else:
plt.imshow(ims[n], cmap=cm.Greys_r)
plt.title(ti)
return f