代码:# 随机生成数据集 X, y = make_classification(n_samples=100, n_features=10, n_classes=3, n_clusters_per_class=1, random_state=42) # 构建图 G = nx.complete_graph(len(X)) # 计算相似度 similarity_matrix = np.zeros((len(X), len(X))) for i in range(len(X)): for j in range(len(X)): if i != j: similarity_matrix[i][j] = np.dot(X[i], X[j]) / (np.linalg.norm(X[i]) * np.linalg.norm(X[j])) # 图坍缩 for i in range(len(X)): neighbors = sorted(G.neighbors(i), key=lambda x: similarity_matrix[i][x], reverse=True) for j in neighbors: if i != j: G = nx.contracted_edge(G, (i, j)) 报错:KeyError: 1 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:/403/myworld/GraphNet.py", line 23, in <module> neighbors = sorted(G.neighbors(i), key=lambda x: similarity_matrix[i][x], reverse=True) File "D:\code\myworld\lib\site-packages\networkx\classes\graph.py", line 1356, in neighbors raise NetworkXError(f"The node {n} is not in the graph.") from err networkx.exception.NetworkXError: The node 1 is not in the graph. 进程已结束,退出代码1 如何修改
时间: 2023-12-27 16:04:49 浏览: 57
随机生成数据的C#代码
4星 · 用户满意度95%
这个错误可能是因为你的图 `G` 中没有节点 `1`。建议在计算相似度矩阵时,将对角线上的元素设置为0,以避免出现自环。另外,你也可以尝试在使用 `sorted` 函数前,先检查一下节点 `i` 是否存在于图中,例如:
```python
for i in range(len(X)):
if not G.has_node(i):
continue
neighbors = sorted(G.neighbors(i), key=lambda x: similarity_matrix[i][x], reverse=True)
for j in neighbors:
if i != j and G.has_node(j):
G = nx.contracted_edge(G, (i, j))
```
这里我们增加了 `if not G.has_node(i): continue` 和 `if i != j and G.has_node(j):` 条件语句,以确保只有存在于图中的节点才会被处理。
阅读全文