def plot_x_y_yhat(x, y, y_hat, xsz, ysz, binz=False):
"""Plot x, y and y_hat side by side."""
plt.close("all")
f = plt.figure(figsize=(15, 10.8), dpi=300)
gs = gridspec.GridSpec(1, 3)
if binz:
y_hat = (y_hat > 0.5) * 1.
ims = [x, y, y_hat]
tils = [
"x:" + str(xsz) + "x" + str(xsz),
"y:" + str(ysz) + "x" + str(ysz),
"yhat:" + str(ysz) + "x" + str(ysz)]
for n, ti in zip([0, 1, 2], tils):
f.add_subplot(gs[n])
if n == 0:
plt.imshow(ims[n], cmap=cm.Greys_r)
else:
plt.imshow(ims[n], cmap=cm.Greys_r)
plt.title(ti)
return f
python类figure()的实例源码
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()
demo_mi.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
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")
plot_kmeans_example.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
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
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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")
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
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