Temperature چالش 5 از جلسهی 35، سخت
تابع next_word(word, temperature) بنویس: با احتمال temperature (یعنی اگر random.random() < temperature) کلمهی بعدی را تصادفی از جدول انتخاب کن، وگرنه محتملترین را. بعد generate(start, length, temperature) را طوری کامل کن که از next_word استفاده کند. برنامه با دمای ۰ (باید همیشه یکسان باشد) و دمای ۱ تولید میکند. خروجی خط اول حتماً the cat sat on the cat sat on است؛ خط دوم هر چیزی میتواند باشد.
import random
from collections import Counter
followers = {"the": ["cat", "mat", "cat", "fish"], "cat": ["sat", "ate"], "sat": ["on"], "on": ["the"], "mat": ["the"], "ate": ["the"]}
def most_likely(word):
return Counter(followers[word]).most_common(1)[0][0]
def next_word(word, temperature):
pass
def generate(start, length, temperature):
word = start
result = [word]
for i in range(length - 1):
if word not in followers:
break
# word = next_word(...)
result.append(word)
return " ".join(result)
random.seed(7)
print(generate("the", 8, 0))
print(generate("the", 8, 1))
راهنما و جواب این چالش · برگشت به درس جلسهی 35: پیشبینی کلمهی بعدی · چالش بعدی: Two Words of Context
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال