Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Softmax Function

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

1 ≤ length ≤ 1,000

-1,000 ≤ each score ≤ 1,000

Ví dụ

Ví dụ 1
Đầu vào:
logits = [1.0, 2.0, 3.0]

Kết quả mong đợi:
expected = [0.090031, 0.244728, 0.665241]
Đầu vào:
std::vector<double> logits = {1.0, 2.0, 3.0};

Kết quả mong đợi:
std::vector<double> expected = {0.090031, 0.244728, 0.665241};
Đầu vào:
double[] logits = new double[] {1.0, 2.0, 3.0};

Kết quả mong đợi:
double[] expected = new double[] {0.090031, 0.244728, 0.665241};

Giải thích

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].

Ví dụ 2
Đầu vào:
logits = [1000.0, 1000.0]

Kết quả mong đợi:
expected = [0.5, 0.5]
Đầu vào:
std::vector<double> logits = {1000.0, 1000.0};

Kết quả mong đợi:
std::vector<double> expected = {0.5, 0.5};
Đầu vào:
double[] logits = new double[] {1000.0, 1000.0};

Kết quả mong đợi:
double[] expected = new double[] {0.5, 0.5};

Giải thích

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.