ง่าย 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

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก