不调用sklearn.manifold ,实现ISOMAP降维度。
时间: 2024-02-25 19:55:14 浏览: 87
ISOMAP是一种基于流形学习的非线性降维算法,可以将高维数据映射到低维空间中。下面是一个简单的实现ISOMAP降维的代码:
1. 定义计算欧几里得距离的函数
```
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2) ** 2))
```
2. 构建邻接矩阵
```
def construct_adjacency_matrix(X, k):
n = X.shape[0]
W = np.zeros((n, n))
for i in range(n):
dist = []
for j in range(n):
if i != j:
dist.append((j, euclidean_distance(X[i], X[j])))
dist.sort(key=lambda x: x[1])
for j in range(1, k+1):
idx, d = dist[j]
W[i][idx] = d
W[idx][i] = d
return W
```
3. 计算最短距离矩阵
```
def shortest_path(W):
n = W.shape[0]
D = np.full((n, n), np.inf)
for i in range(n):
D[i][i] = 0
for j in range(n):
if W[i][j] != 0:
D[i][j] = W[i][j]
for k in range(n):
for i in range(n):
for j in range(n):
if D[i][j] > D[i][k] + D[k][j]:
D[i][j] = D[i][k] + D[k][j]
return D
```
4. 根据最短距离矩阵计算嵌入矩阵
```
def isomap(X, k, n_components):
W = construct_adjacency_matrix(X, k)
D = shortest_path(W)
B = -0.5 * (D ** 2 - np.sum(D ** 2, axis=0) / n + np.sum(D ** 2) / (n ** 2))
eigvals, eigvecs = np.linalg.eig(B)
idx = np.argsort(eigvals)[::-1][:n_components]
eigvals, eigvecs = eigvals[idx], eigvecs[:, idx]
Y = eigvecs * np.sqrt(eigvals)
return Y.real
```
其中,参数`X`是原始数据,`k`是近邻数,`n_components`是降维后的维度。函数返回降维后的结果。
阅读全文