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()
python类gca()的实例源码
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 plotValueFunction(self, valueFunction, prefix):
'''3d plot of a value function.'''
fig, ax = plt.subplots(subplot_kw = dict(projection = '3d'))
X, Y = np.meshgrid(np.arange(self.numCols), np.arange(self.numRows))
Z = valueFunction.reshape(self.numRows, self.numCols)
for i in xrange(len(X)):
for j in xrange(len(X[i])/2):
tmp = X[i][j]
X[i][j] = X[i][len(X[i]) - j - 1]
X[i][len(X[i]) - j - 1] = tmp
my_col = cm.jet(np.random.rand(Z.shape[0],Z.shape[1]))
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1,
cmap = plt.get_cmap('jet'))
plt.gca().view_init(elev=30, azim=30)
plt.savefig(self.outputPath + prefix + 'value_function.png')
plt.close()
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def plot_feat_importance(feature_names, clf, name):
pylab.clf()
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(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
项目源码
文件源码
阅读 23
收藏 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
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def plot_feat_importance(feature_names, clf, name):
pylab.clf()
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(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_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 hrd_new(self, input_label="", skip=0):
"""
plot an HR diagram with options to skip the first N lines and
add a label string
Parameters
----------
input_label : string, optional
Diagram label. The default is "".
skip : integer, optional
Skip the first n lines. The default is 0.
"""
xl_old=pyl.gca().get_xlim()
if input_label == "":
my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z'])
else:
my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z'])+"; "+str(input_label)
pyl.plot(self.data[skip:,self.cols['log_Teff']-1],self.data[skip:,self.cols['log_L']-1],label = my_label)
pyl.legend(loc=0)
xl_new=pyl.gca().get_xlim()
pyl.xlabel('log Teff')
pyl.ylabel('log L')
if any(array(xl_old)==0):
pyl.gca().set_xlim(max(xl_new),min(xl_new))
elif any(array(xl_new)==0):
pyl.gca().set_xlim(max(xl_old),min(xl_old))
else:
pyl.gca().set_xlim([max(xl_old+xl_new),min(xl_old+xl_new)])
def plot1D_mat(a, b, M, title=''):
""" Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source distribution
b : np.array, shape (nb,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot
"""
na, nb = M.shape
gs = gridspec.GridSpec(3, 3)
xa = np.arange(na)
xb = np.arange(nb)
ax1 = pl.subplot(gs[0, 1:])
pl.plot(xb, b, 'r', label='Target distribution')
pl.yticks(())
pl.title(title)
ax2 = pl.subplot(gs[1:, 0])
pl.plot(a, xa, 'b', label='Source distribution')
pl.gca().invert_xaxis()
pl.gca().invert_yaxis()
pl.xticks(())
pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
pl.imshow(M, interpolation='nearest')
pl.axis('off')
pl.xlim((0, nb))
pl.tight_layout()
pl.subplots_adjust(wspace=0., hspace=0.2)
def plotBasisFunctions(self, eigenvalues, eigenvectors):
'''3d plot of the basis function. Right now I am plotting eigenvectors,
so each coordinate of the eigenvector correspond to the value to be
plotted for the correspondent state.'''
for i in xrange(len(eigenvalues)):
fig, ax = plt.subplots(subplot_kw = dict(projection = '3d'))
X, Y = np.meshgrid(np.arange(self.numRows), np.arange(self.numCols))
Z = eigenvectors[:,i].reshape(self.numCols, self.numRows)
for ii in xrange(len(X)):
for j in xrange(len(X[ii])/2):
tmp = X[ii][j]
X[ii][j] = X[ii][len(X[ii]) - j - 1]
X[ii][len(X[ii]) - j - 1] = tmp
my_col = cm.jet(np.random.rand(Z.shape[0],Z.shape[1]))
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1,
cmap = plt.get_cmap('jet'))
plt.gca().view_init(elev=30, azim=30)
plt.savefig(self.outputPath + str(i) + '_eig' + '.png')
plt.close()
plt.plot(eigenvalues, 'o')
plt.savefig(self.outputPath + 'eigenvalues.png')
def clean_ticks():
ax = plt.gca()
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
def percent_ylabel():
plt.gca().set_yticklabels(['%d%%' % (x * 100) for
x in plt.gca().get_yticks()])
def plotBoundVsK(KVals=np.arange(1,50),
alpha=0.5,
gamma=10,
labels=None,
betaFunc='prior'):
if labels is None:
txtlabel = str(alpha)
labels = [None, None]
else:
txtlabel = 'alpha\n' + str(alpha)
exactVals = np.zeros(len(KVals))
boundVals = np.zeros(len(KVals))
for ii, K in enumerate(KVals):
betaVec = 1.0/(1.0 + gamma) * np.ones(K+1)
for k in range(1, K):
betaVec[k] = betaVec[k] * (1 - np.sum(betaVec[:k]))
betaVec[-1] = 1 - np.sum(betaVec[:-1])
print betaVec
assert np.allclose(betaVec.sum(), 1.0)
exactVals[ii] = cDir_exact(alpha, betaVec)
boundVals[ii] = cDir_surrogate(alpha, betaVec)
assert np.all(exactVals >= boundVals)
pylab.plot(KVals, exactVals,
'k-', linewidth=LINEWIDTH, label=labels[0])
pylab.plot(KVals, boundVals,
'r--', linewidth=LINEWIDTH, label=labels[1])
index = -1
pylab.text(KVals[index]+.25, boundVals[index],
txtlabel, fontsize=LEGENDSIZE-8)
pylab.xlim([0, np.max(KVals)+7.5])
pylab.gca().set_xticks([0, 10, 20, 30, 40, 50])
pylab.xlabel("K", fontsize=FONTSIZE)
pylab.ylabel("cDir function", fontsize=FONTSIZE)
pylab.tick_params(axis='both', which='major', labelsize=TICKSIZE)
def makeFigure(hmmKappa=0):
Data, trueResp = makeDataAndTrueResp()
kemptyVals = np.asarray([0, 1, 2, 3.])
ELBOVals = np.zeros_like(kemptyVals, dtype=np.float)
# Iterate over the number of empty states (0, 1, 2, ...)
for ii, kempty in enumerate(kemptyVals):
resp = makeNewRespWithEmptyStates(trueResp, kempty)
ELBOVals[ii] = resp2ELBO_HDPHMM(Data, resp, hmmKappa=hmmKappa)
# Make largest value the one with kempty=0, to make plot look good
ELBOVals -= ELBOVals[0]
# Plot the results
from matplotlib import pylab
figH = pylab.figure(figsize=(6, 4))
plotargs = dict(markersize=10, linewidth=3)
pylab.plot(kemptyVals, ELBOVals, 'o--', label='HDP surrogate',
color='b', markeredgecolor='b',
**plotargs)
pylab.xlabel('num. empty topics', fontsize=20)
pylab.ylabel('change in ELBO', fontsize=20)
B = 0.25
pylab.xlim([-B, kemptyVals[-1] + B])
pylab.xticks(kemptyVals)
axH = pylab.gca()
axH.tick_params(axis='both', which='major', labelsize=15)
legH = pylab.legend(loc='upper left', prop={'size': 15})
figH.subplots_adjust(bottom=0.16, left=0.2)
pylab.show(block=True)
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_cube(points3d, title=''):
fig = plt.figure()
fig.suptitle(title, fontsize=16)
ax = fig.gca(projection='3d')
ax.set_aspect('equal')
ax.plot(points3d[0], points3d[1], points3d[2], 'b.')
ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
ax.view_init(elev=135, azim=90)
return ax
def plotPolicy(self, policy, prefix):
plt.clf()
for idx in xrange(len(policy)):
i, j = self.env.getStateXY(idx)
dx = 0
dy = 0
if policy[idx] == 0: # up
dy = 0.35
elif policy[idx] == 1: #right
dx = 0.35
elif policy[idx] == 2: #down
dy = -0.35
elif policy[idx] == 3: #left
dx = -0.35
elif self.matrixMDP[i][j] != -1 and policy[idx] == 4: # termination
circle = plt.Circle(
(j + 0.5, self.numRows - i + 0.5 - 1), 0.025, color='k')
plt.gca().add_artist(circle)
if self.matrixMDP[i][j] != -1:
plt.arrow(j + 0.5, self.numRows - i + 0.5 - 1, dx, dy,
head_width=0.05, head_length=0.05, fc='k', ec='k')
else:
plt.gca().add_patch(
patches.Rectangle(
(j, self.numRows - i - 1), # (x,y)
1.0, # width
1.0, # height
facecolor = "gray"
)
)
plt.xlim([0, self.numCols])
plt.ylim([0, self.numRows])
for i in xrange(self.numCols):
plt.axvline(i, color='k', linestyle=':')
plt.axvline(self.numCols, color='k', linestyle=':')
for j in xrange(self.numRows):
plt.axhline(j, color='k', linestyle=':')
plt.axhline(self.numRows, color='k', linestyle=':')
plt.savefig(self.outputPath + prefix + 'policy.png')
plt.close()
def _plot_ND_FES(data, ax_labels, weights=None, bins=50, figsize=(4,4)):
r""" A wrapper for pyemmas FESs plotting function that can also plot 1D
Parameters
----------
data : list of numpy nd.arrays
ax_labels : list
Returns
-------
ax : :obj:`pylab.Axis` object
FES_data : numpy nd.array containing the FES (only for 1D data)
edges : tuple containimg the axes along which FES is to be plotted (only in the 1D case so far, else it's None)
"""
_plt.figure(figsize=figsize)
ax = _plt.gca()
idata = _np.vstack(data)
ax.set_xlabel(ax_labels[0])
if idata.shape[1] == 1:
h, edges = _np.histogramdd(idata, weights=weights, bins=bins, normed=True)
FES_data = -_np.log(h)
FES_data -= FES_data.min()
ax.plot(edges[0][:-1], FES_data)
ax.set_ylabel('$\Delta G / \kappa T $')
elif idata.shape[1] == 2:
_plot_free_energy(idata[:,0], idata[:,1], weights=weights, nbins=bins, ax=ax,
cmap='nipy_spectral'
)
ax.set_ylabel(ax_labels[1])
edges, FES_data = [None], None
# TODO: retrieve the actual edges from pyemma's "plot_free_energy"'s axes
else:
raise NotImplementedError('Can only plot 1D or 2D FESs, but data has %s columns' % _np.shape(idata)[0])
return ax, FES_data, edges
def makeFigure(**kwargs):
Data, trueResp = makeDataAndTrueResp(**kwargs)
kemptyVals = np.asarray([0, 1, 2, 3.])
ELBOVals = np.zeros_like(kemptyVals, dtype=np.float)
PointEstELBOVals = np.zeros_like(kemptyVals, dtype=np.float)
# Iterate over the number of empty states (0, 1, 2, ...)
for ii, kempty in enumerate(kemptyVals):
resp = makeNewRespWithEmptyStates(trueResp, kempty)
PointEstELBOVals[ii] = resp2ELBO_HDPTopicModel(
Data,
resp,
doPointEstimate=1,
**kwargs)
ELBOVals[ii] = resp2ELBO_HDPTopicModel(Data, resp, **kwargs)
# Make largest value the one with kempty=0, to make plot look good
PointEstELBOVals -= PointEstELBOVals[0]
ELBOVals -= ELBOVals[0]
# Rescale so that yaxis has units on order of 1, not 0.001
scale = np.max(np.abs(ELBOVals))
ELBOVals /= scale
PointEstELBOVals /= scale
# Set buffer-space for defining plotable area
xB = 0.25
B = 0.19 # big buffer for sides where we will put text labels
b = 0.01 # small buffer for other sides
TICKSIZE = 30
FONTSIZE = 40
LEGENDSIZE = 30
LINEWIDTH = 4
# Plot the results
figH = pylab.figure(figsize=(9.1, 6))
axH = pylab.subplot(111)
axH.set_position([xB, B, (1 - xB - b), (1 - B - b)])
plotargs = dict(markersize=20, linewidth=LINEWIDTH)
pylab.plot(kemptyVals, PointEstELBOVals, 'v-', label='HDP point est',
color='b', markeredgecolor='b',
**plotargs)
pylab.plot(kemptyVals, np.zeros_like(kemptyVals), 's:', label='HDP exact',
color='g', markeredgecolor='g',
**plotargs)
pylab.plot(kemptyVals, ELBOVals, 'o--', label='HDP surrogate',
color='r', markeredgecolor='r',
**plotargs)
pylab.xlabel('num. empty topics', fontsize=FONTSIZE)
pylab.ylabel('change in ELBO', fontsize=FONTSIZE)
xB = 0.25
pylab.xlim([-xB, kemptyVals[-1] + xB])
pylab.xticks(kemptyVals)
pylab.yticks([-1, 0, 1])
axH = pylab.gca()
axH.tick_params(axis='both', which='major', labelsize=TICKSIZE)
legH = pylab.legend(loc='upper left', prop={'size': LEGENDSIZE})
def illustrate(Colors=Colors):
if hasattr(Colors, 'colors'):
Colors = Colors.colors
from matplotlib import pylab
rcParams = pylab.rcParams
rcParams['pdf.fonttype'] = 42
rcParams['ps.fonttype'] = 42
rcParams['text.usetex'] = False
rcParams['xtick.labelsize'] = 20
rcParams['ytick.labelsize'] = 20
rcParams['legend.fontsize'] = 25
import bnpy
Data = get_data(T=1000, nDocTotal=8)
for k in xrange(K):
zmask = Data.TrueParams['Z'] == k
pylab.plot(Data.X[zmask, 0], Data.X[zmask, 1], '.', color=Colors[k],
markeredgecolor=Colors[k],
alpha=0.4)
sigEdges = np.flatnonzero(transPi[k] > 0.0001)
for j in sigEdges:
if j == k:
continue
dx = mus[j, 0] - mus[k, 0]
dy = mus[j, 1] - mus[k, 1]
pylab.arrow(mus[k, 0], mus[k, 1],
0.8 * dx,
0.8 * dy,
head_width=2, head_length=4,
facecolor=Colors[k], edgecolor=Colors[k])
tx = 0 - mus[k, 0]
ty = 0 - mus[k, 1]
xy = (mus[k, 0] - 0.2 * tx, mus[k, 1] - 0.2 * ty)
'''
pylab.annotate( u'\u27F2',
xy=(mus[k,0], mus[k,1]),
color=Colors[k],
fontsize=35,
)
'''
pylab.gca().yaxis.set_ticks_position('left')
pylab.gca().xaxis.set_ticks_position('bottom')
pylab.axis('image')
pylab.ylim([-38, 38])
pylab.xlim([-38, 38])