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).
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",
]
# write best_sentence(query, sentences) and print the three lines
for q in ["a puppy and a kitten", "pizza for dinner", "my dog likes the car"]:
pass
راهنما و جواب این چالش · برگشت به درس جلسهی 56: تعبیهی کلمه ۲ · چالش بعدی: Neutralise the Bias
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال