1

Создаю вручную мешок слов. Вот функция для его создания:

def my_bag_of_words(text, words_to_index, dict_size):
    """
        text: a string
        dict_size: size of the dictionary

        return a vector which is a bag-of-words representation of 'text'
    """
    result_vector = np.zeros(dict_size)
    sentence_tokens = nltk.word_tokenize(text_prepare(text))
    attributes = []
    for i, k in words_to_index.items():
      while len(attributes)<=dict_size:
        attributes.append(i)
    for i in sentence_tokens: 
      for k in attributes:
        if i==k:
          result_vector[attributes.index(i)]=+1

    return result_vector

Функция возвращает 1, если слово в тексте есть в атрибутах и 0 - если его нет.

Проверяю эту функцию:

def test_my_bag_of_words():
    words_to_index = {'hi': 0, 'you': 1, 'me': 2, 'are': 3}
    examples = ['hi how are you']
    answers = [[1, 1, 0, 1]]
    for ex, ans in zip(examples, answers):
        if (my_bag_of_words(ex, words_to_index, 4) != ans).any():
          print(my_bag_of_words(ex, words_to_index, 4))
          return "Wrong answer for the case: '%s'" % ex
    return 'Basic tests are passed.'
print(test_my_bag_of_words())

Результат:

[1. 0. 0. 0.]
Wrong answer for the case: 'hi how are you'

Если функция правильно создана, должно вывести:

[1, 1, 0, 1]
Basic tests are passed

Т. е. после увеличение первого элемента массива на 1, функция далее прекращает работу. Помогите пжл понять, в чем ошибка

1 ответ 1

1

Для начала предлагаю оптимизировать генерацию атрибутов:

attributes = list(words_to_index.keys())

А затем упростить последнюю часть кода:

for i in sentence_tokens:
    result_vector[attributes.index(i)] = int(i in attributes)

В таком случае, ответ будет таким: answers = [[1, 0, 1, 1]], потому что отсутствующее в словаре слово how находится на второй позиции.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.