Вы обучаете FastText SkipGram Negative Sampling с окном заданной ширины (аналогично…
- User
Вы обучаете FastText SkipGram Negative Sampling с окном заданной ширины (аналогично первой задаче). Общий алгоритм обучения также описывался ранее. Единственное существенное отличие от Word2Vec - использование N-грамм для получения вектора центрального слова.
Напишите функцию, которая генерирует обучающие примеры из текста. Каждый обучающий пример должен иметь вид кортежа из трёх элементов (CenterSubwords,CtxWord,Label), где CenterSubwords - список идентификаторов N-грамм, входящих в токен в центре окна (включая идентификатор самого токена), CtxWord∈N - идентификатор соседнего токена, Label∈{0,1} - 1 если CtxWord настоящий и 0, если это отрицательный пример.
Функция должна возвращать список обучающих примеров. Аргумент ns_rate задаёт количество отрицательных примеров, которое нужно сгенерировать на каждый положительный пример.
Входной текст уже токенизирован, токены заменены на их идентификаторы.
Для получения списка N-грамм, входящих в токен, используется заранее построенный словарь (он передаётся в функцию, которую Вам нужно написать). В этом задании следует считать, что сам токен всегда есть в словаре и поэтому нужно обновлять вектор для него (хотя при обучении FastText на настоящих данных это может быть не так). Все n-граммы имеют номера больше или равные vocab_size.
Тесты генерируются случайно, ограничения:
len(text) < 20 vocab_size < 10 window_size <= 11, нечётное ns_rate < 3 ngrams_n < 20 Слова имеют идентификаторы 0..vocab_size - 1 (как возвращает np.random.randint). N-граммы имеют идентификаторы vocab_size .. vocab_size + ngrams_n - 1.
Обратите также внимание на то, что -3 // 2 != -(3 // 2).
import sys import ast import numpy as np
def read_list(): return ast.literal_eval(sys.stdin.readline())
def parse_array(s): return np.array(ast.literal_eval(s), dtype=object)
def read_array(): return parse_array(sys.stdin.readline())
def write_array(arr): print(repr(arr.tolist()))
def generate_ft_sgns_samples(text, window_size, vocab_size, ns_rate, token2subwords): """ text - list of integer numbers - ids of tokens in text window_size - odd integer - width of window vocab_size - positive integer - number of tokens in vocabulary ns_rate - positive integer - number of negative tokens to sample per one positive sample token2subwords - list of lists of int - i-th sublist contains list of identifiers of n-grams for token #i (list of subword units)
returns list of training samples (CenterSubwords, CtxWord, Label) """ return your code heretext = read_array() window_size = int(sys.stdin.readline().strip()) vocab_size = int(sys.stdin.readline().strip()) ns_rate = int(sys.stdin.readline().strip()) token2subwords = read_list()
result = generate_ft_sgns_samples(text, window_size, vocab_size, ns_rate, token2subwords)
print(repr(result))
Assistant
import sys import ast import numpy as np import random # Although numpy is used for random choice, random might be slightly more familiar for lists def read_list(): return ast.literal_eval(sys.stdin.readline()) def parse_array(s): # ast.literal_eval can safely handle lists of integers and nested lists for token2subwords return ast.literal_eval(s) def read_array(): return parse_array(sys.stdin.readline()) def write_array(arr): # Ensure output format is correct, repr handles lists/tuples appropriately print(repr(arr)) def generate_ft_sgns_samples(text, window_size, vocab_size, ns_rate, token2subwords): """ text - list of integer numbers - ids of tokens in text window_size - odd integer - width of window vocab_size - positive integer - number of tokens in vocabulary ns_rate - positive integer - number of negative tokens to sample per one positive sample token2subwords - list of lists of int - i-th sublist contains list of identifiers of n-grams for token #i (list of subword units) returns list of training samples (CenterSubwords, CtxWord, Label) """ samples = [] # Calculate the context window radius on one side of the center word context_radius = (window_size - 1) // 2 for center_idx in range(len(text)): center_token_id = text[center_idx] # Get the list of subword (n-gram) IDs for the center token # The problem guarantees the token itself is included and index exists center_subwords = token2subwords[center_token_id] # Determine the start and end indices for the context window # Ensure window stays within the bounds of the text ctx_start = max(0, center_idx - context_radius) ctx_end = min(len(text), center_idx + context_radius + 1) # +1 because range is exclusive # Iterate through potential context indices within the window for ctx_idx in range(ctx_start, ctx_end): # Skip the center word itself if ctx_idx == center_idx: continue ctx_token_id = text[ctx_idx] # 1. Add the positive sample (CenterSubwords, CtxWord, 1) samples.append((center_subwords, ctx_token_id, 1)) # 2. Add ns_rate negative samples for _ in range(ns_rate): # Sample a random negative token from the entire vocabulary negative_token_id = np.random.randint(0, vocab_size) samples.append((center_subwords, negative_token_id, 0)) return samples # Read input from stdin text = read_array() window_size = int(sys.stdin.readline().strip()) vocab_size = int(sys.stdin.readline().strip()) ns_rate = int(sys.stdin.readline().strip()) token2subwords = read_list() # token2subwords is a list of lists # Generate samples result = generate_ft_sgns_samples(text, window_size, vocab_size, ns_rate, token2subwords) # Print the result in the required format write_array(result)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.