Python matplotlib.pylab 模块,figure() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pylab.figure()。
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
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 set_nice_params():
fsize=18
params = {'axes.labelsize': fsize,
# 'font.family': 'serif',
'font.family': 'Times New Roman',
'figure.facecolor': 'white',
'text.fontsize': fsize,
'legend.fontsize': fsize,
'xtick.labelsize': fsize*0.8,
'ytick.labelsize': fsize*0.8,
'ytick.minor.pad': 8,
'ytick.major.pad': 8,
'xtick.minor.pad': 8,
'xtick.major.pad': 8,
'text.usetex': False,
'lines.markeredgewidth': 0}
pl.rcParams.update(params)
def postaud(x, fmax, fbtype=None):
if fbtype is None:
fbtype = 'bark'
nbands = x.shape[0]
nframes = x.shape[1]
nfpts = nbands
if fbtype == 'bark':
bancfhz = bark2freq(np.linspace(0, freq2bark(fmax), nfpts))
fsq = bancfhz * bancfhz
ftmp = fsq + 1.6e5
eql = ((fsq/ftmp)**2) * ((fsq + 1.44e6)/(fsq + 9.61e6))
'''
plt.figure()
plt.plot(eql)
plt.show()
'''
eql = eql.reshape(np.size(eql), 1)
z = np.repeat(eql, nframes, axis=1) * x
z = z ** (1./3.)
y = np.vstack((z[1, :], z[1:nbands-1, :], z[nbands-2, :]))
return y
def plot_volcano(logFC,p_val,sample_name,saveName,logFC_thresh):
fig=pl.figure()
## To plot and save
pl.scatter(logFC[(p_val>0.05)|(abs(logFC)<logFC_thresh)],-np.log10(p_val[(p_val>0.05)|(abs(logFC)<logFC_thresh)]),color='blue',alpha=0.5);
pl.scatter(logFC[(p_val<0.05)&(abs(logFC)>logFC_thresh)],-np.log10(p_val[(p_val<0.05)&(abs(logFC)>logFC_thresh)]),color='red');
pl.hlines(-np.log10(0.05),min(logFC),max(logFC))
pl.vlines(-logFC_thresh,min(-np.log10(p_val)),max(-np.log10(p_val)))
pl.vlines(logFC_thresh,min(-np.log10(p_val)),max(-np.log10(p_val)))
pl.xlim(-3,3)
pl.xlabel('Log Fold Change')
pl.ylabel('-log10(p-value)')
pl.savefig(saveName)
pl.close(fig)
# def plot_histograms(df_peaks,pntr_list):
#
# for pntr in pntr_list:
# colName =pntr[2]+'_Intragenic_position'
# pl.hist(df_peaks[colName])
# pl.xlabel(colName)
# pl.ylabel()
# pl.show()
def plot(l, x1, x2, y, e):
# Plot
time_range = numpy.arange(0, l)
pl.figure(1)
pl.subplot(221)
pl.plot(time_range, x1)
pl.title("Input signal")
pl.subplot(222)
pl.plot(time_range, x2, c="r")
pl.plot(time_range, y, c="b")
pl.title("Reference signal")
pl.subplot(223)
pl.plot(time_range, e, c="r")
pl.title("Noise")
pl.xlabel("time")
pl.show()
def plot_prediction_MM(model, y_train, y_test, plot_title=''):
T = y_test.shape[0]
mx, vx, my, vy_noiseless, vy = model.predict_forward(T, prop_mode=PROP_MM)
T_train = y_train.shape[0]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.arange(T_train), y_train[:, 0], 'k+-')
ttest = np.arange(T_train, T_train+T)
# pdb.set_trace()
ax.plot(ttest, my[:, 0], '-', color='b')
ax.fill_between(
ttest,
my[:, 0] + 2*np.sqrt(vy_noiseless[:, 0]),
my[:, 0] - 2*np.sqrt(vy_noiseless[:, 0]),
alpha=0.3, edgecolor='b', facecolor='b')
ax.fill_between(
ttest,
my[:, 0] + 2*np.sqrt(vy[:, 0]),
my[:, 0] - 2*np.sqrt(vy[:, 0]),
alpha=0.1, edgecolor='b', facecolor='b')
ax.plot(ttest, y_test, 'ro')
ax.set_xlim([T_train-5, T_train + T])
plt.title(plot_title)
plt.savefig('/tmp/kink_pred_MM_'+plot_title+'.pdf')
# plt.savefig('/tmp/kink_pred_MM_'+plot_title+'.png')
def plot(m, Xtrain, ytrain):
xx = np.linspace(-0.5, 1.5, 100)[:, None]
mean, var = m.predict_y(xx)
mean = np.reshape(mean, (xx.shape[0], 1))
var = np.reshape(var, (xx.shape[0], 1))
if isinstance(m, aep.SDGPR):
zu = m.sgp_layers[0].zu
elif isinstance(m, vfe.SGPR_collapsed):
zu = m.zu
else:
zu = m.sgp_layer.zu
mean_u, var_u = m.predict_f(zu)
plt.figure()
plt.plot(Xtrain, ytrain, 'kx', mew=2)
plt.plot(xx, mean, 'b', lw=2)
# pdb.set_trace()
plt.fill_between(
xx[:, 0],
mean[:, 0] - 2 * np.sqrt(var[:, 0]),
mean[:, 0] + 2 * np.sqrt(var[:, 0]),
color='blue', alpha=0.2)
plt.errorbar(zu, mean_u, yerr=2 * np.sqrt(var_u), fmt='ro')
plt.xlim(-0.1, 1.1)
def plot(params_dir):
model_dirs = [name for name in os.listdir(params_dir)
if os.path.isdir(os.path.join(params_dir, name))]
df = defaultdict(list)
for model_dir in model_dirs:
df[re.sub('_bin_scaled_mono_True_ratio', '', model_dir)] = [
dd.io.load(path)['best_epoch']['validate_objective']
for path in glob.glob(os.path.join(
params_dir, model_dir) + '/*.h5')]
df = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in df.iteritems()]))
df.to_csv(os.path.basename(os.path.normpath(params_dir)))
plt.figure(figsize=(16, 4), dpi=300)
g = sns.boxplot(df)
g.set_xticklabels(df.columns, rotation=45)
plt.tight_layout()
plt.savefig('{}_errors_box_plot.png'.format(
os.path.join(IMAGES_DIRECTORY,
os.path.basename(os.path.normpath(params_dir)))))
def show_mpl(self, im, enhance=True, clear_fig=True):
if self._pylab is None:
import pylab
self._pylab = pylab
if self._render_figure is None:
self._render_figure = self._pylab.figure(1)
if clear_fig: self._render_figure.clf()
if enhance:
nz = im[im > 0.0]
nim = im / (nz.mean() + 6.0 * np.std(nz))
nim[nim > 1.0] = 1.0
nim[nim < 0.0] = 0.0
del nz
else:
nim = im
ax = self._pylab.imshow(nim[:,:,:3]/nim[:,:,:3].max(), origin='upper')
return ax
def plot_allsky_healpix(image, nside, fn, label = "", rotation = None,
take_log = True, resolution=512, cmin=None, cmax=None):
import matplotlib.figure
import matplotlib.backends.backend_agg
if rotation is None: rotation = np.eye(3).astype("float64")
img, count = pixelize_healpix(nside, image, resolution, resolution, rotation)
fig = matplotlib.figure.Figure((10, 5))
ax = fig.add_subplot(1,1,1,projection='aitoff')
if take_log: func = np.log10
else: func = lambda a: a
implot = ax.imshow(func(img), extent=(-np.pi,np.pi,-np.pi/2,np.pi/2),
clip_on=False, aspect=0.5, vmin=cmin, vmax=cmax)
cb = fig.colorbar(implot, orientation='horizontal')
cb.set_label(label)
ax.xaxis.set_ticks(())
ax.yaxis.set_ticks(())
canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
canvas.print_figure(fn)
return img, count
def plotRes(pre, real, test_x,l):
s = set(pre)
col = ['r','b','g','y','m']
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(0, len(s)):
index1 = pre == i
index2 = real == i
x1 = test_x[index1, :]
x2 = test_x[index2, :]
ax.scatter(x1[:,0],x1[:,1],color=col[i],marker='v',linewidths=0.5)
ax.scatter(x2[:,0],x2[:,1],color=col[i],marker='.',linewidths=12)
plt.title('learning rating='+str(l))
plt.legend(('c1:predict','c1:true',\
'c2:predict','c2:true',
'c3:predict','c3:true',
'c4:predict','c4:true',
'c5:predict','c5:true'), shadow = True, loc = (0.01, 0.4))
plt.show()
def __init__(self, data, **kwargs):
# Settings
self.show_ticks = kwargs.get("show_ticks", False)
self.show_values = kwargs.get("show_values", False)
self.show = kwargs.get("show", False)
self.labels = kwargs.get("labels", None)
# Setup plot
self.rows, self.cols = data.shape
self.fig = plt.figure()
self.plt_ax = self.fig.add_subplot(111)
self.cov_ax = self.plt_ax.matshow(np.array(data))
# Covariance matrix labels
self.label_values = self._add_data_labels(data)
self._add_axis_labels(data)
# Color bar
self.color_bar = self.fig.colorbar(self.cov_ax)
# Show plot
if self.show:
plt.show(block=False)
def test_project(self):
# Load points
points_file = join(test.TEST_DATA_PATH, "house/house.p3d")
points = np.loadtxt(points_file).T
# Setup camera
K = np.eye(3)
R = np.eye(3)
t = np.array([0, 0, 0])
camera = PinholeCameraModel(320, 240, K)
x = camera.project(points, R, t)
# Assert
self.assertEqual(x.shape, (3, points.shape[1]))
self.assertTrue(np.all(x[2, :] == 1.0))
# Plot projection
debug = False
# debug = True
if debug:
plt.figure()
plt.plot(x[0], x[1], 'k. ')
plt.show()
def plot(self, track, track_cam_states, estimates):
plt.figure()
# Feature
feature = T_global_camera * track.ground_truth
plt.plot(feature[0], feature[1],
marker="o", color="red", label="feature")
# Camera states
for cam_state in track_cam_states:
pos = T_global_camera * cam_state.p_G
plt.plot(pos[0], pos[1],
marker="o", color="blue", label="camera")
# Estimates
for i in range(len(estimates)):
cam_state = track_cam_states[i]
cam_pos = T_global_camera * cam_state.p_G
estimate = (T_global_camera * estimates[i]) + cam_pos
plt.plot(estimate[0], estimate[1],
marker="o", color="green")
plt.legend(loc=0)
plt.show()
def plot_1d(dataset, nbins, data):
with sns.axes_style('white'):
plt.rc('font', weight='bold')
plt.rc('grid', lw=2)
plt.rc('lines', lw=3)
plt.figure(1)
plt.hist(data, bins=np.arange(nbins+1), color='blue')
plt.ylabel('Count', weight='bold', fontsize=24)
xticks = list(plt.gca().get_xticks())
while (nbins-1) / float(xticks[-1]) < 1.1:
xticks = xticks[:-1]
while xticks[0] < 0:
xticks = xticks[1:]
xticks.append(nbins-1)
xticks = list(sorted(xticks))
plt.gca().set_xticks(xticks)
plt.xlim([int(np.ceil(-0.05*nbins)),int(np.ceil(nbins*1.05))])
plt.legend(loc='upper right')
plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight')
plt.clf()
plt.close()
def plot_1d(dataset, nbins):
data = np.loadtxt('experiments/uci/data/splits/{0}_all.csv'.format(dataset), skiprows=1, delimiter=',')[:,-1]
with sns.axes_style('white'):
plt.rc('font', weight='bold')
plt.rc('grid', lw=2)
plt.rc('lines', lw=3)
plt.figure(1)
plt.hist(data, bins=np.arange(nbins+1), color='blue')
plt.ylabel('Count', weight='bold', fontsize=24)
xticks = list(plt.gca().get_xticks())
while (nbins-1) / float(xticks[-1]) < 1.1:
xticks = xticks[:-1]
while xticks[0] < 0:
xticks = xticks[1:]
xticks.append(nbins-1)
xticks = list(sorted(xticks))
plt.gca().set_xticks(xticks)
plt.xlim([int(np.ceil(-0.05*nbins)),int(np.ceil(nbins*1.05))])
plt.legend(loc='upper right')
plt.savefig('plots/marginals-{0}.pdf'.format(dataset.replace('_','-')), bbox_inches='tight')
plt.clf()
plt.close()
def plot_entropy():
pylab.clf()
pylab.figure(num=None, figsize=(5, 4))
title = "Entropy $H(X)$"
pylab.title(title)
pylab.xlabel("$P(X=$coin will show heads up$)$")
pylab.ylabel("$H(X)$")
pylab.xlim(xmin=0, xmax=1.1)
x = np.arange(0.001, 1, 0.001)
y = -x * np.log2(x) - (1 - x) * np.log2(1 - x)
pylab.plot(x, y)
# pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in
# [0,1,2,3,4]])
pylab.autoscale(tight=True)
pylab.grid(True)
filename = "entropy_demo.png"
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def plot_clustering(x, y, title, mx=None, ymax=None, xmin=None, km=None):
pylab.figure(num=None, figsize=(8, 6))
if km:
pylab.scatter(x, y, s=50, c=km.predict(list(zip(x, y))))
else:
pylab.scatter(x, y, s=50)
pylab.title(title)
pylab.xlabel("Occurrence word 1")
pylab.ylabel("Occurrence word 2")
pylab.autoscale(tight=True)
pylab.ylim(ymin=0, ymax=1)
pylab.xlim(xmin=0, xmax=1)
pylab.grid(True, linestyle='-', color='0.75')
return pylab
def plot_feat_importance(feature_names, clf, name):
pylab.figure(num=None, figsize=(6, 5))
coef_ = clf.coef_
important = np.argsort(np.absolute(coef_.ravel()))
f_imp = feature_names[important]
coef = coef_.ravel()[important]
inds = np.argsort(coef)
f_imp = f_imp[inds]
coef = coef[inds]
xpos = np.array(list(range(len(coef))))
pylab.bar(xpos, coef, width=1)
pylab.title('Feature importance for %s' % (name))
ax = pylab.gca()
ax.set_xticks(np.arange(len(coef)))
labels = ax.set_xticklabels(f_imp)
for label in labels:
label.set_rotation(90)
filename = name.replace(" ", "_")
pylab.savefig(os.path.join(
CHART_DIR, "feat_imp_%s.png" % filename), bbox_inches="tight")
def plot_roc(auc_score, name, tpr, fpr, label=None):
pylab.clf()
pylab.figure(num=None, figsize=(5, 4))
pylab.grid(True)
pylab.plot([0, 1], [0, 1], 'k--')
pylab.plot(fpr, tpr)
pylab.fill_between(fpr, tpr, alpha=0.5)
pylab.xlim([0.0, 1.0])
pylab.ylim([0.0, 1.0])
pylab.xlabel('False Positive Rate')
pylab.ylabel('True Positive Rate')
pylab.title('ROC curve (AUC = %0.2f) / %s' %
(auc_score, label), verticalalignment="bottom")
pylab.legend(loc="lower right")
filename = name.replace(" ", "_")
pylab.savefig(
os.path.join(CHART_DIR, "roc_" + filename + ".png"), bbox_inches="tight")
def plotKChart(self, misClassDict, saveFigPath):
kList = []
misRateList = []
for k, misClassNum in misClassDict.iteritems():
kList.append(k)
misRateList.append(1.0 - 1.0/k*misClassNum)
fig = plt.figure(saveFigPath)
plt.plot(kList, misRateList, 'r--')
plt.title(saveFigPath)
plt.xlabel('k Num.')
plt.ylabel('Misclassified Rate')
plt.legend(saveFigPath)
plt.grid(True)
plt.savefig(saveFigPath)
plt.show()
################################### PART3 TEST ########################################
# ??
def show_feature_importance(gbdt, feature_names=None):
importance = gbdt.get_fscore(fmap='xgb.fmap')
importance = sorted(importance.items(), key=operator.itemgetter(1))
df = pd.DataFrame(importance, columns=['feature', 'fscore'])
df['fscore'] = df['fscore'] / df['fscore'].sum()
print "feature importance", df
if feature_names is not None:
used_features = df['feature']
unused_features = [f for f in feature_names if f not in used_features]
print "[IDF]Unused features:", str(unused_features)
plt.figure()
df.plot()
df.plot(kind='barh', x='feature', y='fscore', legend=False, figsize=(6, 10))
plt.title('XGBoost Feature Importance')
plt.xlabel('relative importance')
plt.gcf().savefig('feature_importance_xgb.png')
def figure_plotting_space():
"""
defines the plotting space
"""
fig = plt.figure(figsize=(10,10))
bar_height = 0.04
mini_gap = 0.03
gap = 0.05
graph_height = 0.24
axH = fig.add_axes([0.1,gap+3*graph_height+2.5*mini_gap,0.87,bar_height])
axS = fig.add_axes([0.1,gap+2*graph_height+2*mini_gap,0.87,graph_height])
axV = fig.add_axes([0.1,gap+graph_height+mini_gap,0.87,graph_height])
return fig, axH, axS, axV
def test_plot_timeseries2():
filename = abspath(join(testdir, 'plot_timeseries2.png'))
if isfile(filename):
os.remove(filename)
periods = 5
index = pd.date_range('1/1/2016', periods=periods, freq='H')
data = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]])
df = pd.DataFrame(data=data, index=index, columns=['A', 'B', 'C'])
tfilter = pd.Series(data = (df.index < index[3]), index = df.index)
plt.figure()
pecos.graphics.plot_timeseries(df,tfilter, yaxis_min=0, yaxis_max=20)
plt.savefig(filename, format='png')
plt.close()
assert_true(isfile(filename))
def test_plot_heatmap1():
filename = abspath(join(testdir, 'plot_heatmap1.png'))
if isfile(filename):
os.remove(filename)
periods = 5
index = pd.date_range('1/1/2016', periods=periods, freq='D')
data = np.random.rand(periods, 4)
df = pd.DataFrame(data=data, index=index, columns=['A', 'B', 'C', 'D'])
plt.figure()
pecos.graphics.plot_heatmap(df)
plt.savefig(filename, format='png', bbox_inches='tight', pad_inches = 0)
plt.close()
assert_true(isfile(filename))
def test_plot_doy_heatmap1():
filename = abspath(join(testdir, 'plot_doy_heatmap1.png'))
if isfile(filename):
os.remove(filename)
periods = 5*24 # 5 days
index = pd.date_range('3/1/2016', periods=periods, freq='H')
data = np.random.rand(periods)
df = pd.DataFrame(data=data, index=index, columns=['A'])
plt.figure()
pecos.graphics.plot_doy_heatmap(df['A'])
plt.savefig(filename, format='png')
plt.close()
assert_true(isfile(filename))
def test_plot_doy_heatmap2():
filename = abspath(join(testdir, 'plot_doy_heatmap2.png'))
if isfile(filename):
os.remove(filename)
periods = 365*12
index = pd.date_range('1/1/2016', periods=periods, freq='2H')
data = np.random.rand(periods)
df = pd.DataFrame(data=data, index=index, columns=['A'])
overlay = pd.DataFrame(index=[1,100,200,300,365],
data={'A': [40000,20000,60000,10000,5000],
'B': [60000,70000,75000,50000,65000]})
plt.figure()
pecos.graphics.plot_doy_heatmap(df['A'], cmap='gray', overlay=overlay)
plt.savefig(filename, format='png')
plt.close()
assert_true(isfile(filename))
def show_samples(y, ndim, nb=10, cmap=''):
if ndim == 4:
for i in range(nb**2):
plt.subplot(nb, nb, i+1)
plt.imshow(y[i], cmap=cmap, interpolation='none')
plt.axis('off')
else:
x = y[0]
y = y[1]
plt.figure(0)
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(x[i], cmap=cmap, interpolation='none')
plt.axis('off')
plt.figure(1)
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(y[i], cmap=cmap, interpolation='none')
plt.axis('off')
plt.show()
def plot_penalty_vl(debug, tag, fold_exp):
plt.close("all")
vl = np.array(debug["penalty"])
fig = plt.figure(figsize=(15, 10.8), dpi=300)
names = debug["names"]
for i in range(vl.shape[1]):
if vl.shape[1] > 1:
plt.plot(vl[:, i], label="layer_"+str(names[i]))
else:
plt.plot(vl[:], label="layer_"+str(names[i]))
plt.xlabel("mini-batchs")
plt.ylabel("value of penlaty")
plt.title(
"Penalty value over layers:" + "_".join([str(k) for k in names]) +
". tag:" + tag)
plt.legend(loc='upper right', fancybox=True, shadow=True, prop={'size': 8})
plt.grid(True)
fig.savefig(fold_exp+"/penalty.png", bbox_inches='tight')
plt.close('all')
del 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
def plot_roc(y_test, y_pred, label=''):
"""Compute ROC curve and ROC area"""
fpr, tpr, _ = roc_curve(y_test, y_pred)
roc_auc = auc(fpr, tpr)
# Plot of a ROC curve for a specific class
plt.figure()
plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic' + label)
plt.legend(loc="lower right")
plt.show()
def plot_feat_importance(feature_names, clf, name):
pylab.figure(num=None, figsize=(6, 5))
coef_ = clf.coef_
important = np.argsort(np.absolute(coef_.ravel()))
f_imp = feature_names[important]
coef = coef_.ravel()[important]
inds = np.argsort(coef)
f_imp = f_imp[inds]
coef = coef[inds]
xpos = np.array(list(range(len(coef))))
pylab.bar(xpos, coef, width=1)
pylab.title('Feature importance for %s' % (name))
ax = pylab.gca()
ax.set_xticks(np.arange(len(coef)))
labels = ax.set_xticklabels(f_imp)
for label in labels:
label.set_rotation(90)
filename = name.replace(" ", "_")
pylab.savefig(os.path.join(
CHART_DIR, "feat_imp_%s.png" % filename), bbox_inches="tight")
def plot_feat_importance(feature_names, clf, name):
pylab.figure(num=None, figsize=(6, 5))
coef_ = clf.coef_
important = np.argsort(np.absolute(coef_.ravel()))
f_imp = feature_names[important]
coef = coef_.ravel()[important]
inds = np.argsort(coef)
f_imp = f_imp[inds]
coef = coef[inds]
xpos = np.array(list(range(len(coef))))
pylab.bar(xpos, coef, width=1)
pylab.title('Feature importance for %s' % (name))
ax = pylab.gca()
ax.set_xticks(np.arange(len(coef)))
labels = ax.set_xticklabels(f_imp)
for label in labels:
label.set_rotation(90)
filename = name.replace(" ", "_")
pylab.savefig(os.path.join(
CHART_DIR, "feat_imp_%s.png" % filename), bbox_inches="tight")
def plot(embeddings, labels):
assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
pylab.figure(figsize=(15, 15)) # in inches
for i, label in enumerate(labels):
x, y = embeddings[i, :]
pylab.scatter(x, y)
pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
ha='right', va='bottom')
pylab.show()
def CO_ratio(self,ifig,ixaxis):
"""
plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis
Parameters
----------
ifig : integer
Figure number in which to plot
ixaxis : string
what quantity is to be on the x-axis, either 'time' or 'model'
The default is 'model'
"""
def C_O(model):
surface_c12=model.get('surface_c12')
surface_o16=model.get('surface_o16')
CORatio=old_div((surface_c12*4.),(surface_o16*3.))
return CORatio
if ixaxis=='time':
xax=self.get('star_age')
elif ixaxis=='model':
xax=self.get('model_number')
else:
raise IOError("ixaxis not recognised")
pl.figure(ifig)
pl.plot(xax,C_O(self))
def t_lumi(self,num_frame,xax):
"""
Luminosity evolution as a function of time or model.
Parameters
----------
num_frame : integer
Number of frame to plot this plot into.
xax : string
Either model or time to indicate what is to be used on the
x-axis
"""
pyl.figure(num_frame)
if xax == 'time':
xaxisarray = self.get('star_age')
elif xax == 'model':
xaxisarray = self.get('model_number')
else:
print('kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"')
logLH = self.get('log_LH')
logLHe = self.get('log_LHe')
pyl.plot(xaxisarray,logLH,label='L_(H)')
pyl.plot(xaxisarray,logLHe,label='L(He)')
pyl.ylabel('log L')
pyl.legend(loc=2)
if xax == 'time':
pyl.xlabel('t / yrs')
elif xax == 'model':
pyl.xlabel('model number')
def t_surf_parameter(self, num_frame, xax):
"""
Surface parameter evolution as a function of time or model.
Parameters
----------
num_frame : integer
Number of frame to plot this plot into.
xax : string
Either model or time to indicate what is to be used on the
x-axis
"""
pyl.figure(num_frame)
if xax == 'time':
xaxisarray = self.get('star_age')
elif xax == 'model':
xaxisarray = self.get('model_number')
else:
print('kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"')
logL = self.get('log_L')
logTeff = self.get('log_Teff')
pyl.plot(xaxisarray,logL,'-k',label='log L')
pyl.plot(xaxisarray,logTeff,'-k',label='log Teff')
pyl.ylabel('log L, log Teff')
pyl.legend(loc=2)
if xax == 'time':
pyl.xlabel('t / yrs')
elif xax == 'model':
pyl.xlabel('model number')
def example_plot1():
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
x = np.linspace(1., 8., 30)
ax.set_title('Title!')
ax.plot(x, x ** 1.5, color='k', ls='solid', label='line 1')
ax.plot(x, 20/x, color='0.50', ls='dashed', label='line 2')
ax.set_xlabel('Time (s)')
ax.set_ylabel('Temperature (K)')
ax.legend(loc='upper left')
fig.tight_layout()
return [fig], ['example_1']
# Should make an OO example where __init__ sets up data, then methods plot it different ways. Should be able to just pass methods along...
def rasta_plp_extractor(x, sr, plp_order=0, do_rasta=True):
spec = log_power_spectrum_extractor(x, int(sr*0.02), int(sr*0.01), 'hamming', False)
bark_filters = int(np.ceil(freq2bark(sr//2)))
wts = get_fft_bark_mat(sr, int(sr*0.02), bark_filters)
'''
plt.figure()
plt.subplot(211)
plt.imshow(wts)
plt.subplot(212)
plt.hold(True)
for i in range(18):
plt.plot(wts[i, :])
plt.show()
'''
bark_spec = np.matmul(wts, spec)
if do_rasta:
bark_spec = np.where(bark_spec == 0.0, np.finfo(float).eps, bark_spec)
log_bark_spec = np.log(bark_spec)
rasta_log_bark_spec = rasta_filt(log_bark_spec)
bark_spec = np.exp(rasta_log_bark_spec)
post_spec = postaud(bark_spec, sr/2.)
if plp_order > 0:
lpcas = do_lpc(post_spec, plp_order)
# lpcas = do_lpc(spec, plp_order) # just for test
else:
lpcas = post_spec
return lpcas
def plot(l, samp, w1, w2, cor):
time_range = numpy.arange(0, l) * (1.0 / samp)
pl.figure(1)
pl.subplot(211)
pl.plot(time_range, w1)
pl.subplot(212)
pl.plot(time_range, w2, c="r")
pl.xlabel("time")
pl.figure(2)
pl.plot(time_range, cor)
pl.show()
def main():
sampling, maxvalue, wave_data = record.record()
# Pick out two channels for our study.
w1, w2 = wave_data[1:3]
nframes = w1.shape[0]
# Cut one channel in the tail, while the other in the head,
# to guarantee same length and first delays second.
cut_time_len = 0.2 # second
cut_len = int(cut_time_len * sampling)
wp1 = w1[:-cut_len]
wp2 = w2[cut_len:]
# Get their reduced (amplitude) version, and
# calculate correlation.
a = numpy.array(wp1, dtype=numpy.double) / maxvalue
b = numpy.array(wp2, dtype=numpy.double) / maxvalue
delay_time = delay.fst_delay_snd(a, b, sampling)
# Plot the channels, also the correlation.
time_range = numpy.arange(0, nframes - cut_len)*(1.0/sampling)
# Still shows the original signal
pl.figure(1)
pl.subplot(211)
pl.plot(time_range, wp1)
pl.subplot(212)
pl.plot(time_range, wp2, c="r")
pl.xlabel("time")
pl.show()
# Print delay
print("Chan 1 delay chan 2 by {0}".format(delay_time))
def main():
sampling, maxvalue, wave_data = record.record()
# Pick out two channels for our study.
w1, w2 = wave_data[0:2]
nframes = w1.shape[0]
# Pad one channel in the head, while the other in the tail,
# to guarantee same length.
pad_time_len = 0.01 # second
pad_len = int(pad_time_len * sampling)
pad_arr = numpy.zeros(pad_len)
wp1 = numpy.concatenate((pad_arr, w1))
wp2 = numpy.concatenate((w2, pad_arr))
# Get their reduced (amplitude) version, and
# calculate correlation.
a = numpy.array(wp1, dtype=numpy.double) / maxvalue
b = numpy.array(wp2, dtype=numpy.double) / maxvalue
delay_time = delay.fst_delay_snd(a, b, sampling)
# Plot the channels, also the correlation.
time_range = numpy.arange(0, nframes + pad_len)*(1.0/sampling)
# Still shows the original signal
pl.figure(1)
pl.subplot(211)
pl.plot(time_range, wp1)
pl.subplot(212)
pl.plot(time_range, wp2, c="r")
pl.xlabel("time")
pl.show()
# Print delay
print("Chan 1 delay chan 2 by {0}".format(delay_time))
def plot_channel(audio, sampling):
channels, nframes = audio.shape[0], audio.shape[1]
time_range = numpy.arange(0, nframes) * (1.0 / sampling)
for i in range(1, channels + 1):
pl.figure(i)
pl.plot(time_range, audio[i - 1])
pl.xlabel("time{0}".format(i))
pl.show()
def plot_angular_velocities(title,
angular_velocities,
angular_velocities_filtered,
block=True):
fig = plt.figure()
title_position = 1.05
fig.suptitle(title, fontsize='24')
a1 = plt.subplot(1, 2, 1)
a1.set_title(
"Angular Velocities Before Filtering \nvx [red], vy [green], vz [blue]",
y=title_position)
plt.plot(angular_velocities[:, 0], c='r')
plt.plot(angular_velocities[:, 1], c='g')
plt.plot(angular_velocities[:, 2], c='b')
a2 = plt.subplot(1, 2, 2)
a2.set_title(
"Angular Velocities After Filtering \nvx [red], vy [green], vz [blue]", y=title_position)
plt.plot(angular_velocities_filtered[:, 0], c='r')
plt.plot(angular_velocities_filtered[:, 1], c='g')
plt.plot(angular_velocities_filtered[:, 2], c='b')
plt.subplots_adjust(left=0.025, right=0.975, top=0.8, bottom=0.05)
if plt.get_backend() == 'TkAgg':
mng = plt.get_current_fig_manager()
max_size = mng.window.maxsize()
max_size = (max_size[0], max_size[1] * 0.45)
mng.resize(*max_size)
plt.show(block=block)
def plot_mondrian_kernel_vs_mondrian_forest(lifetime_max, res):
""" Plots training and test set error of Mondrian kernel and Mondrian forest based on the same set of M Mondrian samples.
This procedure takes as input a dictionary res, returned by the evaluate_all_lifetimes procedure in mondrian_kernel.py.
"""
times = res['times']
forest_train = res['forest_train']
forest_test = res['forest_test']
kernel_train = res['kernel_train']
kernel_test = res['kernel_test']
# set up test error plot
fig = plt.figure(figsize=(7, 4))
ax = fig.add_subplot('111')
remove_chartjunk(ax)
ax.set_xlabel('lifetime $\lambda$')
ax.set_ylabel('relative error [\%]')
ax.yaxis.grid(b=True, which='major', linestyle='dotted', lw=0.5, color='black', alpha=0.3)
ax.set_xscale('log')
ax.set_xlim((1e-8, lifetime_max))
ax.set_ylim((0, 25))
rasterized = False
ax.plot(times, forest_test, drawstyle="steps-post", ls='-', lw=2, color=tableau20(6), label='"M. forest" (test)', rasterized=rasterized)
ax.plot(times, forest_train, drawstyle="steps-post", ls='-', color=tableau20(7), label='"M. forest" (train)', rasterized=rasterized)
ax.plot(times, kernel_test, drawstyle="steps-post", ls='-', lw=2, color=tableau20(4), label='M. kernel (test)', rasterized=rasterized)
ax.plot(times, kernel_train, drawstyle="steps-post", ls='-', color=tableau20(5), label='M. kernel (train)', rasterized=rasterized)
ax.legend(bbox_to_anchor=[1.15, 1.05], frameon=False)
def plot_kernel_vs_forest_weights(y, res):
""" Plots the weights learned by Mondrian kernel and Mondrian forest based on the same set of M Mondrian samples.
This procedure takes as input a dictionary res, returned by the evaluate_all_lifetimes procedure in mondrian_kernel.py.
"""
w_forest = res['w_forest']
w_kernel = res['w_kernel']
# plot weights against each other
fig1 = plt.figure(figsize=(8, 4))
ax1 = fig1.add_subplot('121')
ax1.set_xlabel('weights learned by "Mondrian forest"')
ax1.set_ylabel('weights learned by Mondrian kernel')
ax1.scatter(w_forest, w_kernel, marker='.', color=tableau20(16))
xl = ax1.get_xlim()
yl = ax1.get_ylim()
lims = [
np.min([xl, yl]), # min of both axes
np.max([xl, yl]), # max of both axes
]
ax1.plot(lims, lims, '--', color='black', alpha=0.75, zorder=0)
ax1.set_xlim(xl)
#ax1.set_ylim(yl)
ax1.set_ylim((-60, 60))
# plot histogram of weight values (and training targets)
ax2 = fig1.add_subplot('122')
ax2.set_xlabel('values')
ax2.set_ylabel('value frequency')
bins = np.linspace(-100, 20, 50)
ax2.hist(w_forest, bins=bins, histtype='stepfilled', normed=True, color=tableau20(6), alpha=0.5,
label='M. forest weights $\mathbf{w}$')
ax2.hist(w_kernel, bins=bins, histtype='stepfilled', normed=True, color=tableau20(4), alpha=0.5,
label='M. kernel weights $\mathbf{w}$')
ax2.hist(y - np.mean(y), bins=bins, histtype='stepfilled', normed=True, color=tableau20(8), alpha=0.5,
label='training targets $\mathbf{y}$')
ax2.set_ylim((0.0, 0.16))
ax2.legend(frameon=False, loc='upper left')
fig1.tight_layout()
def plot_latent(model, y, plot_title=''):
# make prediction on some test inputs
N_test = 300
C = model.get_hypers()['C_emission'][0, 0]
x_test = np.linspace(-10, 8, N_test) / C
x_test = np.reshape(x_test, [N_test, 1])
if isinstance(model, aep.SGPSSM) or isinstance(model, vfe.SGPSSM):
zu = model.dyn_layer.zu
else:
zu = model.sgp_layer.zu
mu, vu = model.predict_f(zu)
# mu, Su = model.dyn_layer.mu, model.dyn_layer.Su
mf, vf = model.predict_f(x_test)
my, vy = model.predict_y(x_test)
# plot function
fig = plt.figure()
ax = fig.add_subplot(111)
# ax.plot(x_test[:,0], kink_true(x_test[:,0]), '-', color='k')
ax.plot(C*x_test[:,0], my[:,0], '-', color='r', label='y')
ax.fill_between(
C*x_test[:,0],
my[:,0] + 2*np.sqrt(vy[:, 0]),
my[:,0] - 2*np.sqrt(vy[:, 0]),
alpha=0.2, edgecolor='r', facecolor='r')
ax.plot(
y[0:model.N-1],
y[1:model.N],
'r+', alpha=0.5)
mx, vx = model.get_posterior_x()
ax.set_xlabel(r'$x_{t-1}$')
ax.set_ylabel(r'$x_{t}$')
plt.title(plot_title)
plt.savefig('/tmp/lincos_'+plot_title+'.png')
# generate a dataset from the lincos function above
def plot_latent(model, y, plot_title=''):
# make prediction on some test inputs
N_test = 200
C = model.get_hypers()['C_emission'][0, 0]
x_test = np.linspace(-4, 6, N_test) / C
x_test = np.reshape(x_test, [N_test, 1])
zu = model.dyn_layer.zu
mu, vu = model.predict_f(zu)
# mu, Su = model.dyn_layer.mu, model.dyn_layer.Su
mf, vf = model.predict_f(x_test)
my, vy = model.predict_y(x_test)
# plot function
fig = plt.figure()
ax = fig.add_subplot(111)
# ax.plot(x_test[:,0], kink_true(x_test[:,0]), '-', color='k')
ax.plot(C*x_test[:,0], my[:,0], '-', color='r', label='y')
ax.fill_between(
C*x_test[:,0],
my[:,0] + 2*np.sqrt(vy[:, 0]),
my[:,0] - 2*np.sqrt(vy[:, 0]),
alpha=0.2, edgecolor='r', facecolor='r')
# ax.plot(zu, mu, 'ob')
# ax.errorbar(zu, mu, yerr=3*np.sqrt(vu), fmt='ob')
# ax.plot(x_test[:,0], mf[:,0], '-', color='b')
# ax.fill_between(
# x_test[:,0],
# mf[:,0] + 2*np.sqrt(vf[:,0]),
# mf[:,0] - 2*np.sqrt(vf[:,0]),
# alpha=0.2, edgecolor='b', facecolor='b')
ax.plot(
y[0:model.N-1],
y[1:model.N],
'r+', alpha=0.5)
mx, vx = model.get_posterior_x()
ax.set_xlabel(r'$x_{t-1}$')
ax.set_ylabel(r'$x_{t}$')
ax.set_xlim([-4, 6])
# ax.set_ylim([-7, 7])
plt.title(plot_title)
# plt.savefig('/tmp/kink_'+plot_title+'.pdf')
plt.savefig('/tmp/kink_'+plot_title+'.png')
def plot_prediction_MC(model, y_train, y_test, plot_title=''):
T = y_test.shape[0]
x_samples, my, vy = model.predict_forward(T, prop_mode=PROP_MC)
T_train = y_train.shape[0]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.arange(T_train), y_train[:, 0], 'k+-')
ttest = np.arange(T_train, T_train+T)
ttest = np.reshape(ttest, [T, 1])
loglik, ranks = compute_log_lik(np.exp(2*model.sn), y_test, my[:, :, 0].T)
red = 0.1
green = 0. * red
blue = 1. - red
color = np.array([red, green, blue]).T
for k in np.argsort(ranks):
ax.plot(ttest, my[:, k, 0], '-', color=color*ranks[k], alpha=0.5)
# ax.plot(np.tile(ttest, [1, my.shape[1]]), my[:, :, 0], '-x', color='r', alpha=0.3)
# ax.plot(np.tile(ttest, [1, my.shape[1]]), x_samples[:, :, 0], 'x', color='m', alpha=0.3)
ax.plot(ttest, y_test, 'ro')
ax.set_xlim([T_train-5, T_train + T])
plt.title(plot_title)
plt.savefig('/tmp/kink_pred_MC_'+plot_title+'.pdf')
# plt.savefig('/tmp/kink_pred_MC_'+plot_title+'.png')
# generate a dataset from the kink function above