بتل کد Battle Codeدارد باز می‌شود…

جواب «Closest Sentence» چالش 5 از جلسه‌ی 56

سؤال

تابع best_sentence(query, sentences) را خودت بنویس: بردار پرسش و بردار هر جمله را بساز و جمله‌ای با بیشترین کسینوس را همراه با شباهتش برگردان. خروجی سه خط است، هر خط به شکل query -> sentence (score): a puppy and a kitten -> my kitten ate an apple (0.819)، pizza for dinner -> we ordered pizza and apple juice (0.996) و my dog likes the car -> the dog chased the bus (0.988).

راهنما

qv = sentence_vector(query) را یک بار بساز، بعد روی جمله‌ها بچرخ و cosine(qv, sentence_vector(s)) را با بهترین تا این‌جا مقایسه کن. موقع چاپ round(float(score), 3).

یک جواب درست

import numpy as np

words = {
    "cat":    np.array([1.0, 0.0, 0.0, 0.3, 0.0]),
    "kitten": np.array([1.0, 0.0, 0.0, 0.1, 1.0]),
    "dog":    np.array([1.0, 0.0, 0.0, 0.5, 0.0]),
    "puppy":  np.array([1.0, 0.0, 0.0, 0.2, 1.0]),
    "car":    np.array([0.0, 0.0, 1.0, 0.6, 0.0]),
    "bus":    np.array([0.0, 0.0, 1.0, 1.0, 0.0]),
    "pizza":  np.array([0.0, 1.0, 0.0, 0.3, 0.0]),
    "apple":  np.array([0.0, 1.0, 0.0, 0.1, 0.0]),
}


def cosine(a, b):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))


def sentence_vector(text):
    vectors = [words[w] for w in text.lower().split() if w in words]
    return np.mean(vectors, axis=0)


sentences = [
    "the dog chased the bus",
    "my kitten ate an apple",
    "we ordered pizza and apple juice",
    "the car is faster than the bus",
]


def best_sentence(query, sentences):
    qv = sentence_vector(query)
    best, best_score = None, -2
    for s in sentences:
        score = cosine(qv, sentence_vector(s))
        if score > best_score:
            best, best_score = s, score
    return best, best_score


for q in ["a puppy and a kitten", "pizza for dinner", "my dog likes the car"]:
    s, score = best_sentence(q, sentences)
    print(f"{q} -> {s} ({round(float(score), 3)})")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن