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

جواب «Most Similar Word» چالش 3 از جلسه‌ی 55

سؤال

تابع most_similar(word) را کامل کن: روی همه‌ی کلمه‌ها بچرخد، خود word را رد کند و کلمه‌ای را که بیشترین شباهت کسینوسی را دارد با شباهتش برگرداند. خروجی سه خط: kitten -> puppy 0.998، bus -> car 0.97 و apple -> pizza 0.982.

راهنما

if other == word: continue، بعد s = cosine(words[word], words[other]) و اگر s > best_score بود، هر دو متغیر را عوض کن.

یک جواب درست

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 most_similar(word):
    best_word = None
    best_score = -1
    for other in words:
        if other == word:
            continue
        s = cosine(words[word], words[other])
        if s > best_score:
            best_word = other
            best_score = s
    return best_word, best_score


for w in ["kitten", "bus", "apple"]:
    other, score = most_similar(w)
    print(w, "->", other, round(float(score), 3))

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