모든 챌린지
보통 0명 해결 정답률 0%

Information Gain

Compute how much splitting on a feature reduces entropy, the criterion behind ID3 decision trees.

배우게 될 내용

  • Compute entropy before and after a split
  • Weight subsets by their size
  • Pick the most informative feature

문제

번역본 보기

Entropy measures the uncertainty of a set of labels: H(S) = -Σ pₖ × log₂(pₖ), where pₖ is the fraction of labels of class k. Information gain is how much entropy drops when you split the set by a feature:

IG = H(labels) - Σ (|Sᵥ| / |S|) × H(Sᵥ)

where Sᵥ contains the labels of the samples whose feature equals v. Decision trees pick the feature with the highest gain.

Implement information_gain(feature, labels).

Input

feature: The feature value of each sample.

labels: The class label of each sample (same length).

Output

Return the information gain in bits, as a decimal number.

제약 조건

1 ≤ length ≤ 10,000

Each value and label is 1 to 20 characters

예시

예시 1
입력:
labels = ["no", "no", "yes", "yes"]
feature = ["sunny", "sunny", "rain", "rain"]

예상 출력:
expected = 1.0
입력:
std::vector<std::string> labels = {"no", "no", "yes", "yes"};
std::vector<std::string> feature = {"sunny", "sunny", "rain", "rain"};

예상 출력:
double expected = 1.0;
입력:
string[] labels = new string[] {"no", "no", "yes", "yes"};
string[] feature = new string[] {"sunny", "sunny", "rain", "rain"};

예상 출력:
double expected = 1.0;

설명

The labels are half yes and half no, so H = 1 bit. Splitting by weather gives two pure groups (H = 0 each), so the gain is 1 - 0 = 1: the feature tells you everything.

예시 2
입력:
labels = ["yes", "yes", "no", "no"]
feature = ["a", "b", "a", "b"]

예상 출력:
expected = 0.0
입력:
std::vector<std::string> labels = {"yes", "yes", "no", "no"};
std::vector<std::string> feature = {"a", "b", "a", "b"};

예상 출력:
double expected = 0.0;
입력:
string[] labels = new string[] {"yes", "yes", "no", "no"};
string[] feature = new string[] {"a", "b", "a", "b"};

예상 출력:
double expected = 0.0;

설명

Each group a and b still has one yes and one no (H = 1), so the remainder is 0.5 × 1 + 0.5 × 1 = 1 and the gain is 1 - 1 = 0: the feature is useless.

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.