在python中仅使用numpy和scipy编码Isomap(& MDS)函数

62lalag4  于 2023-01-05  发布在  Python
关注(0)|答案(2)|浏览(108)

我已经编写了Isomap函数,从计算欧氏距离矩阵开始(使用scipy.spatial.distance.cdist),接下来基于K-最近邻方法和Dijkstra算法(确定最短路径),我已经计算了所有路径上的完整距离矩阵,最后我已经完成了Map计算,随后进行了维度缩减。但是,我想使用epsilon代替K-最近邻,如下所示:
Y =异构图(X,ε,d)
· X是一个n × m矩阵,对应于具有m个属性的n个点。
· epsilon是距离矩阵的匿名函数,用于查找邻域的参数(邻域图必须通过消除完整距离图中宽度大于epsilon的边来形成)。
· d是表示输出维数的参数。
· Y是一个n × d矩阵,表示由等距Map产生的嵌入。
先谢谢你

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist

def distance_Matrix(X):
    return cdist(X,X,'euclidean')

def Dijkstra(h):
    q = h.copy()
    for i in range(ndata):
        for j in range(ndata):
            k = np.argmin(q[i,:])
            while not(np.isinf(q[i,k])):
                q[i,k] = np.inf
                for l in neighbours[k,:]:
                    possible = h[i,l] + h[l,k]
                    if possible < h[i,k]:
                        h[i,k] = possible
                k = np.argmin(q[i,:])
    return h

def MDS(D,newdim=2):  

    n = D.shape[0]
    # Torgerson formula
    I = np.eye(n)
    J = np.ones(D.shape)
    J = I-(1/n)*J
    B = (-1/2)*np.dot(np.dot(J,D),np.dot(D,J))  # B = -(1/2).JD²J

    # 
    eigenval, eigenvec = np.linalg.eig(B)
    indices = np.argsort(eigenval)[::-1]   
    eigenval = eigenval[indices]
    eigenvec = eigenvec[:, indices]

    # dimension reduction
    K = eigenvec[:, :newdim]
    L = np.diag(eigenval[:newdim])  
    # result
    Y = K @ L **(1/2)    
    return np.real(Y)

def isomap(data,newdim=2,K=12):

    ndata = np.shape(data)[0]
    ndim = np.shape(data)[1]

    d = distance_Matrix(X)

    # replace begin 
    # K-nearest neighbours
    indices = d.argsort()
    #notneighbours = indices[:,K+1:]
    neighbours = indices[:,:K+1]
    # replace end

    h = np.ones((ndata,ndata),dtype=float)*np.inf
    for i in range(ndata):
        h[i,neighbours[i,:]] = d[i,neighbours[i,:]]
    h = Dijkstra(h)
    return MDS(h,newdim)
zf9nrax1

zf9nrax12#

你好有一个代码与epsilon方法?你能分享吗?谢谢

相关问题