python - Weisbuch-Defufant 模型
问题描述
嗨,我需要一些帮助来运行我在网上为我的学校项目找到的代码。我目前在 Jupyter notebook 上运行。
%matplotlib inline
from networkx import *
import networkx as nx
import random
import itertools
import matplotlib.pyplot as plt
N= 1000
SIMULATIONS = 100
def run_N_times(G,edges,confidence_bound):
biggest_change = 0
for i in range (N):
(index1, index2) = random.choice(edges)
node1 = G.node[index1]
node2 = G.node[index2]
confidence = abs(node1['opinion'] - node2['opinion'])
#print('confidence between %f and %f is %f' % (node1['opinion'], node2['opinion'], confidence))
if (confidence <= confidence_bound):
newOpinion1 = node1['opinion'] + 0.5*(node2['opinion'] - node1['opinion'])
#print('node %d changed opinion from %f to %f' % (index1, node1['opinion'], newOpinion1))
newOpinion2 = node2['opinion'] + 0.5*(node1['opinion'] - node2['opinion'])
#print('node %d changed opinion from %f to %f' % (index2, node2['opinion'], newOpinion2))
change = abs(newOpinion1 - node1['opinion'])
if (change > biggest_change):
biggest_change = change
node1['opinion'] = newOpinion1
node2['opinion'] = newOpinion2
return biggest_change
def run_with_confidence_bound(confidence_bound):
G=nx.empty_graph(N)
# Generate the nodes and edges
nodes = []
for i in range(N):
nodes.append((i,{'opinion': random.random()}))
edges=itertools.combinations(range(N),2)
G.add_nodes_from(nodes)
G.add_edges_from(edges)
#print('Running')
biggest_change = 1
while(biggest_change > 0.000001):
biggest_change = run_N_times(G, G.edges(), confidence_bound)
#print('Biggest change in run %f'% biggest_change)
# Compute clusters
nodes = G.nodes(True)
opinions = list(set(n[1]['opinion'] for n in nodes))
opinions.sort()
micro_clusters = []
macro_clusters = []
current_cluster = []
cluster_minimum = opinions[0]
for opinion in opinions:
#print('Difference: %f: '% (opinion - cluster_minimum))
if (opinion - cluster_minimum) < 0.0000001:
current_cluster.append(opinion)
else:
# Is it a macro or micro cluster?
if (len(current_cluster) >= 10):
macro_clusters.append(current_cluster)
else:
micro_clusters.append(current_cluster)
current_cluster = [opinion]
cluster_minimum = opinion
if (len(current_cluster) >= 10):
macro_clusters.append(current_cluster)
else:
micro_clusters.append(current_cluster)
#print("%d Macro Clusters" % (len(macro_clusters)))
return len(macro_clusters)
我在下一行运行以下代码。
confidence_bounds = [0.05, 0.1, 0.15, 0.2,0.25, 0.3, 0.35, 0.4, 0.45, 0.5]
#confidence_bounds = [0.45, 0.5]
results = []
for confidence_bound in confidence_bounds:
print('Confidence bound %f' % confidence_bound)
total = 0
for i in range(SIMULATIONS):
macro_clusters = run_with_confidence_bound(confidence_bound)
print('%d - %d macro clusters ' % (i, macro_clusters))
total += macro_clusters
average = total / float(SIMULATIONS)
print('Total: %f Average: %f' % (total, average))
results.append(average)
plt.plot(confidence_bounds, results, 'ro')
plt.ylabel('Average number of Macro Clusters (N >= 10)')
plt.xlabel('Confidence Bound')
plt.title("Deffuant model simulation - %d agents" % N)
plt.show()
运行这些代码后。我收到以下输出
Confidence bound 0.050000
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-26-0bd6f8844b00> in <module>()
7 total = 0
8 for i in range(SIMULATIONS):
----> 9 macro_clusters = run_with_confidence_bound(confidence_bound)
10 print('%d - %d macro clusters ' % (i, macro_clusters))
11 total += macro_clusters
<ipython-input-25-a1a064699954> in run_with_confidence_bound(confidence_bound)
53
54 while(biggest_change > 0.000001):
---> 55 biggest_change = run_N_times(G, G.edges(), confidence_bound)
56 #print('Biggest change in run %f'% biggest_change)
57
<ipython-input-25-a1a064699954> in run_N_times(G, edges, confidence_bound)
12
13 for i in range (N):
---> 14 (index1, index2) = random.choice(edges)
15 node1 = G.node[index1]
16 node2 = G.node[index2]
/anaconda3/lib/python3.7/random.py in choice(self, seq)
260 except ValueError:
261 raise IndexError('Cannot choose from an empty sequence') from None
--> 262 return seq[i]
263
264 def shuffle(self, x, random=None):
/anaconda3/lib/python3.7/site-packages/networkx/classes/reportviews.py in __getitem__(self, e)
927 # Mapping Methods
928 def __getitem__(self, e):
--> 929 u, v = e
930 return self._adjdict[u][v]
931
TypeError: cannot unpack non-iterable int object
我目前很困惑,因为我是编程和使用 python 或 jupyter 的初学者。我可以做些什么来纠正此代码的任何建议都将非常有帮助。谢谢!
解决方案
您需要将第 14 行中的边转换为列表,如下所示:
(index1, index2) = random.choice(list(edges))
在您的示例中,边是由 networkx 包定义的类型。但是,random.choice需要一个序列作为参数。Python 中的序列类型是str、unicode、list、tuple、buffer或xrange。在Python 文档中进一步描述了random模块及其方法random.choice : https ://docs.python.org/2/library/random.html#random.choice
推荐阅读
- python - 对象检测图像文件夹读取返回
返回 NULL 而不设置错误 - mysql - Doctrine DQL - 防止笛卡尔连接
- markdown - 如何在 m2r2 中使用“m2r_parse_relative_links”?
- javascript - 检查 discord bot 命令的参数是否与命令配置指定的格式匹配
- python - add_roles 的 Discord.py 问题
- r - 得到“不能对不存在的列进行子集化。” 当 dplyr 确实存在该列时
- vim - 我们能否在评论部分转义类型、代码等,以便拼写检查不会将它们视为拼写错误
- java - 配置 Swagger-ui 路径
- python - 不可能做到“从硒导入网络驱动程序”
- angular - 加载资源失败:服务器响应状态为 404 (Not Found)-lab-logo.png