n_samples = 1500 noise = 0.05 X, _ = make_swiss_roll(n_samples, noise=noise) 对以上代码产生的数据不调用sklearn.manifold ,python实现ISOMAP降维度
时间: 2024-02-24 20:58:16 浏览: 109
OpenCV_Samples.rar_opencv sampl_opencv source_opencv._opencv_sam
Here's an implementation of ISOMAP for dimensionality reduction in Python without using `sklearn.manifold` on the data generated by the code you provided:
```
import numpy as np
from sklearn.neighbors import NearestNeighbors
from scipy.spatial.distance import pdist, squareform
from sklearn.manifold import MDS
# Step 1: Compute pairwise Euclidean distance matrix
dist_matrix = squareform(pdist(X, metric='euclidean'))
# Step 2: Find k-nearest neighbors for each point
k = 10
knn = NearestNeighbors(n_neighbors=k+1) # include self as a neighbor
knn.fit(X)
distances, indices = knn.kneighbors(X)
# Step 3: Build graph with edges between each point and its k-nearest neighbors
adj_matrix = np.zeros((n_samples, n_samples))
for i in range(n_samples):
for j in indices[i]:
if i != j:
adj_matrix[i, j] = dist_matrix[i, j]
adj_matrix[j, i] = dist_matrix[j, i]
# Step 4: Compute shortest path distance between all pairs of nodes using Floyd-Warshall algorithm
shortest_paths = np.zeros((n_samples, n_samples))
for i in range(n_samples):
for j in range(n_samples):
if i != j:
shortest_paths[i, j] = np.inf
for k in range(n_samples):
for i in range(n_samples):
for j in range(n_samples):
if shortest_paths[i, j] > shortest_paths[i, k] + shortest_paths[k, j]:
shortest_paths[i, j] = shortest_paths[i, k] + shortest_paths[k, j]
# Step 5: Apply classical MDS to embed graph in lower-dimensional space
embedding = MDS(n_components=2, dissimilarity='precomputed').fit_transform(shortest_paths)
# Visualize embedded points
import matplotlib.pyplot as plt
plt.scatter(embedding[:,0], embedding[:,1], c=X[:,2], cmap=plt.cm.jet)
plt.xlabel('Dimension 1')
plt.ylabel('Dimension 2')
plt.show()
```
Note that the above code embeds the data in a 2-dimensional space, but you can change `n_components` in the `MDS` class to embed the data in a different number of dimensions.
阅读全文