ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

One-Hot Encoding

Turn categories into vectors with a single 1, the input format for classifiers and embeddings.

สิ่งที่คุณจะได้เรียนรู้

  • Map categories to vector positions
  • Build one-hot rows for each label
  • Prepare categorical data for models

โจทย์

ดูฉบับแปล

Models need numbers, not words. One-hot encoding turns each category into a vector with one position per category: 1 at the category's position and 0 everywhere else.

Order the categories alphabetically. For each label, output its one-hot vector.

Implement one_hot(labels).

Input

labels: A list of category names.

Output

Return a matrix with one row per label and one column per distinct category (alphabetical order).

เงื่อนไข

1 ≤ length ≤ 1,000

Each label is 1 to 20 characters

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
labels = ["red", "green", "blue", "green"]

ผลลัพธ์ที่คาดหวัง:
expected = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 0],
    [0, 1, 0]
]
อินพุต:
std::vector<std::string> labels = {"red", "green", "blue", "green"};

ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<long long>> expected = {
    {0, 0, 1},
    {0, 1, 0},
    {1, 0, 0},
    {0, 1, 0}
};
อินพุต:
string[] labels = new string[] {"red", "green", "blue", "green"};

ผลลัพธ์ที่คาดหวัง:
long[][] expected = new long[][] {
    new long[] {0, 0, 1},
    new long[] {0, 1, 0},
    new long[] {1, 0, 0},
    new long[] {0, 1, 0}
};

คำอธิบาย

The categories in alphabetical order are blue, green, red. So red → [0, 0, 1], green → [0, 1, 0] and blue → [1, 0, 0].

ตัวอย่างที่ 2
อินพุต:
labels = ["yes"]

ผลลัพธ์ที่คาดหวัง:
expected = [
    [1]
]
อินพุต:
std::vector<std::string> labels = {"yes"};

ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<long long>> expected = {
    {1}
};
อินพุต:
string[] labels = new string[] {"yes"};

ผลลัพธ์ที่คาดหวัง:
long[][] expected = new long[][] {
    new long[] {1}
};

คำอธิบาย

There is only one category, so every vector is [1].

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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