def plot_density_map(x, y, xbins, ybins, Nlevels=4, cbar=True, weights=None):
Z = np.histogram2d(x, y, bins=(xbins, ybins), weights=weights)[0].astype(float).T
# central values
lt = get_centers_from_bins(xbins)
lm = get_centers_from_bins(ybins)
cX, cY = np.meshgrid(lt, lm)
X, Y = np.meshgrid(xbins, ybins)
im = plt.pcolor(X, Y, Z, cmap=plt.cm.Blues)
plt.contour(cX, cY, Z, levels=nice_levels(Z, Nlevels), cmap=plt.cm.Greys_r)
if cbar:
cb = plt.colorbar(im)
else:
cb = None
plt.xlim(xbins[0], xbins[-1])
plt.ylim(ybins[0], ybins[-1])
try:
plt.tight_layout()
except Exception as e:
print(e)
return plt.gca(), cb
python类colorbar()的实例源码
def twoDimensionalScatter(title, title_x, title_y,
x, y,
lim_x = None, lim_y = None,
color = 'b', size = 20, alpha=None):
"""
Create a two-dimensional scatter plot.
INPUTS
"""
pylab.figure()
pylab.scatter(x, y, c=color, s=size, alpha=alpha, edgecolors='none')
pylab.xlabel(title_x)
pylab.ylabel(title_y)
pylab.title(title)
if type(color) is not str:
pylab.colorbar()
if lim_x:
pylab.xlim(lim_x[0], lim_x[1])
if lim_y:
pylab.ylim(lim_y[0], lim_y[1])
############################################################
def plot(self,**kwargs):
"""plot landscape (kwargs are passed on to imshow()
Use interpolation='bilinear' or 'bicubic' for a smooth
surface. Default is 'nearest', which shows exact bin
boundaries.
"""
import pylab
kwargs.setdefault('interpolation','nearest')
pylab.clf()
pylab.xlabel('x')
pylab.ylabel('y')
pylab.imshow(self.pmf_masked.T,**kwargs)
pylab.colorbar()
pylab.show()
def add_colorbar(ax, im, side='right', size='5%', pad=0.1, **kwds):
"""
Add colorbar to the axes *ax* with colors corresponding to the
color mappable object *im*. Place the colorbar at the *side* of
*ax* (options are `'right'`, `'left'`, `'top'`, or
`'bottom'`). The width (or height) of the colorbar is specified by
*size* and is relative to *ax*. Add space *pad* between *ax* and
the colorbar. The remaining keyword arguments *kwds* are passed to
the call to :func:`colorbar`. Return the colorbar instance.
Reference: http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html
"""
divider = make_axes_locatable(ax)
cax = divider.append_axes(side, size=size, pad=pad)
cb = PL.colorbar(im, cax=cax, **kwds)
PL.axes(ax)
return cb
def drawStellarDensity(self,ax=None):
if not ax: ax = plt.gca()
# Stellar Catalog
self._create_catalog()
catalog = self.catalog
#catalog=ugali.observation.catalog.Catalog(self.config,roi=self.roi)
pix = ang2pix(self.nside, catalog.lon, catalog.lat)
counts = collections.Counter(pix)
pixels, number = numpy.array(sorted(counts.items())).T
star_map = healpy.UNSEEN * numpy.ones(healpy.nside2npix(self.nside))
star_map[pixels] = number
star_map = numpy.where(star_map == 0, healpy.UNSEEN, star_map)
#im = healpy.gnomview(star_map,**self.gnom_kwargs)
#healpy.graticule(dpar=1,dmer=1,color='0.5',verbose=False)
#pylab.close()
im = drawHealpixMap(star_map,self.glon,self.glat,self.radius,coord=self.coord)
#im = ax.imshow(im,origin='bottom')
try: ax.cax.colorbar(im)
except: pylab.colorbar(im,ax=ax)
ax.annotate("Stars",**self.label_kwargs)
return im
def plot_time_freq(self, colors=True, ax=None):
import pylab as pl
if ax is None:
fig, allax = pl.subplots(1)
ax = allax
# make time matrix same shape as others
t = np.outer(self.t, np.ones(self.npeaks))
f = self.f
if colors:
mag = 20*np.log10(self.mag)
ax.scatter(t, f, s=6, c=mag, lw=0)
else:
mag = 100 + 20*np.log10(self.mag)
ax.scatter(t, f, s=mag, lw=0)
pl.xlabel('Time (s)')
pl.ylabel('Frequency (Hz)')
# if colors:
# cs = pl.colorbar(ax=ax)
# cs.set_label('Magnitude (dB)')
# pl.show()
return ax
def plot_time_mag(self):
import pylab as pl
pl.figure()
t = np.outer(self.t, np.ones(self.npeaks))
# f = np.log2(self.f)
f = self.f
mag = 20*np.log10(self.mag)
pl.scatter(t, mag, s=10, c=f, lw=0,
norm=pl.matplotlib.colors.LogNorm())
pl.xlabel('Time (s)')
pl.ylabel('Magnitude (dB)')
cs = pl.colorbar()
cs.set_label('Frequency (Hz)')
# pl.show()
return pl.gca()
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def plotAgainstGFP_hist2d(self):
fig1 = pylab.figure(figsize = (20, 15))
print len(self.GFP)
for i in xrange(min(len(data.cat), 4)):
print len(self.GFP[self.categories == i])
vect = []
pylab.subplot(2,2,i+1)
pop = self.GFP[self.categories == i]
print "cat", i, "n pop", len(self.GFP[(self.categories == i) & (self.GFP > -np.log(12.5))])
H, xedges, yedges = np.histogram2d(self.angles[self.categories == i], self.GFP[self.categories == i], bins = 10)
hist = pylab.hist2d(self.GFP[self.categories == i], self.angles[self.categories == i], bins = 10, cmap = pylab.cm.Reds, normed = True)
pylab.clim(0.,0.035)
pylab.colorbar()
pylab.title(data.cat[i])
pylab.xlabel('GFP score')
pylab.ylabel('Angle (degree)')
pylab.xlim([-4.2, -1])
pylab.show()
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 view_whitening(data):
pylab.subplot(121)
pylab.imshow(data['spatial'], interpolation='nearest')
pylab.title('Spatial')
pylab.xlabel('# Electrode')
pylab.ylabel('# Electrode')
pylab.colorbar()
pylab.subplot(122)
pylab.title('Temporal')
pylab.plot(data['temporal'])
pylab.xlabel('Time [ms]')
x, y = pylab.xticks()
pylab.xticks(x, (x-x[-1]//2)//10)
pylab.tight_layout()
def get_performance(file_name, name):
a, b = os.path.splitext(os.path.basename(file_name))
file_name, ext = os.path.splitext(file_name)
file_out = os.path.join(os.path.abspath(file_name), a)
data = {}
result = h5py.File(file_out + '.basis.hdf5')
data['spatial'] = result.get('spatial')[:]
data['temporal'] = numpy.zeros(61) #result.get('temporal')[:]
pylab.figure()
pylab.subplot(121)
pylab.imshow(data['spatial'], interpolation='nearest')
pylab.title('Spatial')
pylab.xlabel('# Electrode')
pylab.ylabel('# Electrode')
pylab.colorbar()
pylab.subplot(122)
pylab.title('Temporal')
pylab.plot(data['temporal'])
pylab.xlabel('Time [ms]')
x, y = pylab.xticks()
pylab.xticks(x, (x-x[-1]//2)//10)
pylab.tight_layout()
plot_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
plot_path = os.path.join(plot_path, 'plots')
plot_path = os.path.join(plot_path, 'whitening')
if not os.path.exists(plot_path):
os.makedirs(plot_path)
output = os.path.join(plot_path, '%s.pdf' %name)
pylab.savefig(output)
return data
def make_panel_of_intensity_slices(fn, c_n=9):
M.rcParams.update({'font.size': 13})
intensList = read.extract_arr_from_h5(fn, "/history/intensities", n=c_n)
quatList = read.extract_arr_from_h5(fn, "/history/quaternion", n=-1)
P.ioff()
intens_len = len(intensList)
sqrt_len = int(N.sqrt(intens_len))
intens_sh = intensList[0].shape
iter_labels = read.create_interval_labels(len(quatList), c_n)[:intens_len]
to_plot = intensList[:intens_len]
quat_label = quatList[N.array(iter_labels)-1][:intens_len]
plot_titles = ["iter_%d, quat_%d"%(ii,jj) for ii,jj in zip(iter_labels, quat_label)]
fig, ax = P.subplots(sqrt_len, sqrt_len, sharex=True, sharey=True, figsize=(1.8*sqrt_len, 2.*sqrt_len))
plt_counter = 0
for r in range(sqrt_len):
for c in range(sqrt_len):
ax[r,c].set_title(plot_titles[plt_counter])
curr_slice = to_plot[plt_counter][intens_sh[0]/2]
curr_slice = curr_slice*(curr_slice>0.) + 1.E-8*(curr_slice<=0.)
ax[r,c].set_title(plot_titles[plt_counter], fontsize=11.5)
im = ax[r,c].imshow(N.log10(curr_slice), vmin=-6.5, vmax=-3.5, aspect='auto', cmap=P.cm.coolwarm)
plt_counter += 1
fig.subplots_adjust(wspace=0.01)
(shx, shy) = curr_slice.shape
(h_shx, h_shy) = (shx/2, shy/2)
xt = N.linspace(0.5*h_shx, shx-.5*h_shx-1, 3).astype('int')
xt_l = N.linspace(-0.5*h_shx, 0.5*h_shx, 3).astype('int')
yt = N.linspace(0, shy-1, 3).astype('int')
yt_l = N.linspace(-1*h_shy, h_shy, 3).astype('int')
P.setp(ax, xticks=xt, xticklabels=xt_l, yticks=yt, yticklabels=yt_l)
cbar_ax = fig.add_axes([0.9, 0.1, 0.025, 0.8])
fig.colorbar(im, cax=cbar_ax, label="log10(intensities)")
img_name = "recon_series.pdf"
P.savefig(img_name, bbox_inches='tight')
print("Image has been saved as %s" % img_name)
P.close(fig)
def twoDimensionalHistogram(title, title_x, title_y,
z, bins_x, bins_y,
lim_x=None, lim_y=None,
vmin=None, vmax=None):
"""
Create a two-dimension histogram plot or binned map.
If using the outputs of numpy.histogram2d, remember to transpose the histogram.
INPUTS
"""
pylab.figure()
mesh_x, mesh_y = numpy.meshgrid(bins_x, bins_y)
if vmin != None and vmin == vmax:
pylab.pcolor(mesh_x, mesh_y, z)
else:
pylab.pcolor(mesh_x, mesh_y, z, vmin=vmin, vmax=vmax)
pylab.xlabel(title_x)
pylab.ylabel(title_y)
pylab.title(title)
pylab.colorbar()
if lim_x:
pylab.xlim(lim_x[0], lim_x[1])
if lim_y:
pylab.ylim(lim_y[0], lim_y[1])
############################################################
def drawTS(self,ax=None, filename=None, zidx=0):
if not ax: ax = plt.gca()
if not filename:
#dirname = self.config.params['output2']['searchdir']
#basename = self.config.params['output2']['mergefile']
#filename = os.path.join(dirname,basename)
filename = self.config.mergefile
results=pyfits.open(filename)[1]
pixels = results.data['PIXEL']
values = 2*results.data['LOG_LIKELIHOOD']
if values.ndim == 1: values = values.reshape(-1,1)
ts_map = healpy.UNSEEN * numpy.ones(healpy.nside2npix(self.nside))
# Sum through all distance_moduli
#ts_map[pixels] = values.sum(axis=1)
# Just at maximum slice from object
ts_map[pixels] = values[:,zidx]
#im = healpy.gnomview(ts_map,**self.gnom_kwargs)
#healpy.graticule(dpar=1,dmer=1,color='0.5',verbose=False)
#pylab.close()
#im = ax.imshow(im,origin='bottom')
im = drawHealpixMap(ts_map,self.glon,self.glat,self.radius,coord=self.coord)
try: ax.cax.colorbar(im)
except: pylab.colorbar(im)
ax.annotate("TS",**self.label_kwargs)
return im
def drawCMD(self, ax=None, radius=None, zidx=None):
if not ax: ax = plt.gca()
import ugali.isochrone
if zidx is not None:
filename = self.config.mergefile
logger.debug("Opening %s..."%filename)
f = pyfits.open(filename)
distance_modulus = f[2].data['DISTANCE_MODULUS'][zidx]
iso = ugali.isochrone.Padova(age=12,z=0.0002,mod=distance_modulus)
#drawIsochrone(iso,ls='',marker='.',ms=1,c='k')
drawIsochrone(iso)
# Stellar Catalog
self._create_catalog()
if radius is not None:
sep = ugali.utils.projector.angsep(self.glon,self.glat,self.catalog.lon,self.catalog.lat)
cut = (sep < radius)
catalog_cmd = self.catalog.applyCut(cut)
else:
catalog_cmd = self.catalog
ax.scatter(catalog_cmd.color, catalog_cmd.mag,color='b',marker='.',s=1)
ax.set_xlim(self.roi.bins_color[0],self.roi.bins_color[-1])
ax.set_ylim(self.roi.bins_mag[-1],self.roi.bins_mag[0])
ax.set_xlabel('Color (mag)')
ax.set_ylabel('Magnitude (mag)')
try: ax.cax.colorbar(im)
except: pass
ax.annotate("Stars",**self.label_kwargs)
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 visualiseObject(self, cmap="hot"):
pylab.ion()
#pylab.set_cmap("gray")
pylab.gray()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(self.getObject(), interpolation="nearest", cmap=cmap)
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def visualiseObject(self, cmap="hot"):
pylab.ion()
#pylab.set_cmap("gray")
pylab.gray()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(self.getObject(), interpolation="nearest", cmap=cmap)
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
"""Wrapper around pl.imshow"""
if cmap is None:
cmap = cm.jet
if vmin is None:
vmin = data.min()
if vmax is None:
vmax = data.max()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
pl.colorbar(im, cax=cax)
def plot_hebbsom_links_distances_activations(X, Y, mdl, predictions, distances, activities):
"""plot the hebbian link matrix, and all node distances and activities for all inputs"""
hebblink_log = np.log(mdl.hebblink_filter.T + 1.0)
fig4 = pl.figure()
fig4.suptitle("Debugging SOM: hebbian links, distances, activities (%s)" % (mdl.__class__.__name__))
gs = gridspec.GridSpec(4, 1)
# pl.plot(X, Y, "k.", alpha=0.5)
# pl.subplot(numplots, 1, numplots-1)
ax1 = fig4.add_subplot(gs[0])
# im1 = ax1.imshow(mdl.hebblink_filter, interpolation="none", cmap=pl.get_cmap("gray"))
im1 = ax1.pcolormesh(hebblink_log, cmap=pl.get_cmap("gray"))
ax1.set_xlabel("in (e)")
ax1.set_ylabel("out (p)")
cbar = fig4.colorbar(mappable = im1, ax=ax1, orientation="horizontal")
ax2 = fig4.add_subplot(gs[1])
distarray = np.array(distances)
print("distarray.shape", distarray.shape)
pcm = ax2.pcolormesh(distarray.T)
cbar = fig4.colorbar(mappable = pcm, ax=ax2, orientation="horizontal")
# pl.subplot(numplots, 1, numplots)
ax3 = fig4.add_subplot(gs[2])
actarray = np.array(activities)
print("actarray.shape", actarray.shape)
pcm = ax3.pcolormesh(actarray.T)
cbar = fig4.colorbar(mappable = pcm, ax=ax3, orientation="horizontal")
ax4 = fig4.add_subplot(gs[3])
ax4.plot(hebblink_log.flatten())
print("hebblink_log", hebblink_log)
fig4.show()
def plot_colormeshmatrix_reduced(
X, Y, ymin = None, ymax = None,
title = "plot_colormeshmatrix_reduced"):
print "plot_colormeshmatrix_reduced X.shape", X.shape, "Y.shape", Y.shape
# input_cols = [i for i in df.columns if i.startswith("X")]
# output_cols = [i for i in df.columns if i.startswith("Y")]
# Xs = df[input_cols]
# Ys = df[output_cols]
# numsamples = df.shape[0]
# print "plot_scattermatrix_reduced: numsamples = %d" % numsamples
# # numplots = Xs.shape[1] * Ys.shape[1]
# # print "numplots = %d" % numplots
cbar_orientation = "vertical" # "horizontal"
gs = gridspec.GridSpec(Y.shape[2], X.shape[2]/2)
pl.ioff()
fig = pl.figure()
fig.suptitle(title)
# # alpha = 1.0 / np.power(numsamples, 1.0/(Xs.shape[1] - 0))
# alpha = 0.2
# print "alpha", alpha
# cols = ["k", "b", "r", "g", "c", "m", "y"]
for i in range(X.shape[2]/2):
for j in range(Y.shape[2]):
# print "i, j", i, j, Xs, Ys
ax = fig.add_subplot(gs[j, i])
pcm = ax.pcolormesh(X[:,:,i], X[:,:,X.shape[2]/2+i], Y[:,:,j], vmin = ymin, vmax = ymax)
# ax.plot(Xs.as_matrix()[:,i], Ys.as_matrix()[:,j], "ko", alpha = alpha)
ax.set_xlabel("goal")
ax.set_ylabel("error")
cbar = fig.colorbar(mappable = pcm, ax=ax, orientation=cbar_orientation)
ax.set_aspect(1)
if SAVEPLOTS:
fig.savefig("fig_%03d_colormeshmatrix_reduced.pdf" % (fig.number), dpi=300)
fig.show()
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
from mpl_toolkits.axes_grid1 import make_axes_locatable
"""Wrapper around pl.imshow"""
if cmap is None:
cmap = cm.jet
if vmin is None:
vmin = data.min()
if vmax is None:
vmax = data.max()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
pl.colorbar(im, cax=cax)
def nice_imshow(ax, data, vmin=None, vmax=None, cmap=None):
"""Wrapper around pl.imshow"""
if cmap is None:
cmap = cm.jet
if vmin is None:
vmin = data.min()
if vmax is None:
vmax = data.max()
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest', cmap=cmap)
pl.colorbar(im, cax=cax)
mlcomp_sparse_document_classification.py 文件源码
项目:Parallel-SGD
作者: angadgill
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def benchmark(clf_class, params, name):
print("parameters:", params)
t0 = time()
clf = clf_class(**params).fit(X_train, y_train)
print("done in %fs" % (time() - t0))
if hasattr(clf, 'coef_'):
print("Percentage of non zeros coef: %f"
% (np.mean(clf.coef_ != 0) * 100))
print("Predicting the outcomes of the testing set")
t0 = time()
pred = clf.predict(X_test)
print("done in %fs" % (time() - t0))
print("Classification report on test set for classifier:")
print(clf)
print()
print(classification_report(y_test, pred,
target_names=news_test.target_names))
cm = confusion_matrix(y_test, pred)
print("Confusion matrix:")
print(cm)
# Show confusion matrix
pl.matshow(cm)
pl.title('Confusion matrix of the %s classifier' % name)
pl.colorbar()
def view_classification(data_1, data_2, title=None, save=None):
fig = pylab.figure()
count = 0
panels = [0, 2, 1, 3]
for item in [data_1, data_2]:
clf, cld, X, X_raw, y = item
for mode in ['predict', 'decision_function']:
ax = fig.add_subplot(2, 2, panels[count]+1)
if mode == 'predict':
c = clf
vmax = 1.0
vmin = 0.0
elif mode == 'decision_function':
c = cld
vmax = max(abs(numpy.amin(c)), abs(numpy.amax(c)))
vmin = - vmax
from circus.validating.utils import Projection
p = Projection()
_ = p.fit(X_raw, y)
X_raw_ = p.transform(X_raw)
# Plot figure.
sc = ax.scatter(X_raw_[:, 0], X_raw_[:, 1], c=c, s=5, lw=0.1, cmap='bwr',
vmin=vmin, vmax=vmax)
cb = fig.colorbar(sc)
ax.grid(True)
if panels[count] in [0, 1]:
if panels[count] == 0:
ax.set_title('Classification Before')
ax.set_ylabel("2nd component")
if panels[count] == 1:
ax.set_title('Classification After')
cb.set_label('Prediction')
elif panels[count] in [2, 3]:
ax.set_xlabel("1st component")
if panels[count] == 2:
ax.set_ylabel("2nd component")
if panels[count] == 3:
cb.set_label('Decision function')
count += 1
if save is None:
pylab.show()
else:
pylab.savefig(save)
pylab.close(fig)
return