9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでJaccard係数を実装

Posted at

#はじめに
学校でJaccard係数なるものがでてきたので, 自分で実装してみようと思います. その際, 参考にしたサイトは以下です.
参考サイト

#Jaccard係数
Jaccard係数は集合同士の類似度を示すものです.
集合Aと集合BのJaccard係数Jaccard(A,B)は
Jaccard(A,B) = |A∩B|/|A∪B|
と定義されます.
集合A = [1, 2, 3, 4], 集合B = [2, 3, 5, 7] とすると以下の図のように表現できます.
図1.png

JAccard係数は, 2つの集合の要素のうち共通要素がどれくらいの割合占めるかを表す値です. Jaccard係数の値が大きいほど, 2つの集合の類似度が高いことを示す.

#実装
実際のコードは以下のようになります. 例として集合を3つ作り, それぞれの集合の組み合わせのJaccard係数を求めるようにしています.

# coding:utf-8
import numpy as np
import itertools
from fractions import Fraction

# Jaccard係数を計算
def jaccard(x,y):
    # 積集合の要素数
    intersection = len(set.intersection(set(x), set(y)))    
    # 和集合の要素数
    union = len(set.union(set(x), set(y)))  
    # 分数表示で返す                 
    return Fraction(intersection , union)

A = np.array([1, 2, 3, 4])
B = np.array([2, 3, 5, 7])
C = np.array([2, 4, 6])
tmp = [A, B, C]
### すべてのリストの組合せ作成
tmp2 = list(itertools.combinations(tmp, 2))
###すべての組合せにjaccard適用
for i in tmp2:
    print(i[0],"&",i[1],":",jaccard(i[0], i[1]))
9
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?