簡単 0件解決済み 正答率0%

Softmax Function

Turn raw scores into probabilities that add up to 1, without overflowing on large values.

このチャレンジで学べること

  • Turn scores into probabilities
  • Subtract the maximum to avoid overflow
  • Make outputs sum to 1

問題

翻訳を表示

The softmax function turns a list of scores (logits) into probabilities. Language models use it to choose the next word:

softmax(x)_i = e^(x_i) / (e^(x_1) + e^(x_2) + … + e^(x_n))

Large scores make e^x overflow, so first subtract the largest score from every score. The result is mathematically the same.

Implement softmax(logits).

Input

logits: A list of scores.

Output

Return the list of probabilities, in the same order. They are all between 0 and 1 and add up to 1.

制約

1 ≤ length ≤ 1,000

-1,000 ≤ each score ≤ 1,000

例

例 1
入力:
logits = [1.0, 2.0, 3.0]

期待される出力:
expected = [0.090031, 0.244728, 0.665241]
入力:
std::vector<double> logits = {1.0, 2.0, 3.0};

期待される出力:
std::vector<double> expected = {0.090031, 0.244728, 0.665241};
入力:
double[] logits = new double[] {1.0, 2.0, 3.0};

期待される出力:
double[] expected = new double[] {0.090031, 0.244728, 0.665241};

解説

e¹ ≈ 2.718, e² ≈ 7.389 and e³ ≈ 20.086 add up to 30.193, so the probabilities are about [0.090031, 0.244728, 0.665241].

例 2
入力:
logits = [1000.0, 1000.0]

期待される出力:
expected = [0.5, 0.5]
入力:
std::vector<double> logits = {1000.0, 1000.0};

期待される出力:
std::vector<double> expected = {0.5, 0.5};
入力:
double[] logits = new double[] {1000.0, 1000.0};

期待される出力:
double[] expected = new double[] {0.5, 0.5};

解説

Computing e^1000 directly overflows. Subtracting the maximum gives [0, 0], and e⁰ / (e⁰ + e⁰) = 0.5 for both.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Subtract the largest logit before exponentiating so the largest transformed score becomes zero and overflow is avoided.

ヒント 2

Compute each exponent, sum them once, then divide every exponent by that total to get probabilities.

ヒント 3

Make sure the returned values stay in the same order as the input and still sum to one after normalization.

目安の計算量

O(n) time, O(n) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。