جواب «Sorted Neighbours» چالش 4 از جلسهی 55
سؤال
تابع neighbours(word, k) را کامل کن: جفتهای (شباهت گردشده به ۳ رقم، کلمه) را برای همهی کلمههای دیگر بسازد، از بزرگ به کوچک مرتب کند و k تای اول را برگرداند. برنامه برای dog با k=3 هر همسایه را در یک خط چاپ میکند: cat 0.985، puppy 0.689، kitten 0.662.
راهنما
در حلقه: pairs.append((round(float(cosine(...)), 3), other)). آخر: sorted(pairs, reverse=True)[:k].
یک جواب درست
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 neighbours(word, k):
pairs = []
for other in words:
if other != word:
pairs.append((round(float(cosine(words[word], words[other])), 3), other))
return sorted(pairs, reverse=True)[:k]
for score, other in neighbours("dog", 3):
print(other, score)
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن