共有メンバーシップを見つける:転置
疎行列に変換すると、グラフのメタデータが失われることに気づいたかもしれません。ここでは、共有メンバーシップをさらに分析できるように、メタデータを推定して戻す方法を学びます。
前の演習で計算した user_matrix は、すでにワークスペースに読み込まれています。
ここでは np.where() 関数が役立ちます。例えば配列 a = [1, 5, 9, 5] があり、値が 5 の位置のインデックスを取得したい場合、idxs = np.where(a == 5) とします。これによりタプルに入った配列、つまり (array([1, 3]),) が返されます。これらのインデックスにアクセスするには、idxs[0] のようにタプルをインデックス指定します。
この演習はコースの一部です
Python 中級ネットワーク解析
演習の手順
- 最も多くのクラブに所属していた人の名前を見つけましょう。
- まず、
user_matrixに対して.diagonal()メソッドを用いてdiagを計算します。 - 次に、
np.where()を使って、diagがdiag.max()に等しいインデックスを選択します。これはタプルを返すので、[0]でタプルにインデックス指定して、必要なインデックスにアクセスしてください。 indicesを反復し、与えられたprint()関数を用いて、各インデックスiに対応するpeople_nodesの要素を出力します。
- まず、
- 対角成分をゼロに設定し、「座標形式(coordinate matrix format)」へ変換します。このコードは解答内に用意されています。
- 最も多くのクラブで所属が重なっていたユーザーの組を見つけましょう。
np.where()を使い、users_coo.dataがusers_coo.data.max()に等しいインデックスにアクセスします。indices2を反復し、各インデックスidxについて、users_coo.rowとusers_coo.colを用いて該当するpeople_nodeの要素を出力します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
import numpy as np
# Find out the names of people who were members of the most number of clubs
diag = ____
indices = np.where(____ == ____)[0]
print('Number of clubs: {0}'.format(diag.max()))
print('People with the most number of memberships:')
for i in indices:
print('- {0}'.format(____))
# Set the diagonal to zero and convert it to a coordinate matrix format
user_matrix.setdiag(0)
users_coo = user_matrix.tocoo()
# Find pairs of users who shared membership in the most number of clubs
indices2 = np.where(____ == ____)[0]
print('People with most number of shared memberships:')
for idx in indices2:
print('- {0}, {1}'.format(people_nodes[____.____[____]], people_nodes[____.____[____]]))