PHP Jaccard 유사성 지수 구현

Jmnote (토론 | 기여)님의 2014년 2월 19일 (수) 22:07 판 (→‎예제)
PHP Jaccard 유사성 지수 구현

1 함수

function jaccard_index($set1, $set2) {
	$union_cnt = count(array_unique(array_merge($set1, $set2)));
	if($union_cnt < 1)return -1;
	$intersect_cnt = count(array_intersect($set1, $set2));
	return $intersect_cnt / $union_cnt;
}

2 예제

<?php
function jaccard_index($set1, $set2) {
	$union_cnt = count(array_unique(array_merge($set1, $set2)));
	if($union_cnt < 1)return -1;
	$intersect_cnt = count(array_intersect($set1, $set2));
	return $intersect_cnt / $union_cnt;
}

$sets = array();
$sets[1] = array(3,5,6,7,8);
$sets[2] = array(1,2,3,4,5,6,8,9,10);
$sets[3] = array(2,3,9);
$sets[4] = array(1,2,3,4,5,6,8);

$cnt = count($sets);
echo "<table>";
echo "<th>구분</th>";
foreach(array_keys($sets) as $i) {
	echo "<th>$i</th>";
}
foreach($sets as $i => $set1) {
	echo "<tr>";
	echo "<th>$i</th>";
	foreach($sets as $j => $set2) {
		if($i == $j) {
			$j_index = '-';
		} else {
			$j_index = jaccard_index($set1, $set2);
			$j_index = number_format($j_index, 2);
		}
		echo "<td>$j_index</td>";
	}
	echo "</tr>";
}
echo "</table>";

3 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}