def plot_word_frequencies(freq, user):
samples = [item for item, _ in freq.most_common(50)]
freqs = np.array([float(freq[sample]) for sample in samples])
freqs /= np.max(freqs)
ylabel = "Normalized word count"
pylab.grid(True, color="silver")
kwargs = dict()
kwargs["linewidth"] = 2
kwargs["label"] = user
pylab.plot(freqs, **kwargs)
pylab.xticks(range(len(samples)), [nltk.compat.text_type(s) for s in samples], rotation=90)
pylab.xlabel("Samples")
pylab.ylabel(ylabel)
pylab.gca().set_yscale('log', basey=2)
python类xticks()的实例源码
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 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 plot_eigenspectrum(G, s, nvis, nhid):
with misc.gnumpy_conversion_check('allow'):
dim = G.shape[0]
d, Q = scipy.linalg.eigh(G)
d = d[::-1]
Q = Q[:, ::-1]
pts = np.unique(np.floor(np.logspace(0., np.log10(dim-1), 500)).astype(int)) - 1
cf = [fisher.correlation_fraction(Q[:, i], s, nvis, nhid) for i in pts]
pylab.figure()
pylab.subplot(2, 1, 1)
pylab.loglog(range(1, dim+1), d, 'b-', lw=2.)
pylab.xticks([])
pylab.yticks(fontsize='large')
pylab.subplot(2, 1, 2)
pylab.semilogx(pts+1, cf, 'r-', lw=2.)
pylab.xticks(fontsize='x-large')
pylab.yticks(fontsize='large')
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 plot(self,title='',include_baseline=False,equal_aspect=True):
""" Method that generates a plot of the ROC curve
Parameters:
title: Title of the chart
include_baseline: Add the baseline plot line if it's True
equal_aspect: Aspects to be equal for all plot
"""
pylab.clf()
pylab.plot([x[0] for x in self.derived_points], [y[1] for y in self.derived_points], self.linestyle)
if include_baseline:
pylab.plot([0.0,1.0], [0.0,1.0],'k-.')
pylab.ylim((0,1))
pylab.xlim((0,1))
pylab.xticks(pylab.arange(0,1.1,.1))
pylab.yticks(pylab.arange(0,1.1,.1))
pylab.grid(True)
if equal_aspect:
cax = pylab.gca()
cax.set_aspect('equal')
pylab.xlabel('1 - Specificity')
pylab.ylabel('Sensitivity')
pylab.title(title)
pylab.show()
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 view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False):
nb_templates = templates.shape[1]
n_panels = numpy.ceil(numpy.sqrt(nb_templates))
mask = numpy.where(halo > -1)[0]
clust_idx = numpy.unique(halo[mask])
fig = pylab.figure()
square = True
center = len(data[0] - 1)//2
for count, i in enumerate(xrange(nb_templates)):
if square:
pylab.subplot(n_panels, n_panels, count + 1)
if (numpy.mod(count, n_panels) != 0):
pylab.setp(pylab.gca(), yticks=[])
if (count < n_panels*(n_panels - 1)):
pylab.setp(pylab.gca(), xticks=[])
subcurves = numpy.where(halo == clust_idx[count])[0]
for k in numpy.random.permutation(subcurves)[:n_curves]:
pylab.plot(data[k], '0.5')
pylab.plot(templates[:, count], 'r')
pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5)
pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5)
xmin, xmax = pylab.xlim()
pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--')
pylab.plot([xmin, xmax], [threshold, threshold], 'k--')
#pylab.ylim(-1.5*threshold, 1.5*threshold)
ymin, ymax = pylab.ylim()
pylab.plot([center, center], [ymin, ymax], 'k--')
pylab.title('Cluster %d' %i)
if nb_templates > 0:
pylab.tight_layout()
if save:
pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1]))
pylab.close()
else:
pylab.show()
del fig
def view_raw_templates(file_name, n_temp=2, square=True):
N_e, N_t, N_tm = templates.shape
if not numpy.iterable(n_temp):
if square:
idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp**2]
else:
idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp]
else:
idx = n_temp
import matplotlib.colors as colors
my_cmap = pylab.get_cmap('winter')
cNorm = colors.Normalize(vmin=0, vmax=N_e)
scalarMap = pylab.cm.ScalarMappable(norm=cNorm, cmap=my_cmap)
pylab.figure()
for count, i in enumerate(idx):
if square:
pylab.subplot(n_temp, n_temp, count + 1)
if (numpy.mod(count, n_temp) != 0):
pylab.setp(pylab.gca(), yticks=[])
if (count < n_temp*(n_temp - 1)):
pylab.setp(pylab.gca(), xticks=[])
else:
pylab.subplot(len(idx), 1, count + 1)
if count != (len(idx) - 1):
pylab.setp(pylab.gca(), xticks=[])
for j in xrange(N_e):
colorVal = scalarMap.to_rgba(j)
pylab.plot(templates[j, :, i], color=colorVal)
pylab.title('Template %d' %i)
pylab.tight_layout()
pylab.show()
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 align_subplots(
N,
M,
xlim=None,
ylim=None,
):
"""make all of the subplots have the same limits, turn off unnecessary ticks"""
# find sensible xlim,ylim
if xlim is None:
xlim = [np.inf, -np.inf]
for i in range(N * M):
pb.subplot(N, M, i + 1)
xlim[0] = min(xlim[0], pb.xlim()[0])
xlim[1] = max(xlim[1], pb.xlim()[1])
if ylim is None:
ylim = [np.inf, -np.inf]
for i in range(N * M):
pb.subplot(N, M, i + 1)
ylim[0] = min(ylim[0], pb.ylim()[0])
ylim[1] = max(ylim[1], pb.ylim()[1])
for i in range(N * M):
pb.subplot(N, M, i + 1)
pb.xlim(xlim)
pb.ylim(ylim)
if i % M:
pb.yticks([])
else:
removeRightTicks()
if i < M * (N - 1):
pb.xticks([])
else:
removeUpperTicks()
def showgrid(l,cols=None,n=400,titles=None,xlabels=None,ylabels=None,**kw):
if "cmap" not in kw: kw["cmap"] = cm.gray
if "interpolation" not in kw: kw["interpolation"] = "nearest"
n = minimum(n,len(l))
if cols is None: cols = int(sqrt(n))
rows = (n+cols-1)//cols
for i in range(n):
pylab.xticks([]) ;pylab.yticks([])
pylab.subplot(rows,cols,i+1)
pylab.imshow(l[i],**kw)
if titles is not None: pylab.title(str(titles[i]))
if xlabels is not None: pylab.xlabel(str(xlabels[i]))
if ylabels is not None: pylab.ylabel(str(ylabels[i]))
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 dendrogram(df, number_of_clusters, agglomerated_feature_labels):
import seaborn as sns
# Todo: Create Dendrogram
# used networks are the labels occuring in agglomerated_features.labels_
# which corresponds to np.arange(0, number_of_clusters)
# number_of_clusters = int(df.shape[1] / 1.2)
# used_networks = np.arange(0, number_of_clusters, dtype=int)
used_networks = np.unique(agglomerated_feature_labels)
# used_networks = [1, 5, 6, 7, 8, 11, 12, 13, 16, 17]
# In our case all columns are clustered, which means used_columns is true in every element
# used_columns = (df.columns.get_level_values(None)
# .astype(int)
# .isin(used_networks))
# used_columns = (agglomerated_feature_labels.astype(int).isin(used_networks))
# df = df.loc[:, used_columns]
# Create a custom palette to identify the networks
network_pal = sns.cubehelix_palette(len(used_networks),
light=.9, dark=.1, reverse=True,
start=1, rot=-2)
network_lut = dict(zip(map(str, df.columns), network_pal))
# Convert the palette to vectors that will be drawn on the side of the matrix
networks = df.columns.get_level_values(None)
# networks = agglomerated_feature_labels
network_colors = pd.Series(networks, index=df.columns).map(network_lut)
# plt.figure()
# cg = sns.clustermap(df, metric="correlation")
# plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)
sns.set(font="monospace")
# Create custom colormap
cmap = sns.diverging_palette(h_neg=210, h_pos=350, s=90, l=30, as_cmap=True)
cg = sns.clustermap(df.astype(float).corr(), cmap=cmap, linewidths=.5, row_colors=network_colors,
col_colors=network_colors)
plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)
plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)
# plt.xticks(rotation=90)
plt.show()
def showgrid(l,cols=None,n=400,titles=None,xlabels=None,ylabels=None,**kw):
if "cmap" not in kw: kw["cmap"] = cm.gray
if "interpolation" not in kw: kw["interpolation"] = "nearest"
n = minimum(n,len(l))
if cols is None: cols = int(sqrt(n))
rows = (n+cols-1)//cols
for i in range(n):
pylab.xticks([]) ;pylab.yticks([])
pylab.subplot(rows,cols,i+1)
pylab.imshow(l[i],**kw)
if titles is not None: pylab.title(str(titles[i]))
if xlabels is not None: pylab.xlabel(str(xlabels[i]))
if ylabels is not None: pylab.ylabel(str(ylabels[i]))
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 showgrid(l,cols=None,n=400,titles=None,xlabels=None,ylabels=None,**kw):
if "cmap" not in kw: kw["cmap"] = cm.gray
if "interpolation" not in kw: kw["interpolation"] = "nearest"
n = minimum(n,len(l))
if cols is None: cols = int(sqrt(n))
rows = (n+cols-1)//cols
for i in range(n):
pylab.xticks([]) ;pylab.yticks([])
pylab.subplot(rows,cols,i+1)
pylab.imshow(l[i],**kw)
if titles is not None: pylab.title(str(titles[i]))
if xlabels is not None: pylab.xlabel(str(xlabels[i]))
if ylabels is not None: pylab.ylabel(str(ylabels[i]))
def drawHessDiagram(self,catalog=None):
ax = plt.gca()
if not catalog: catalog = self.get_stars()
r_peak = self.kernel.extension
angsep = ugali.utils.projector.angsep(self.ra, self.dec, catalog.ra, catalog.dec)
cut_inner = (angsep < r_peak)
cut_annulus = (angsep > 0.5) & (angsep < 1.) # deg
mmin, mmax = 16., 24.
cmin, cmax = -0.5, 1.0
mbins = np.linspace(mmin, mmax, 150)
cbins = np.linspace(cmin, cmax, 150)
color = catalog.color[cut_annulus]
mag = catalog.mag[cut_annulus]
h, xbins, ybins = numpy.histogram2d(color, mag, bins=[cbins,mbins])
blur = nd.filters.gaussian_filter(h.T, 2)
kwargs = dict(extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()],
cmap='gray_r', aspect='auto', origin='lower',
rasterized=True, interpolation='none')
ax.imshow(blur, **kwargs)
pylab.scatter(catalog.color[cut_inner], catalog.mag[cut_inner],
c='red', s=7, edgecolor='none')# label=r'$r < %.2f$ deg'%(r_peak))
ugali.utils.plotting.drawIsochrone(self.isochrone, c='b', zorder=10)
ax.set_xlim(-0.5, 1.)
ax.set_ylim(24., 16.)
plt.xlabel(r'$g - r$')
plt.ylabel(r'$g$')
plt.xticks([-0.5, 0., 0.5, 1.])
plt.yticks(numpy.arange(mmax - 1., mmin - 1., -1.))
radius_string = (r'${\rm r}<%.1f$ arcmin'%( 60 * r_peak))
pylab.text(0.05, 0.95, radius_string,
fontsize=10, ha='left', va='top', color='red',
transform=pylab.gca().transAxes,
bbox=dict(facecolor='white', alpha=1., edgecolor='none'))
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 showFourier(self):
psd2D = np.log(np.abs(self.four)**2+1)
(height,width) = psd2D.shape
py.figure(figsize=(10,10*height/width),facecolor='white')
py.clf()
py.rc('text',usetex=True)
py.xlabel(r'$\omega_1$',fontsize=24)
py.ylabel(r'$\omega_2$',fontsize=24)
py.xticks(fontsize=16)
py.yticks(fontsize=16)
py.imshow( psd2D, cmap='Greys_r',extent=[-pi,pi,-pi,pi],aspect='auto')
py.show()
def plot_results(self, results, xloc, color, ls, label):
iter_counts = sorted(set([it for it, av in results.keys() if av == self.average]))
sorted_results = [results[it, self.average] for it in iter_counts]
avg = np.array([r.train_logprob() for r in sorted_results])
if hasattr(r, 'train_logprob_interval'):
lower = np.array([r.train_logprob_interval()[0] for r in sorted_results])
upper = np.array([r.train_logprob_interval()[1] for r in sorted_results])
if self.logscale:
plot_cmd = pylab.semilogx
else:
plot_cmd = pylab.plot
xloc = xloc[:len(avg)]
lw = 2.
if label not in self.labels:
plot_cmd(xloc, avg, color=color, ls=ls, lw=lw, label=label)
else:
plot_cmd(xloc, avg, color=color, ls=ls, lw=lw)
self.labels.add(label)
pylab.xticks(fontsize='xx-large')
pylab.yticks(fontsize='xx-large')
try:
pylab.errorbar(xloc, (lower+upper)/2., yerr=(upper-lower)/2., fmt='', ls='None', ecolor=color)
except:
pass
def feature_importance(rf, save_path=None):
"""Plots feature importance of sklearn RandomForest
Parameters
----------
rf : RandomForestClassifier
save_path : str
"""
importances = rf.feature_importances_
nb = len(importances)
tree_imp = [tree.feature_importances_ for tree in rf.estimators_]
# print "Print feature importance of rf with %d trees." % len(tree_imp)
std = np.std(tree_imp, axis=0) / np.sqrt(len(tree_imp))
indices = np.argsort(importances)[::-1]
# Print the feature ranking
# print("Feature ranking:")
# for f in range(nb):
# print("%d. feature %d (%f)" %
# (f + 1, indices[f], importances[indices[f]]))
# Plot the feature importances of the forest
pl.figure()
pl.title("Feature importances")
pl.bar(range(nb), importances[indices],
color="r", yerr=std[indices], align="center")
pl.xticks(range(nb), indices)
pl.xlim([-1, nb])
if save_path is not None:
pl.savefig(save_path)
pl.close()
c10_20_6_figures.py 文件源码
项目:Python-for-Finance-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def graph(text,text2=''):
pl.xticks(())
pl.yticks(())
pl.xlim(0,30)
pl.ylim(0,20)
pl.plot([x,x],[0,3])
pl.text(x,-2,"X");
pl.text(0,x,"X")
pl.text(x,x*1.7, text, ha='center', va='center',size=10, alpha=.5)
pl.text(-5,10,text2,size=25)
def plot_multiple_roc(rocList,title='',labels=None, include_baseline=False, equal_aspect=True):
""" Plots multiple ROC curves on the same chart.
Parameters:
rocList: the list of ROCData objects
title: The tile of the chart
labels: The labels of each ROC curve
include_baseline: if it's True include the random baseline
equal_aspect: keep equal aspect for all roc curves
"""
pylab.clf()
pylab.ylim((0,1))
pylab.xlim((0,1))
pylab.xticks(pylab.arange(0,1.1,.1))
pylab.yticks(pylab.arange(0,1.1,.1))
pylab.grid(True)
if equal_aspect:
cax = pylab.gca()
cax.set_aspect('equal')
pylab.xlabel("1 - Specificity")
pylab.ylabel("Sensitivity")
pylab.title(title)
if not labels:
labels = [ '' for x in rocList]
_remove_duplicate_styles(rocList)
for ix, r in enumerate(rocList):
pylab.plot([x[0] for x in r.derived_points], [y[1] for y in r.derived_points], r.linestyle, linewidth=1, label=labels[ix])
if include_baseline:
pylab.plot([0.0,1.0], [0.0, 1.0], 'k-', label= 'random')
if labels:
pylab.legend(loc='lower right')
pylab.show()
def view_templates(file_name, temp_id=0, best_elec=None, templates=None):
params = CircusParser(file_name)
N_e = params.getint('data', 'N_e')
N_total = params.getint('data', 'N_total')
sampling_rate = params.getint('data', 'sampling_rate')
do_temporal_whitening = params.getboolean('whitening', 'temporal')
do_spatial_whitening = params.getboolean('whitening', 'spatial')
spike_thresh = params.getfloat('detection', 'spike_thresh')
file_out_suff = params.get('data', 'file_out_suff')
N_t = params.getint('detection', 'N_t')
nodes, edges = get_nodes_and_edges(params)
chunk_size = N_t
N_total = params.getint('data', 'N_total')
inv_nodes = numpy.zeros(N_total, dtype=numpy.int32)
inv_nodes[nodes] = numpy.argsort(nodes)
if templates is None:
templates = load_data(params, 'templates')
clusters = load_data(params, 'clusters')
probe = params.probe
positions = {}
for i in probe['channel_groups'].keys():
positions.update(probe['channel_groups'][i]['geometry'])
xmin = 0
xmax = 0
ymin = 0
ymax = 0
scaling = 10*numpy.max(numpy.abs(templates[:,temp_id].toarray().reshape(N_e, N_t)))
for i in xrange(N_e):
if positions[i][0] < xmin:
xmin = positions[i][0]
if positions[i][0] > xmax:
xmax = positions[i][0]
if positions[i][1] < ymin:
ymin = positions[i][0]
if positions[i][1] > ymax:
ymax = positions[i][1]
if best_elec is None:
best_elec = clusters['electrodes'][temp_id]
elif best_elec == 'auto':
best_elec = numpy.argmin(numpy.min(templates[:, :, temp_id], 1))
pylab.figure()
for count, i in enumerate(xrange(N_e)):
x, y = positions[i]
xpadding = ((x - xmin)/(float(xmax - xmin) + 1))*(2*N_t)
ypadding = ((y - ymin)/(float(ymax - ymin) + 1))*scaling
if i == best_elec:
c='r'
elif i in inv_nodes[edges[nodes[best_elec]]]:
c='k'
else:
c='0.5'
pylab.plot(xpadding + numpy.arange(0, N_t), ypadding + templates[i, :, temp_id], color=c)
pylab.tight_layout()
pylab.setp(pylab.gca(), xticks=[], yticks=[])
pylab.xlim(xmin, 3*N_t)
pylab.show()
return best_elec
def plotPrecisionRecall(precision, recall, outFileName, Fig=None, drawCol=1, textLabel = None, title = None, fontsize1 = 24, fontsize2 = 20, linewidth = 3):
'''
:param precision:
:param recall:
:param outFileName:
:param Fig:
:param drawCol:
:param textLabel:
:param fontsize1:
:param fontsize2:
:param linewidth:
'''
clearFig = False
if Fig == None:
Fig = pylab.figure()
clearFig = True
#tableString = 'Algo avgprec Fmax prec recall accuracy fpr Q(TonITS)\n'
linecol = ['g','m','b','c']
#if we are evaluating SP, then BL is available
#sectionName = 'Evaluation_'+tag+'PxProb'
#fullEvalFile = os.path.join(eval_dir,evalName)
#Precision,Recall,evalString = readEvaluation(fullEvalFile,sectionName,AlgoLabel)
pylab.plot(100*recall, 100*precision, linewidth=linewidth, color=linecol[drawCol], label=textLabel)
#writing out PrecRecall curves as graphic
setFigLinesBW(Fig)
if textLabel!= None:
pylab.legend(loc='lower left',prop={'size':fontsize2})
if title!= None:
pylab.title(title, fontsize=fontsize1)
#pylab.title(title,fontsize=24)
pylab.ylabel('PRECISION [%]',fontsize=fontsize1)
pylab.xlabel('RECALL [%]',fontsize=fontsize1)
pylab.xlim(0,100)
pylab.xticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
pylab.ylim(0,100)
pylab.yticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
pylab.grid(True)
#
if type(outFileName) != list:
pylab.savefig( outFileName )
else:
for outFn in outFileName:
pylab.savefig( outFn )
if clearFig:
pylab.close()
Fig.clear()
def plotPrecisionRecall(precision, recall, outFileName, Fig=None, drawCol=1, textLabel = None, title = None, fontsize1 = 24, fontsize2 = 20, linewidth = 3):
'''
:param precision:
:param recall:
:param outFileName:
:param Fig:
:param drawCol:
:param textLabel:
:param fontsize1:
:param fontsize2:
:param linewidth:
'''
clearFig = False
if Fig == None:
Fig = pylab.figure()
clearFig = True
#tableString = 'Algo avgprec Fmax prec recall accuracy fpr Q(TonITS)\n'
linecol = ['g','m','b','c']
#if we are evaluating SP, then BL is available
#sectionName = 'Evaluation_'+tag+'PxProb'
#fullEvalFile = os.path.join(eval_dir,evalName)
#Precision,Recall,evalString = readEvaluation(fullEvalFile,sectionName,AlgoLabel)
pylab.plot(100*recall, 100*precision, linewidth=linewidth, color=linecol[drawCol], label=textLabel)
#writing out PrecRecall curves as graphic
setFigLinesBW(Fig)
if textLabel!= None:
pylab.legend(loc='lower left',prop={'size':fontsize2})
if title!= None:
pylab.title(title, fontsize=fontsize1)
#pylab.title(title,fontsize=24)
pylab.ylabel('PRECISION [%]',fontsize=fontsize1)
pylab.xlabel('RECALL [%]',fontsize=fontsize1)
pylab.xlim(0,100)
pylab.xticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
pylab.ylim(0,100)
pylab.yticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
pylab.grid(True)
#
if type(outFileName) != list:
pylab.savefig( outFileName )
else:
for outFn in outFileName:
pylab.savefig( outFn )
if clearFig:
pylab.close()
Fig.clear()
def plotPrecisionRecall(precision, recall, outFileName, Fig=None, drawCol=1, textLabel = None, title = None, fontsize1 = 24, fontsize2 = 20, linewidth = 3):
'''
:param precision:
:param recall:
:param outFileName:
:param Fig:
:param drawCol:
:param textLabel:
:param fontsize1:
:param fontsize2:
:param linewidth:
'''
clearFig = False
if Fig == None:
Fig = pylab.figure()
clearFig = True
#tableString = 'Algo avgprec Fmax prec recall accuracy fpr Q(TonITS)\n'
linecol = ['g','m','b','c']
#if we are evaluating SP, then BL is available
#sectionName = 'Evaluation_'+tag+'PxProb'
#fullEvalFile = os.path.join(eval_dir,evalName)
#Precision,Recall,evalString = readEvaluation(fullEvalFile,sectionName,AlgoLabel)
pylab.plot(100*recall, 100*precision, linewidth=linewidth, color=linecol[drawCol], label=textLabel)
#writing out PrecRecall curves as graphic
setFigLinesBW(Fig)
if textLabel!= None:
pylab.legend(loc='lower left',prop={'size':fontsize2})
if title!= None:
pylab.title(title, fontsize=fontsize1)
#pylab.title(title,fontsize=24)
pylab.ylabel('PRECISION [%]',fontsize=fontsize1)
pylab.xlabel('RECALL [%]',fontsize=fontsize1)
pylab.xlim(0,100)
pylab.xticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
pylab.ylim(0,100)
pylab.yticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )
pylab.grid(True)
#
if type(outFileName) != list:
pylab.savefig( outFileName )
else:
for outFn in outFileName:
pylab.savefig( outFn )
if clearFig:
pylab.close()
Fig.clear()