実現したいこと
- 複数のグラフの平均をとって一つのグラフを出力する。
前提
ここに質問の内容を詳しく書いてください。
pythonで以下のようにネットワーク上のSIRモデルをシミュレーションすることを目指しております。最後、10回シミュレーションを行ってデータを重ねてグラフを描画するところまでは完了しました。しかし、その10個のグラフの平均をとって一つのグラフを作成する方法がよくわかりません。
発生している問題・エラーメッセージ
白紙のグラフが出力されました。
該当のソースコード
python
1import matplotlib.pyplot as plt 2import numpy as np 3import networkx as nx 4 5#ネットワークの設定。今回はBAモデル 6N=10000 #人口 7M=5 #次数 8G=nx.barabasi_albert_graph(N,M) 9 10#SIRモデルのシミュレーションを定義 11class SIR: 12 def __init__(self, G, beta, gamma): #ネットワーク、感染率、回復率を定義 13 self.G = G 14 self.beta = beta 15 self.gamma = gamma 16 17 def run(self, seed=[], num_steps = 1, sentinels = [], immunization_rate = 0.0, immunized_nodes = []): 18 #ネットワーク上の初期状態での免疫保持者をランダムに決定する。今回は0人。 19 if len(immunized_nodes) == 0: 20 immunized = set(np.random.choice(self.G.nodes(), 21 size=int(immunization_rate*len(self.G.nodes())), 22 replace=False)) 23 else: 24 immunized = immunized_nodes 25 26 # 初期状態でのIをランダムで決定する。 27 if len(seed) == 0: 28 seed = [np.random.choice(list(set(self.G.nodes()).difference(immunized)))] 29 30 #S,I,Rの初期状態 31 I_set = set(seed) 32 S_set = set(self.G.nodes()).difference(I_set).difference(immunized) 33 R_set = set() 34 35 t = 0 36 37 StoI = set(seed) 38 ItoR = set() 39 40 sentinels_t = {} 41 for sen in sentinels: 42 sentinels_t[sen] = 0 43 44 #I>0の場合、感染症が伝播 45 while len(I_set) > 0: 46 for i in I_set.copy(): 47 for s in set(self.G.neighbors(i)).intersection(S_set).copy(): 48 if np.random.uniform() < self.beta: 49 S_set.remove(s) 50 I_set.add(s) 51 StoI.add(s) 52 53 if sentinels_t.get(s) != None: 54 sentinels_t[s] = t 55 56 #回復率に従ってIをRに変化 57 if np.random.uniform() < self.gamma: 58 I_set.remove(i) 59 R_set.add(i) 60 ItoR.add(i) 61 62 t += 1 63 if t % num_steps == 0 or len(I_set) == 0: 64 yield({'t': t, 'S':S_set, 'I':I_set, 'R':R_set, 'StoI':StoI, 'ItoR':ItoR, 'sentinels': sentinels_t}) 65beta = 0.2 #感染率 66gamma = 0.1 #回復率 67 68peak_times = [] 69 70#複数のデータを一つのグラフにまとめる。 71plt.figure() 72ax = plt.subplot(111) 73ax.set_prop_cycle('color', ['green', 'red', 'blue']) 74 75#試行回数を決定。L回シミュレーションしてデータを重ねる。 76L=10 77for i in range(0,L): 78 sir = SIR(G, beta = beta, gamma = gamma) 79 ave = [] 80 sum=0 81 for r in sir.run(num_steps=1): 82 sum_S=sum+len(r['S']) 83 sum_I=sum+len(r['I']) 84 sum_R=sum+len(r['R']) 85 ave.append([sum_S, sum_I, sum_R]) 86 87 88 #データをプロット 89 plt.plot(ave) 90 91#結果をプロット 92plt.title("Infection On Network") 93plt.legend(['S', 'I', 'R']) 94plt.xlabel("day") 95plt.ylabel("Population") 96plt.show()
試したこと
numpyで平均値を取る関数を用いたりしましたが、うまくいきませんでした。
有識者の方、どうか解決法をご教授いただけませんでしょうか。

回答3件
あなたの回答
tips
プレビュー