def plot_feat_hist(data_name_list, filename=None):
if len(data_name_list) > 1:
assert filename is not None
pylab.figure(num=None, figsize=(8, 6))
num_rows = int(1 + (len(data_name_list) - 1) / 2)
num_cols = int(1 if len(data_name_list) == 1 else 2)
pylab.figure(figsize=(5 * num_cols, 4 * num_rows))
for i in range(num_rows):
for j in range(num_cols):
pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
x, name = data_name_list[i * num_cols + j]
pylab.title(name)
pylab.xlabel('Value')
pylab.ylabel('Fraction')
# the histogram of the data
max_val = np.max(x)
if max_val <= 1.0:
bins = 50
elif max_val > 50:
bins = 50
else:
bins = max_val
n, bins, patches = pylab.hist(
x, bins=bins, normed=1, alpha=0.75)
pylab.grid(True)
if not filename:
filename = "feat_hist_%s.png" % name.replace(" ", "_")
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
python类subplot()的实例源码
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def plot_feat_hist(data_name_list, filename=None):
pylab.clf()
num_rows = 1 + (len(data_name_list) - 1) / 2
num_cols = 1 if len(data_name_list) == 1 else 2
pylab.figure(figsize=(5 * num_cols, 4 * num_rows))
for i in range(num_rows):
for j in range(num_cols):
pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
x, name = data_name_list[i * num_cols + j]
pylab.title(name)
pylab.xlabel('Value')
pylab.ylabel('Density')
# the histogram of the data
max_val = np.max(x)
if max_val <= 1.0:
bins = 50
elif max_val > 50:
bins = 50
else:
bins = max_val
n, bins, patches = pylab.hist(
x, bins=bins, normed=1, facecolor='green', alpha=0.75)
pylab.grid(True)
if not filename:
filename = "feat_hist_%s.png" % name
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def fancy_show(y, cmap=''):
x = y[0]
y = y[1]
plt.figure(0)
for i in range(100):
plt.subplot(10, 10, i+1)
plt.imshow(x[i], cmap=cmap, interpolation='none')
plt.axis('off')
plt.figure(1)
for i in range(100):
plt.subplot(10, 10, i+1)
plt.imshow(y[i], cmap=cmap, interpolation='none')
plt.axis('off')
plt.show()
def __init__(self, fig, gs, time_window=500, labels=None, alphas=None):
self._fig = fig
self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs)
self._ax = plt.subplot(self._gs[0])
self._time_window = time_window
self._labels = labels
self._alphas = alphas
self._init = False
if self._labels:
self.init(len(self._labels))
self._fig.canvas.draw()
self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
def __init__(self, fig, gs, num_plots, rows=None, cols=None):
if cols is None:
cols = int(np.floor(np.sqrt(num_plots)))
if rows is None:
rows = int(np.ceil(float(num_plots)/cols))
assert num_plots <= rows*cols, 'Too many plots to put into gridspec.'
self._fig = fig
self._gs = gridspec.GridSpecFromSubplotSpec(8, 1, subplot_spec=gs)
self._gs_legend = self._gs[0:1, 0]
self._gs_plot = self._gs[1:8, 0]
self._ax_legend = plt.subplot(self._gs_legend)
self._ax_legend.get_xaxis().set_visible(False)
self._ax_legend.get_yaxis().set_visible(False)
self._gs_plots = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=self._gs_plot)
self._axarr = [plt.subplot(self._gs_plots[i], projection='3d') for i in range(num_plots)]
self._lims = [None for i in range(num_plots)]
self._plots = [[] for i in range(num_plots)]
for ax in self._axarr:
ax.tick_params(pad=0)
ax.locator_params(nbins=5)
for item in (ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()):
item.set_fontsize(10)
self._fig.canvas.draw()
self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
def plot_representations(X, y, title):
"""Plot distributions and thier labels."""
x_min, x_max = np.min(X, 0), np.max(X, 0)
X = (X - x_min) / (x_max - x_min)
f = plt.figure(figsize=(15, 10.8), dpi=300)
# ax = plt.subplot(111)
for i in range(X.shape[0]):
plt.text(X[i, 0], X[i, 1], str(y[i]),
color=plt.cm.Set1(y[i] / 10.),
fontdict={'weight': 'bold', 'size': 9})
# if hasattr(offsetbox, 'AnnotationBbox'):
# # only print thumbnails with matplotlib > 1.0
# shown_images = np.array([[1., 1.]]) # just something big
# for i in range(digits.data.shape[0]):
# dist = np.sum((X[i] - shown_images) ** 2, 1)
# if np.min(dist) < 4e-3:
# # don't show points that are too close
# continue
# shown_images = np.r_[shown_images, [X[i]]]
# imagebox = offsetbox.AnnotationBbox(
# offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r),
# X[i])
# ax.add_artist(imagebox)
plt.xticks([]), plt.yticks([])
if title is not None:
plt.title(title)
return f
def plot_feat_hist(data_name_list, filename=None):
if len(data_name_list)>1:
assert filename is not None
pylab.figure(num=None, figsize=(8, 6))
num_rows = 1 + (len(data_name_list) - 1) / 2
num_cols = 1 if len(data_name_list) == 1 else 2
pylab.figure(figsize=(5 * num_cols, 4 * num_rows))
for i in range(num_rows):
for j in range(num_cols):
pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
x, name = data_name_list[i * num_cols + j]
pylab.title(name)
pylab.xlabel('Value')
pylab.ylabel('Fraction')
# the histogram of the data
max_val = np.max(x)
if max_val <= 1.0:
bins = 50
elif max_val > 50:
bins = 50
else:
bins = max_val
n, bins, patches = pylab.hist(
x, normed=1, facecolor='blue', alpha=0.75)
pylab.grid(True)
if not filename:
filename = "feat_hist_%s.png" % name.replace(" ", "_")
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def plot_feat_hist(data_name_list, filename=None):
if len(data_name_list)>1:
assert filename is not None
pylab.figure(num=None, figsize=(8, 6))
num_rows = 1 + (len(data_name_list) - 1) / 2
num_cols = 1 if len(data_name_list) == 1 else 2
pylab.figure(figsize=(5 * num_cols, 4 * num_rows))
for i in range(num_rows):
for j in range(num_cols):
pylab.subplot(num_rows, num_cols, 1 + i * num_cols + j)
x, name = data_name_list[i * num_cols + j]
pylab.title(name)
pylab.xlabel('Value')
pylab.ylabel('Fraction')
# the histogram of the data
max_val = np.max(x)
if max_val <= 1.0:
bins = 50
elif max_val > 50:
bins = 50
else:
bins = max_val
n, bins, patches = pylab.hist(
x, normed=1, facecolor='blue', alpha=0.75)
pylab.grid(True)
if not filename:
filename = "feat_hist_%s.png" % name.replace(" ", "_")
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
def plotImgPatchPrototypes(doShowNow=True):
from matplotlib import pylab
pylab.figure()
for kk in range(K):
pylab.subplot(2, 4, kk + 1)
Xp = makeImgPatchPrototype(D, kk)
pylab.imshow(Xp, interpolation='nearest')
if doShowNow:
pylab.show()
def plotTrueCovMats(doShowNow=True):
from matplotlib import pylab
pylab.figure()
for kk in range(K):
pylab.subplot(2, 4, kk + 1)
pylab.imshow(Sigma[kk], interpolation='nearest')
if doShowNow:
pylab.show()
def _viz_Gauss(curModel, propModel, Plan,
curELBO=None, propELBO=None, block=False, **kwargs):
from ..viz import GaussViz
from matplotlib import pylab
pylab.figure()
h = pylab.subplot(1, 2, 1)
GaussViz.plotGauss2DFromHModel(curModel, compsToHighlight=Plan['ktarget'])
h = pylab.subplot(1, 2, 2)
newCompIDs = np.arange(curModel.obsModel.K, propModel.obsModel.K)
GaussViz.plotGauss2DFromHModel(propModel, compsToHighlight=newCompIDs)
pylab.show(block=block)
def plot_convergence_data(scores, errors):
subplt_2 = plt.subplot(3, 1, 2)
score_line, = plt.plot(scores, color="blue", label="score")
plt.title("Best Score")
plt.legend()
subplt_3 = plt.subplot(3, 1, 3)
error_line, = plt.plot(errors, color="red", label="error")
plt.title("Best Error")
plt.legend()
return score_line, error_line, subplt_2, subplt_3
def plot_convergence_data(scores, errors):
subplt_2 = plt.subplot(3, 1, 2)
score_line, = plt.plot(scores, color="blue", label="score")
plt.title("Best Score")
plt.legend()
subplt_3 = plt.subplot(3, 1, 3)
error_line, = plt.plot(errors, color="red", label="error")
plt.title("Best Error")
plt.legend()
return score_line, error_line, subplt_2, subplt_3
def plot_projections(points):
num_images = len(points)
plt.figure()
plt.suptitle('3D to 2D Projections', fontsize=16)
for i in range(num_images):
plt.subplot(1, num_images, i+1)
ax = plt.gca()
ax.set_aspect('equal')
ax.plot(points[i][0], points[i][1], 'r.')
def plot_profiles_to_file(annot, pntr, ups=200, smooth_param=50):
pp = PdfPages(options.save_path + 'Figures/individual_signals.pdf')
clrs_ = ['red', 'blue', 'black', 'orange', 'magenta', 'cyan']
vec_sense = {}
vec_antisense = {}
# for qq in tq(range(annot.shape[0])):
for qq in tq(range(100)):
chname = annot['chr'].iloc[qq]
if annot['strand'].iloc[qq] == '+':
start = annot['start'].iloc[qq] - ups
stop = annot['end'].iloc[qq]
for key in pntr.keys():
vec_sense[key] = pntr[key][0].get_nparray(chname, start, stop - 1)
vec_antisense[key] = pntr[key][1].get_nparray(chname, start, stop - 1)
xran = np.arange(start, stop)
else:
start = annot['start'].iloc[qq]
stop = annot['end'].iloc[qq] + ups
for key in pntr.keys():
vec_sense[key] = np.flipud(pntr[key][1].get_nparray(chname, start, stop))
vec_antisense[key] = np.flipud(pntr[key][0].get_nparray(chname, start, stop))
xran = np.arange(stop, start, -1)
ax = {}
fig = pl.figure()
pl.title(annot['name'].iloc[qq])
for i, key in enumerate(pntr.keys()):
sm_vec_se = sm.smooth(vec_sense[key], smooth_param)[(smooth_param - 1):-(smooth_param - 1)]
sm_vec_as = sm.smooth(vec_antisense[key], smooth_param)[(smooth_param - 1):-(smooth_param - 1)]
ax[key] = pl.subplot(len(pntr), 1, i+1)
ax[key].plot(xran, vec_sense[key], label=key, color=clrs_[i], alpha=0.5)
ax[key].plot(xran, -vec_antisense[key], color=clrs_[i], alpha=0.5)
ax[key].plot(xran, sm_vec_se, color=clrs_[i], linewidth=2)
ax[key].plot(xran, -sm_vec_as, color=clrs_[i], linewidth=2)
ax[key].legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), fontsize=6, ncol=1)
pp.savefig()
pl.close()
pp.close()
for pn in pntr.values():
pn[0].close()
pn[1].close()
def lms(x1: numpy.array, x2: numpy.array, N: int):
# Verify argument shape.
s1, s2 = x1.shape, x2.shape
if len(s1) != 1 or len(s2) != 1 or s1[0] != s2[0]:
raise Exception("Argument shape invalid, in 'lms' function")
l = s1[0]
# Coefficient matrix
W = numpy.mat(numpy.zeros([1, 2 * N + 1]))
# Coefficient (time) matrix
Wt = numpy.mat(numpy.zeros([l, 2 * N + 1]))
# Feedback (time) matrix
y = numpy.mat(numpy.zeros([l, 1]))
# Error (time) matrix
e = numpy.mat(numpy.zeros([l, 1]))
# Traverse channel data
for i in range(N, l-N):
x1_vec = numpy.asmatrix(x1[i-N:i+N+1])
y[i] = x1_vec * numpy.transpose(W)
e[i] = x2[i] - y[i]
W += mu * e[i] * x1_vec
Wt[i] = W
# Find the coefficient matrix which has max maximum.
Wt_maxs = numpy.max(Wt, axis=1)
row_idx = numpy.argmax(Wt_maxs)
max_W = Wt[row_idx]
delay_count = numpy.argmax(max_W) - N
# 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.figure(2)
time_range2 = numpy.arange(-N, N + 1)
pl.plot(time_range2, numpy.transpose(max_W))
pl.title("Maximal coefficient vector")
pl.show()
return delay_count
time_alignment_plotting_tools.py 文件源码
项目:hand_eye_calibration
作者: ethz-asl
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def plot_results(times_A, times_B, signal_A, signal_B,
convoluted_signals, time_offset, block=True):
fig = plt.figure()
title_position = 1.05
matplotlib.rcParams.update({'font.size': 20})
# fig.suptitle("Time Alignment", fontsize='24')
a1 = plt.subplot(1, 3, 1)
a1.get_xaxis().get_major_formatter().set_useOffset(False)
plt.ylabel('angular velocity norm [rad]')
plt.xlabel('time [s]')
a1.set_title(
"Before Time Alignment", y=title_position)
plt.hold("on")
min_time = min(np.amin(times_A), np.amin(times_B))
times_A_zeroed = times_A - min_time
times_B_zeroed = times_B - min_time
plt.plot(times_A_zeroed, signal_A, c='r')
plt.plot(times_B_zeroed, signal_B, c='b')
times_A_shifted = times_A + time_offset
a3 = plt.subplot(1, 3, 2)
a3.get_xaxis().get_major_formatter().set_useOffset(False)
plt.ylabel('correlation')
plt.xlabel('sample idx offset')
a3.set_title(
"Correlation Result \n[Ideally has a single dominant peak.]",
y=title_position)
plt.hold("on")
plt.plot(np.arange(-len(signal_A) + 1, len(signal_B)), convoluted_signals)
a2 = plt.subplot(1, 3, 3)
a2.get_xaxis().get_major_formatter().set_useOffset(False)
plt.ylabel('angular velocity norm [rad]')
plt.xlabel('time [s]')
a2.set_title(
"After Time Alignment", y=title_position)
plt.hold("on")
min_time = min(np.amin(times_A_shifted), np.amin(times_B))
times_A_shifted_zeroed = times_A_shifted - min_time
times_B_zeroed = times_B - min_time
plt.plot(times_A_shifted_zeroed, signal_A, c='r')
plt.plot(times_B_zeroed, signal_B, c='b')
plt.subplots_adjust(left=0.04, right=0.99, top=0.8, bottom=0.15)
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)
time_alignment_plotting_tools.py 文件源码
项目:hand_eye_calibration
作者: ethz-asl
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def plot_time_stamped_poses(title,
time_stamped_poses_A,
time_stamped_poses_B,
block=True):
fig = plt.figure()
title_position = 1.05
fig.suptitle(title + " [A = top, B = bottom]", fontsize='24')
a1 = plt.subplot(2, 2, 1)
a1.set_title(
"Orientation \nx [red], y [green], z [blue], w [cyan]",
y=title_position)
plt.plot(time_stamped_poses_A[:, 4], c='r')
plt.plot(time_stamped_poses_A[:, 5], c='g')
plt.plot(time_stamped_poses_A[:, 6], c='b')
plt.plot(time_stamped_poses_A[:, 7], c='c')
a2 = plt.subplot(2, 2, 2)
a2.set_title(
"Position (eye coordinate frame) \nx [red], y [green], z [blue]", y=title_position)
plt.plot(time_stamped_poses_A[:, 1], c='r')
plt.plot(time_stamped_poses_A[:, 2], c='g')
plt.plot(time_stamped_poses_A[:, 3], c='b')
a3 = plt.subplot(2, 2, 3)
plt.plot(time_stamped_poses_B[:, 4], c='r')
plt.plot(time_stamped_poses_B[:, 5], c='g')
plt.plot(time_stamped_poses_B[:, 6], c='b')
plt.plot(time_stamped_poses_B[:, 7], c='c')
a4 = plt.subplot(2, 2, 4)
plt.plot(time_stamped_poses_B[:, 1], c='r')
plt.plot(time_stamped_poses_B[:, 2], c='g')
plt.plot(time_stamped_poses_B[:, 3], 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 run_regression_1D():
np.random.seed(42)
print "create dataset ..."
N = 50
rng = np.random.RandomState(42)
X = np.sort(2 * rng.rand(N, 1) - 1, axis=0)
Y = np.array([np.pi * np.sin(10 * X).ravel(),
np.pi * np.cos(10 * X).ravel()]).T
Y += (0.5 - rng.rand(*Y.shape))
Y = Y / np.std(Y, axis=0)
def plot(model, alpha, fname):
xx = np.linspace(-1.2, 1.2, 200)[:, None]
if isinstance(model, IndepSGPR):
mf, vf = model.predict_f(xx, alpha)
else:
# mf, vf = model.predict_f(xx, alpha, use_mean_only=False)
mf, vf = model.predict_f(xx, alpha, use_mean_only=True)
colors = ['r', 'b']
plt.figure()
for i in range(model.Dout):
plt.subplot(model.Dout, 1, i + 1)
plt.plot(X, Y[:, i], 'x', color=colors[i], mew=2)
zu = model.models[i].zu
mean_u, var_u = model.models[i].predict_f(zu, alpha)
plt.plot(xx, mf[:, i], '-', color=colors[i], lw=2)
plt.fill_between(
xx[:, 0],
mf[:, i] - 2 * np.sqrt(vf[:, i]),
mf[:, i] + 2 * np.sqrt(vf[:, i]),
color=colors[i], alpha=0.3)
# plt.errorbar(zu[:, 0], mean_u, yerr=2*np.sqrt(var_u), fmt='ro')
plt.xlim(-1.2, 1.2)
plt.savefig(fname)
# inference
print "create independent output model and optimize ..."
M = N
alpha = 0.01
indep_model = IndepSGPR(X, Y, M)
indep_model.train(alpha=alpha)
plot(indep_model, alpha, '/tmp/reg_indep_multioutput.pdf')
print "create correlated output model and optimize ..."
M = N
ar_model = AutoSGPR(X, Y, M)
ar_model.train(alpha=alpha)
plot(ar_model, alpha, '/tmp/reg_autoreg_multioutput.pdf')
def plot_posterior_linear(params_fname, fig_fname, control=False, M=20):
# load dataset
data = np.loadtxt('./sandbox/hh_data.txt')
# use the voltage and potasisum current
data = data / np.std(data, axis=0)
y = data[:, :4]
xc = data[:, [-1]]
# init hypers
Dlatent = 2
Dobs = y.shape[1]
T = y.shape[0]
if control:
x_control = xc
no_panes = 5
else:
x_control = None
no_panes = 4
model_aep = aep.SGPSSM_Linear(y, Dlatent, M,
lik='Gaussian', prior_mean=0, prior_var=1000, x_control=x_control)
model_aep.load_model(params_fname)
my, vy, vyn = model_aep.get_posterior_y()
vy_diag = np.diagonal(vy, axis1=1, axis2=2)
vyn_diag = np.diagonal(vyn, axis1=1, axis2=2)
cs = ['k', 'r', 'b', 'g']
labels = ['V', 'm', 'n', 'h']
plt.figure()
t = np.arange(T)
for i in range(4):
yi = y[:, i]
mi = my[:, i]
vi = vy_diag[:, i]
vin = vyn_diag[:, i]
plt.subplot(no_panes, 1, i + 1)
plt.fill_between(t, mi + 2 * np.sqrt(vi), mi - 2 *
np.sqrt(vi), color=cs[i], alpha=0.4)
plt.plot(t, mi, '-', color=cs[i])
plt.plot(t, yi, '--', color=cs[i])
plt.ylabel(labels[i])
plt.xticks([])
plt.yticks([])
if control:
plt.subplot(no_panes, 1, no_panes)
plt.plot(t, x_control, '-', color='m')
plt.ylabel('I')
plt.yticks([])
plt.xlabel('t')
plt.savefig(fig_fname)
if control:
plot_model_with_control(model_aep, '', '_linear_with_control')
else:
plot_model_no_control(model_aep, '', '_linear_no_control')