这个代码如何修改实现输出可视化
时间: 2024-04-16 12:26:52 浏览: 91
要将传播过程可视化,你可以使用networkx库中的绘图功能。下面是修改后的代码示例:
```python
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# 读取Excel文件中的邻接矩阵
adjacency_matrix = pd.read_excel('output.xlsx', index_col=0)
# 将邻接矩阵转换为numpy数组
adjacency_matrix = adjacency_matrix.to_numpy()
# 创建有向图对象
G = nx.DiGraph(adjacency_matrix)
def preprocess(G):
p = 0
directedGraph = nx.DiGraph()
for u in G.nodes():
for v in G.neighbors(u):
if (v != u):
propProb = G.number_of_edges(u, v) / G.degree(v)
directedGraph.add_edge(u, v, pp=propProb)
return directedGraph
def simulate(G, seedNode, propProbability):
newActive = True
currentActiveNodes = seedNode.copy()
newActiveNodes = set()
activatedNodes = seedNode.copy()
influenceSpread = len(seedNode)
while newActive:
for node in currentActiveNodes:
for neighbor in G.neighbors(node):
if neighbor not in activatedNodes:
if G[node][neighbor]['pp'] > propProbability:
newActiveNodes.add(neighbor)
activatedNodes.append(neighbor)
influenceSpread += len(newActiveNodes)
if newActiveNodes:
currentActiveNodes = list(newActiveNodes)
newActiveNodes = set()
else:
newActive = False
return influenceSpread
def flipCoin(probability):
return np.random.random() < probability
# 可视化传播过程
def visualizePropagation(G, seedNode, propProbability):
pos = nx.spring_layout(G) # 选择布局算法
labels = {node: node for node in G.nodes()} # 节点标签为节点名
colors = ['r' if node in seedNode else 'b' for node in G.nodes()] # 种子节点为红色,其他节点为蓝色
plt.figure(figsize=(10, 6))
nx.draw_networkx_nodes(G, pos, node_color=colors)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos, labels)
plt.title('Propagation Visualization')
plt.show()
# 示例用法
seedNode = [1, 2, 3]
propProbability = 0.5
directedGraph = preprocess(G)
influenceSpread = simulate(directedGraph, seedNode, propProbability)
print("Influence Spread:", influenceSpread)
visualizePropagation(directedGraph, seedNode, propProbability)
```
在上面的代码中,我添加了一个名为`visualizePropagation`的函数,用于绘制传播过程的可视化。它使用`spring_layout`布局算法确定节点的位置,根据种子节点设置节点的颜色(红色表示种子节点,蓝色表示其他节点),然后使用`draw_networkx_nodes`、`draw_networkx_edges`和`draw_networkx_labels`函数绘制图形。
在示例用法部分,我定义了一个种子节点列表和传播概率,并调用了`visualizePropagation`函数来展示传播过程的可视化结果。
你可以根据自己的需求修改代码,并根据实际情况调整布局算法和节点标签等参数来获得更具吸引力的可视化效果。
阅读全文