Mittel 0 gelöst 0% Erfolgsquote

Information Gain

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

Das lernst du

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

Problem

Übersetzung anzeigen

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.

Einschränkungen

1 ≤ length ≤ 10,000

Each value and label is 1 to 20 characters

Beispiele

Beispiel 1
Eingabe:
labels = ["no", "no", "yes", "yes"]
feature = ["sunny", "sunny", "rain", "rain"]

Erwartete Ausgabe:
expected = 1.0
Eingabe:
std::vector<std::string> labels = {"no", "no", "yes", "yes"};
std::vector<std::string> feature = {"sunny", "sunny", "rain", "rain"};

Erwartete Ausgabe:
double expected = 1.0;
Eingabe:
string[] labels = new string[] {"no", "no", "yes", "yes"};
string[] feature = new string[] {"sunny", "sunny", "rain", "rain"};

Erwartete Ausgabe:
double expected = 1.0;

Erläuterung

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.

Beispiel 2
Eingabe:
labels = ["yes", "yes", "no", "no"]
feature = ["a", "b", "a", "b"]

Erwartete Ausgabe:
expected = 0.0
Eingabe:
std::vector<std::string> labels = {"yes", "yes", "no", "no"};
std::vector<std::string> feature = {"a", "b", "a", "b"};

Erwartete Ausgabe:
double expected = 0.0;
Eingabe:
string[] labels = new string[] {"yes", "yes", "no", "no"};
string[] feature = new string[] {"a", "b", "a", "b"};

Erwartete Ausgabe:
double expected = 0.0;

Erläuterung

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.

Referenzen

Diese Aufgabe wurde für CodeUtility angepasst. Beachte die oben genannten Vorgaben und Einschränkungen.

Von anderen lernen

Community-Lösungen

Noch keine veröffentlichten Lösungen. Löse die Aufgabe und teile als Erster eine Lösung.