WeisbuchDeffuant模块

2024-04-29 13:43:43 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我需要一些帮助来运行一个代码,我在网上找到我的学校项目。我目前正在操作Jupyter笔记本电脑。你知道吗

%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的初学者。任何建议我能做什么来纠正这段代码将是非常有帮助的。谢谢!你知道吗


Tags: runincurrentchangemacroclustersclusterprint
1条回答
网友
1楼 · 发布于 2024-04-29 13:43:43

您需要将第14行中的转换为列表,如下所示:

(index1, index2) = random.choice(list(edges))

在您的示例中,是由networkx包定义的类型。但是,随机选择需要一个序列作为参数。Python中的序列类型有strunicodelisttuplebufferxrange。随机模及其方法随机选择在Python文档中有进一步的描述:https://docs.python.org/2/library/random.html#random.choice

相关问题 更多 >