我已经对 Isomap 函数进行了编码,首先是计算欧式距离矩阵(使用 scipy.spatial.distance.cdist),接下来基于 K-最近邻方法和 Dijkstra 算法(确定最短路径)我已经计算了全部距离矩阵路径,最后我做了地图计算,然后是降维。但是,我想使用 epsilon 而不是 K 近邻,如下所示:
Y = isomap (X, epsilon, d)
• X 是一个 n × m 矩阵,对应于具有 m 个属性的 n 个点。
• epsilon 是距离矩阵的匿名函数,用于查找邻域的参数。(邻域图必须通过消除宽度大于完整距离图的ε的边来形成)。
• d 是表示输出维度的参数。
• Y 是一个n × d 矩阵,表示从isomap 产生的嵌入。
提前致谢
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)