提供一段python代码:构建一个无向加权符号网络(节点、连边、权重信息由excel文件输入),每个节点的初始值为0,权重大小的绝对值小于1,当一个节点增大或减小1时,它的邻居节点有连边权重绝对值大小的概率增大或减小1(如果连边为正则增大,连边为负则减小),一个节点有可能被多个邻居同时影响,再接着影响下一个邻居节点直至所有节点发生变化。迭代整个程序100次最后按节点发生变化的先后顺序输出节点的增减情况
时间: 2023-06-08 22:08:23 浏览: 140
ex3-neural network_神经网络_Python神经网络_python_
以下是构建无向加权符号网络的 Python 代码,包括节点、连边和权重信息从 Excel 文件中读取,并实现了迭代 100 次,输出节点的增减情况:
```python
import pandas as pd
import random
# 从 Excel 文件中读取节点、连边和权重信息
df_nodes = pd.read_excel("network.xlsx", sheet_name="Nodes")
df_edges = pd.read_excel("network.xlsx", sheet_name="Edges")
df_weights = pd.read_excel("network.xlsx", sheet_name="Weights")
# 构建邻接矩阵和权重矩阵
n = len(df_nodes)
adj_matrix = [[0]*n for i in range(n)]
weight_matrix = [[0]*n for i in range(n)]
node_dict = {node: i for i, node in enumerate(df_nodes["Node"])}
for i, row in df_edges.iterrows():
source = node_dict[row["Source"]]
target = node_dict[row["Target"]]
weight = df_weights.iloc[source, target]
adj_matrix[source][target] = 1
adj_matrix[target][source] = 1
weight_matrix[source][target] = weight
weight_matrix[target][source] = weight
# 初始化节点值和节点增减情况记录
node_values = [0] * n
node_changes = [0] * n
# 迭代整个程序 100 次
for iteration in range(100):
# 记录本次迭代中节点的增减情况
iteration_changes = []
# 对每个节点进行计算
for i in range(n):
# 计算该节点的增减值
delta = 0
neighbors = [j for j, adj in enumerate(adj_matrix[i]) if adj == 1]
for j in neighbors:
weight = weight_matrix[i][j]
sign = 1 if weight > 0 else -1
probability = abs(weight)
if random.random() < probability:
delta += sign * node_changes[j]
# 更新节点的值和增减情况记录
node_values[i] += delta
if delta != 0:
node_changes[i] = delta
iteration_changes.append((df_nodes["Node"][i], delta))
else:
node_changes[i] = 0
# 输出本次迭代节点的增减情况
iteration_changes.sort(key=lambda x: node_dict[x[0]])
print(f"Iteration {iteration+1}:")
for node, delta in iteration_changes:
print(f"{node}: {delta}")
```
阅读全文