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

جواب «Write the Analogy» چالش 3 از جلسه‌ی 56

سؤال

تابع analogy(words, a, b, c) را کامل کن: target = words[b] - words[a] + words[c]، بعد نزدیک‌ترین کلمه به target با کسینوس، به جز سه کلمه‌ی ورودی. خروجی سه خط: man : king = woman : queen، boy : prince = girl : princess و france : paris = iran : tehran.

راهنما

if w in (a, b, c): continue سه ورودی را رد می‌کند. بقیه همان «بهترین تا این‌جا» با cosine(target, words[w]) است.

یک جواب درست

import numpy as np

people = {
    "king":     np.array([0.95, 0.95, 0.9, 1.0]),
    "queen":    np.array([0.9, 0.1, 0.85, 1.0]),
    "man":      np.array([0.05, 0.95, 0.9, 1.0]),
    "woman":    np.array([0.05, 0.05, 0.9, 1.0]),
    "prince":   np.array([0.9, 0.95, 0.2, 1.0]),
    "princess": np.array([0.9, 0.05, 0.2, 1.0]),
    "boy":      np.array([0.05, 0.95, 0.1, 1.0]),
    "girl":     np.array([0.05, 0.05, 0.1, 1.0]),
}
places = {
    "paris":   np.array([1.0, 1.0, 0.0, 0.0, 1.0, 0.0]),
    "france":  np.array([0.0, 0.0, 1.0, 0.0, 1.0, 0.0]),
    "tehran":  np.array([1.0, 1.0, 0.0, 1.0, 0.0, 0.0]),
    "isfahan": np.array([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]),
    "iran":    np.array([0.0, 0.0, 1.0, 1.0, 0.0, 0.0]),
    "tokyo":   np.array([1.0, 1.0, 0.0, 0.0, 0.0, 1.0]),
    "japan":   np.array([0.0, 0.0, 1.0, 0.0, 0.0, 1.0]),
    "kyoto":   np.array([1.0, 0.0, 0.0, 0.0, 0.0, 1.0]),
}


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


def analogy(words, a, b, c):
    target = words[b] - words[a] + words[c]
    best, best_score = None, -2
    for w in words:
        if w in (a, b, c):
            continue
        s = cosine(target, words[w])
        if s > best_score:
            best, best_score = w, s
    return best


for words, a, b, c in [(people, "man", "king", "woman"),
                       (people, "boy", "prince", "girl"),
                       (places, "france", "paris", "iran")]:
    print(f"{a} : {b} = {c} : {analogy(words, a, b, c)}")

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