def spectral_partition(W,q,method = 'complete', metric = 'cosine'):

    n,m = W.shape
    K = Kmatrix(W)

    if n == m:
        try:
            e,v = linalg.eigen(K, q)
        except TypeError:
            e,v = linalg.eigs(K, q)

    else:
        try:
            u,e,v = linalg.svds(K, q)
        except AttributeError:
            u,e,v = linalg.svd(K, q)
           
        v = np.concatenate((u, v.T), 0)
                
    max_index = e.argmax()
    v = np.delete(v,max_index,1)
    Obs = np.real(v)
    D = distance.pdist(Obs,metric = metric)
    D = np.multiply(D >= 0, D)
    Z = linkage(D, method = method, metric = metric)
    cluster = fcluster(Z, q, criterion = 'maxclust')
            
    cluster += - 1
    cluster = {'spectral' : cluster}

    return cluster
Beispiel #2
0
def laplaceeigs(k,N,n):
    import scipy.linalg as sl
    tag = "B1"
    elements = H1Elements(k)
    quadrule = pyramidquadrature(k+1)
    system = SymmetricSystem(elements, quadrule, lambda m: buildcubemesh(N, m, tag), [tag])

    SM = system.systemMatrix(True)
    S, SIBs, Gs = system.processBoundary(SM, {tag:lambda p: numpy.zeros((len(p),1))})
    print S.shape
    MM = system.systemMatrix(False)
    M, _, _ = system.processBoundary(MM, {tag:lambda p: numpy.zeros((len(p),1))})
    
    MLU = ssl.splu(M)
    L = A = ssl.LinearOperator( M.shape, matvec=lambda x: MLU.solve(S* x), dtype=float)
    
    return ssl.eigen(L, k=n, which='SM', return_eigenvectors=False)
    vw=np.max(abs(W))
    vl=np.max(abs(L))


    figure(2, figsize=(6,3))
    suptitle('Weight and Laplacian matrices')
    subplot(1,2,1)
    imshow(W, interpolation='nearest', cmap='RdBu', vmin=-vw, vmax=vw)
    subplot(1,2,2)
    imshow(L, interpolation='nearest', cmap='RdBu', vmin=-vl/20, vmax=vl/20)
    savefig('spec2.png', dpi=100)


    figure(3, figsize=(6,3))
    lam,u = eigen(L , k=4, which='SR')
    lamall,ulixo = eigen(L , k=10, which='SR')

    lamall=real(lamall)

    lam =real(lam)
    u   =real(u)

    print lam
    subplot(1,2,1)
    title('First eigenvalues')
    plot(sort(lamall), '-+')
    subplot(1,2,2)
    title('First eigenvectors')
    plot(u[:,:4])
    savefig('spec3.png', dpi=100)