
from Scratch
239
assert entropy([1.0]) == 0
assert entropy([0.5, 0.5]) == 1
assert 0.81 < entropy([0.25, 0.75]) < 0.82
입력 데이터는
(input, label)
쌍으로 구성되어 있기 때문에 각 클래스 레이블
의 확률은 별도로 계산해 주어야 한다. 엔트로피를 구할 때는 어떤 레이블에 어
떤 확률값이 주어졌는지까지는 알 필요가 없고, 레이블과 무관하게 확률값만 알
면 된다.
from typing import Any
from collections import Counter
def class
_
probabilities(labels: List[Any]) -> List[float]:
total
_
count = len(labels)
return [count / total
_
count
for count in Counter(labels).values()]
def data
_
entropy(labels: List[Any]) -> float:
return entropy(class
_
probabilities(labels))
assert data
_
entropy(['a']) == 0
assert data
_
entropy([True, False]) == 1
assert data
_
entropy([3, ...