Python:将iris数据通过近邻转化为图并展示出来
程序员文章站
2022-03-16 12:51:15
import numpy as npfrom sklearn import datasetsimport networkx as nxfrom scipy.spatial.distance import pdist, squareformimport matplotlib.pyplot as pltX, y = datasets.load_iris(return_X_y=True)N = X.shape[0]distlist = pdist(X,metric='euclidean')d....
import numpy as np
from sklearn import datasets
import networkx as nx
from scipy.spatial.distance import pdist, squareform
import matplotlib.pyplot as plt
X, y = datasets.load_iris(return_X_y=True)
N = X.shape[0]
distlist = pdist(X,metric='euclidean')
dist_Matrix = squareform(distlist)
simi_Matrix = np.zeros((N,N))
neiNum = 5
for i in range(N):
ordidx = np.argsort(dist_Matrix[i,:])
for j in range(neiNum+1):
if i != ordidx[j]:
simi_Matrix[i,ordidx[j]] = dist_Matrix[i, ordidx[j]]
G = nx.Graph()
for i in range(N):
for j in range(N):
if simi_Matrix[i,j] > 0:
G.add_weighted_edges_from([(i,j,simi_Matrix[i,j])])
pos = nx.spring_layout(G)
# pos = nx.random_layout(G)
# pos = nx.circular_layout(G)
# pos = nx.shell_layout(G)
nx.draw(G,pos,node_color=y,with_labels=True,font_size=15,node_size=120)
plt.show()
本文地址:https://blog.csdn.net/DeniuHe/article/details/108410681