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)
python类clf()的实例源码
def _auto_plots(self,mode,filebasename,figdir,plotargs):
"""Generate standard plots and write png and and pdf. Chooses filename and plot title."""
import pylab
try:
os.makedirs(figdir)
except OSError,err:
if err.errno != errno.EEXIST:
raise
def figs(*args):
return os.path.join(figdir,*args)
modefilebasename = filebasename + self._suffix[mode]
_plotargs = plotargs.copy() # need a copy because of changing 'title'
if plotargs.get('title') is None: # None --> set automatic title
_plotargs['title'] = self._title[mode]+' '+self.legend
pylab.clf()
self.plot(**_plotargs)
pylab.savefig(figs(modefilebasename + '.png')) # png
pylab.savefig(figs(modefilebasename + '.pdf')) # pdf
print "--- Plotted %(modefilebasename)r (png,pdf)." % vars()
def plot_coverage(db,use_blacklist=True):
"""Plot the total covrage of the unbiased histogram.
>>> db = setup(pmfonly=True)
>>> db.add_metadata()
>>> plot_coverage(db)
Simple hard-coded plotting routine. Adds two dots for the end
points and focuses on the interesting region.
db pmfonly db
use_blacklist True: filter all files that appear in the blacklist [default]
"""
from pylab import clf,plot,xlim,ylim,title
if use_blacklist:
print "Excluding anything listed in the blacklist (i.e. restricting to __meta__)"
selection = db.selection("SELECT * FROM __data__")
else:
selection = db
selection.plot(mode="reldev")
#title(r'Umbrella sampling coverage: ${N}/{\langle{N}\rangle} - 1$')
make_canonical_plot()
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
# Receptive Fields Summary
try:
W = layer.W
except:
W = layer
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fig = mpl.figure(figOffset); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,np.shape(fields)[0]):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
try:
W = layer.output
except:
W = layer
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
# Receptive Fields Summary
W = layer.W
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
fieldsN = min(fields.shape[0],maxFields)
perRow = int(math.floor(math.sqrt(fieldsN)))
perColumn = int(math.ceil(fieldsN/float(perRow)))
fig = mpl.figure(figName); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,fieldsN):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
W = layer.output
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
def edgeplot(self, TT, ps):
for ei,X in enumerate(self.edges):
(i, j) = X[:2]
Ta = TT[i]
Tb = TT[j]
plt.clf()
if len(Ta) > 1000:
nbins = 101
ra = np.hstack((Ta.ra, Tb.ra))
dec = np.hstack((Ta.dec, Tb.dec))
H,xe,ye = np.histogram2d(ra, dec, bins=nbins)
(matchRA, matchDec, dr,dd) = self.edge_matches(ei, goodonly=True)
G,xe,ye = np.histogram2d(matchRA, matchDec, bins=(xe,ye))
assert(G.shape == H.shape)
img = antigray(H / H.max())
img[G>0,:] = matplotlib.cm.hot(G[G>0] / H[G>0])
ax = setRadecAxes(xe[0], xe[-1], ye[0], ye[-1])
plt.imshow(img, extent=(min(xe), max(xe), min(ye), max(ye)),
aspect='auto', origin='lower', interpolation='nearest')
plt.axis(ax)
else:
self.plotallstars([Ta,Tb])
self.plotmatchedstars(ei)
plt.xlabel('RA (deg)')
plt.ylabel('Dec (deg)')
ps.savefig()
# one plot per edge
def quiveroffsets(self, TT, apply=False):
plt.clf()
self.plotallstars(TT)
self.plotallmatches()
for ei in range(len(self.edges)):
(matchRA, matchDec, dr, dd) = self.get_edge_dradec_deg(ei, corrected=apply, goodonly=True)
scale = 100.
plt.plot(np.vstack((matchRA, matchRA + dr*scale)),
np.vstack((matchDec, matchDec + dd*scale)),
'r-', alpha=0.5)
plt.xlabel('RA (deg)')
plt.ylabel('Dec (deg)')
# rad in arcsec
def hsvoffsets(self, TT, rad, apply=False):
print 'hsv offsets plot'
plt.clf()
for ix,X in enumerate(self.edges):
X = self.get_edge_dradec_arcsec(ix, corrected=apply, goodonly=True)
(matchRA, matchDec, dra, ddec) = X
print 'matchRA,Dec:', len(matchRA), len(matchDec)
print 'dra,dec:', len(dra), len(ddec)
for ra,dec,dr,dd in zip(matchRA, matchDec, dra, ddec):
angle = arctan2(dd, dr) / (2.*pi)
angle = fmod(angle + 1, 1.)
mag = hypot(dd, dr)
mag = min(1, mag/(0.5*rad))
rgb = colorsys.hsv_to_rgb(angle, mag, 0.5)
plt.plot([ra], [dec], '.', color=rgb, alpha=0.5)
# legend in top-right corner.
ax=plt.axis()
xlo,xhi = plt.gca().get_xlim()
ylo,yhi = plt.gca().get_ylim()
# fraction
keycx = xlo + 0.90 * (xhi-xlo)
keycy = ylo + 0.90 * (yhi-ylo)
keyrx = 0.1 * (xhi-xlo) / 1.4 # HACK
keyry = 0.1 * (yhi-ylo)
nrings = 5
for i,(rx,ry) in enumerate(zip(np.linspace(0, keyrx, nrings), np.linspace(0, keyry, nrings))):
nspokes = ceil(i / float(nrings-1) * 30)
angles = np.linspace(0, 2.*pi, nspokes, endpoint=False)
for a in angles:
rgb = colorsys.hsv_to_rgb(a/(2.*pi), float(i)/(nrings-1), 0.5)
plt.plot([keycx + rx*sin(a)], [keycy + ry*cos(a)], '.', color=rgb, alpha=1.)
plt.axis(ax)
plt.xlabel('RA (deg)')
plt.ylabel('Dec (deg)')
def magmagplot(self, TT, magcol, filtname, weighted=True):
plt.clf()
m1 = []
m2 = []
ww = []
for ei in range(self.nedges()):
i,j = self.edge_ij(ei)
I,J = self.edge_IJ(ei)
Ti = TT[i][I]
Tj = TT[j][J]
mag1 = Ti.get(magcol)
mag2 = Tj.get(magcol)
weights = self.get_edge_all_weights(ei)
K = (mag1 < 50) * (mag2 < 50)
m1.append(mag1[K])
m2.append(mag2[K])
ww.append(weights[K])
m1 = np.hstack(m1)
m2 = np.hstack(m2)
ww = np.hstack(ww)
if weighted:
loghist(m1, m2, weights=ww)
else:
loghist(m1, m2)
plt.xlabel('%s (mag)' % filtname)
plt.ylabel('%s (mag)' % filtname)
return ww
def plotaffinegrid(affines, exag=1e3, affineOnly=True, R=0.025, tpre='', bboxes=None):
import pylab as plt
NR = 3
NC = int(ceil(len(affines)/3.))
#R = 0.025 # 1.5 arcmin
#for (exag,affonly) in [(1e2, False), (1e3, True), (1e4, True)]:
plt.clf()
for i,aff in enumerate(affines):
plt.subplot(NR, NC, i+1)
dl = aff.refdec - R
dh = aff.refdec + R
rl = aff.refra - R / aff.rascale
rh = aff.refra + R / aff.rascale
RR,DD = np.meshgrid(np.linspace(rl, rh, 11),
np.linspace(dl, dh, 11))
plotaffine(aff, RR.ravel(), DD.ravel(), exag=exag, affineOnly=affineOnly,
doclf=False,
units='dots', width=2, headwidth=2.5, headlength=3, headaxislength=3)
if bboxes is not None:
for bb in bboxes:
plt.plot(*bb, linestyle='-', color='0.5')
plt.plot(*bboxes[i], linestyle='-', color='k')
setRadecAxes(rl,rh,dl,dh)
plt.xlabel('')
plt.ylabel('')
plt.xticks([])
plt.yticks([])
plt.title('field %i' % (i+1))
plt.subplots_adjust(left=0.05, right=0.95, wspace=0.1)
if affineOnly:
tt = tpre + 'Affine part of transformations'
else:
tt = tpre + 'Transformations'
plt.suptitle(tt + ' (x %g)' % exag)
def plotfitquality(H, xe, ye, A):
'''
H,xe,ye from plotalignment()
'''
import pylab as plt
xe /= 1000.
ye /= 1000.
xx = (xe[:-1] + xe[1:])/2.
yy = (ye[:-1] + ye[1:])/2.
XX,YY = np.meshgrid(xx, yy)
XX = XX.ravel()
YY = YY.ravel()
XY = np.vstack((XX,YY)).T
Mdist = np.sqrt(mahalanobis_distsq(XY, A.mu, A.C))
assert(len(H.ravel()) == len(Mdist))
mod = A.getModel(XX, YY)
R2 = XX**2 + YY**2
mod[R2 > (A.match.rad)**2] = 0.
mod *= (H.sum() / mod.sum())
plt.clf()
rng = (0, 7)
plt.hist(Mdist, 100, weights=H.ravel(), histtype='step', color='b', label='data', range=rng)
plt.hist(Mdist, 100, weights=mod, histtype='step', color='r', label='model', range=rng)
plt.xlabel('| Chi |')
plt.ylabel('Number of matches')
plt.title('Gaussian peak fit quality')
plt.legend(loc='upper right')
def plotalignment(A, nbins=200, M=None, rng=None, doclf=True, docolorbar=True,
docutcircle=True, docontours=True, dologhist=False,
doaxlines=False, imshowargs={}):
import pylab as plt
from astrometry.util.plotutils import plothist, loghist
if doclf:
plt.clf()
if M is None:
M = A.match
if dologhist:
f = loghist
else:
f = plothist
H,xe,ye = f(M.dra_arcsec*1000., M.ddec_arcsec*1000., nbins,
range=rng, doclf=doclf, docolorbar=docolorbar,
imshowargs=imshowargs)
ax = plt.axis()
if A is not None:
# The EM fit is based on a subset of the matches;
# draw the subset cut circle.
if docutcircle:
angle = np.linspace(0, 2.*pi, 360)
plt.plot((A.cutcenter[0] + A.cutrange * np.cos(angle))*1000.,
(A.cutcenter[1] + A.cutrange * np.sin(angle))*1000., 'r-')
if docontours:
for i,c in enumerate(['b','c','g']*2):
if i == A.ngauss:
break
for nsig in [1,2]:
XY = A.getContours(nsig, c=i)
if XY is None:
break
X,Y = XY
plt.plot(X*1000., Y*1000., '-', color=c)#, alpha=0.5)
if doaxlines:
plt.axhline(0., color='b', alpha=0.5)
plt.axvline(0., color='b', alpha=0.5)
plt.axis(ax)
plt.xlabel('dRA (mas)')
plt.ylabel('dDec (mas)')
return H,xe,ye
def histlog10(x, **kwargs):
import pylab as plt
I = (x > 0)
L = np.log10(x[I])
plt.clf()
plt.hist(L, **kwargs)
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 plot_episode_reward():
pylab.clf()
sns.set_context("poster")
pylab.plot(0, 0)
episodes = [0]
scores = [0]
for n in xrange(len(csv_episode)):
params = csv_episode[n]
episodes.append(params[0])
scores.append(params[1])
pylab.plot(episodes, scores, sns.xkcd_rgb["windows blue"], lw=2)
pylab.xlabel("episodes")
pylab.ylabel("score")
pylab.savefig("%s/episode_reward.png" % args.plot_dir)
def plot_training_episode_highscore():
pylab.clf()
sns.set_context("poster")
pylab.plot(0, 0)
episodes = [0]
highscore = [0]
for n in xrange(len(csv_training_highscore)):
params = csv_training_highscore[n]
episodes.append(params[0])
highscore.append(params[1])
pylab.plot(episodes, highscore, sns.xkcd_rgb["windows blue"], lw=2)
pylab.xlabel("episodes")
pylab.ylabel("highscore")
pylab.savefig("%s/training_episode_highscore.png" % args.plot_dir)
def plot_trajectories(self):
pylab.clf()
pylab.rc('text', usetex=True)
pylab.rc('font', size=18)
pylab.subplot(121)
self.plot_com()
pylab.subplot(122)
self.plot_zmp()
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()