始める無料で始める

共有メンバーシップを見つける:転置

疎行列に変換すると、グラフのメタデータが失われることに気づいたかもしれません。ここでは、共有メンバーシップをさらに分析できるように、メタデータを推定して戻す方法を学びます。

前の演習で計算した 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() を使って、diagdiag.max() に等しいインデックスを選択します。これはタプルを返すので、[0] でタプルにインデックス指定して、必要なインデックスにアクセスしてください。
    • indices を反復し、与えられた print() 関数を用いて、各インデックス i に対応する people_nodes の要素を出力します。
  • 対角成分をゼロに設定し、「座標形式(coordinate matrix format)」へ変換します。このコードは解答内に用意されています。
  • 最も多くのクラブで所属が重なっていたユーザーの組を見つけましょう。
    • np.where() を使い、users_coo.datausers_coo.data.max() に等しいインデックスにアクセスします。
    • indices2 を反復し、各インデックス idx について、users_coo.rowusers_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[____.____[____]]))  
コードを編集して実行