示例#1
0
def plotDataAsSquareImages(Data,
                           unitIDsToPlot=None,
                           figID=None,
                           nPlots=16,
                           doShowNow=False,
                           seed=0,
                           randstate=np.random.RandomState(0),
                           **kwargs):
    if seed is not None:
        randstate = np.random.RandomState(seed)
    if figID is None:
        pylab.figure()

    V = Data.dim
    assert isPerfectSquare(V)
    sqrtV = int(np.sqrt(V))
    if unitIDsToPlot is not None:
        nPlots = len(unitIDsToPlot)
    else:
        size = np.minimum(Data.nObs, nPlots)
        unitIDsToPlot = randstate.choice(Data.nObs, size=size, replace=False)
    nRows = np.floor(np.sqrt(nPlots))
    nCols = np.ceil(nPlots / nRows)

    for plotPos, unitID in enumerate(unitIDsToPlot):
        squareIm = np.reshape(Data.X[unitID], (sqrtV, sqrtV))
        pylab.subplot(nRows, nCols, plotPos + 1)
        pylab.imshow(squareIm, **imshowArgs)
        pylab.axis('image')
        pylab.xticks([])
        pylab.yticks([])
    pylab.tight_layout()
    if doShowNow:
        pylab.show()
示例#2
0
def plotDocUsageForProposal(docUsageByUID, savefilename=None, **kwargs):
    ''' Make trace plot of doc usage for each component.
    '''
    pylab.figure()
    L = 0
    maxVal = 0
    for k, uid in enumerate(docUsageByUID):
        ys = np.asarray(docUsageByUID[uid])
        xs = np.arange(0, ys.size)
        if k < 6: # only a few labels fit well on a legend
            pylab.plot(xs, ys, label=uid)
        else:
            pylab.plot(xs, ys)
        L = np.maximum(L, ys.size)
        maxVal = np.maximum(maxVal, ys.max())
    # Use big chunk of left-hand side of plot for legend display
    xlims = np.asarray([-0.75*L, L-0.5])
    pylab.xlim(xlims)
    pylab.xticks(np.arange(1, L))
    pylab.ylim([0, 1.1*maxVal])
    pylab.xlabel('num proposal steps')
    pylab.ylabel('num docs using each comp')
    pylab.legend(loc='upper left', fontsize=12)
    pylab.subplots_adjust(left=0.2)
    if savefilename is not None:
        pylab.savefig(savefilename, pad_inches=0)
        pylab.close('all')
示例#3
0
def makePlot(muVals=[(0.01,0), (0.1,0), (1,0), (10,0)], doCorrection=1):
    pylab.figure()
    xgrid = np.linspace(-8, 8, 2000)
    pylab.hold('on')
    pylab.plot(xgrid, np.zeros_like(xgrid), ':', alpha=0.2)
    for mu1, mu2 in muVals:
        ygrid = calcBregDiv_Gauss1D(xgrid, mu1, mu2, doCorrection=doCorrection)
        print ygrid.min()
        pylab.plot(xgrid, ygrid, label='mu1=% 6.2f mu2=% 6.2f' % (mu1, mu2))
    pylab.legend(loc='lower right')
    pylab.xlim([xgrid.min(), xgrid.max()])
    pylab.ylim([xgrid.min(), xgrid.max()])
    pylab.xlabel('x')
    if doCorrection:
        pylab.ylabel('D(x, \mu) + correction')
    else:
        pylab.ylabel('D(x, \mu)')
示例#4
0
def makePlot(muVals=[0.01, 0.1, 1, 10], B=1e-10, nu=2, justMahalTerm=0):
    pylab.figure()
    xgrid = np.linspace(0, 8, 2000)
    pylab.hold('on')
    for mu in muVals:
        ygrid = calcBregDiv_ZeroMean(xgrid,
                                     mu,
                                     B=B,
                                     nu=nu,
                                     justMahalTerm=justMahalTerm)
        pylab.plot(xgrid, ygrid, linewidth=2, label='\mu=%6.2f' % (mu))
    pylab.legend(loc='upper right')
    pylab.xlim([-0.1, xgrid.max()])
    pylab.ylim([-0.1, xgrid.max()])
    pylab.xlabel('x')
    pylab.ylabel('D(x, \mu)')
    pylab.title('B=%s  nu=%s' % (str(B), str(nu)))
示例#5
0
def plotELBOtermsForProposal(
        curLdict, propLdictList,
        xs=None,
        ymin=-0.5,
        ymax=0.5,
        savefilename=None,
        **kwargs):
    ''' Create trace plot of ELBO gain/loss relative to current model.
    '''
    pylab.figure()
    L = len(propLdictList)
    if xs is None:
        xs = np.arange(0, L)
    legendKeys = []
    for key in curLdict:
        if key.count('_') == 0:
            legendKeys.append(key)
    for key in legendKeys:
        if key.count('total'):
            linewidth= 4
            alpha = 1
            style = '-'
        else:
            linewidth = 3
            alpha = 0.5
            style = '--'
        ys = np.asarray([propLdictList[i][key] for i in range(L)])
        ys -= curLdict[key]
        pylab.plot(xs, ys, style,
                   color=_getLineColorFromELBOKey(key),
                   linewidth=linewidth,
                   alpha=alpha,
                   label=key)
    L = L + 1
    xlims = np.asarray([-0.75*L, L-0.5])
    pylab.xlim(xlims)
    pylab.xticks(xs)
    pylab.plot(xlims, np.zeros_like(xlims), 'k:')
    pylab.xlabel('num proposal steps')
    pylab.ylabel('L gain (prop - current)')
    pylab.legend(loc='lower left', fontsize=12)
    pylab.subplots_adjust(left=0.2)
    if savefilename is not None:
        pylab.savefig(savefilename, pad_inches=0)
        pylab.close('all')
示例#6
0
def plotBarsFromHModel(
        hmodel,
        Data=None,
        doShowNow=False,
        figH=None,
        doSquare=1,
        xlabels=[],
        compsToHighlight=None,
        compListToPlot=None,
        activeCompIDs=None,
        Kmax=50,
        width=6,
        height=3,
        vmax=None,
        block=0,  # unused
        jobname='',  # unused
        **kwargs):
    if vmax is not None:
        kwargs['vmax'] = vmax
    if hasattr(hmodel.obsModel, 'Post'):
        lam = hmodel.obsModel.Post.lam
        topics = lam / lam.sum(axis=1)[:, np.newaxis]
    else:
        topics = hmodel.obsModel.EstParams.phi.copy()

    # Determine intensity scale for topic-word image
    global imshowArgs
    if vmax is not None:
        imshowArgs['vmax'] = vmax
    else:
        imshowArgs['vmax'] = 1.5 * np.percentile(topics, 95)

    if doSquare:
        figH = showTopicsAsSquareImages(topics,
                                        activeCompIDs=activeCompIDs,
                                        compsToHighlight=compsToHighlight,
                                        compListToPlot=compListToPlot,
                                        Kmax=Kmax,
                                        figH=figH,
                                        xlabels=xlabels,
                                        **kwargs)
    else:
        if figH is None:
            figH = pylab.figure(figsize=(width, height))
        else:
            pylab.axes(figH)
        showAllTopicsInSingleImage(topics, compsToHighlight, **kwargs)
    if doShowNow:
        pylab.show()
    return figH
示例#7
0
def plotCompsAsRowsInSingleImage(phi,
                                 compsToHighlight,
                                 width=6,
                                 height=3,
                                 **kwargs):
    figH = pylab.figure(figsize=(width, height))
    K, D = phi.shape
    aspectR = D / float(K)
    pylab.imshow(phi, aspect=aspectR, **imshowArgs)
    if compsToHighlight is not None:
        ks = np.asarray(compsToHighlight)
        if ks.ndim == 0:
            ks = np.asarray([ks])
        pylab.yticks(ks, ['**** %d' % (k) for k in ks])
    return figH