모든 챌린지
쉬움 1명 해결 정답률 100.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

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에 맞게 수정되었습니다. 위의 설명과 제약 조건을 기준으로 풀어 주세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 RCRiccardo Corti Python 834 ms - 5/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 풀이

스포일러: 아래에 전체 풀이 1개가 있습니다 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.