Word2Vec в Gensim с использованием model.most_similar

Я новичок в Word2Vec в Gensim. Я хочу построить модель Word2Vec для текста (извлечено из Википедии: машинное обучение) и найти слова, наиболее похожие на «машинное обучение».

Мой текущий код выглядит следующим образом.

# import modules & set up logging
from gensim.models import Word2Vec

sentences = "Machine learning is the subfield of computer science that, according to Arthur Samuel, gives computers the ability to learn without being explicitly programmed.[1][2][verify] Samuel, an American pioneer in the field of computer gaming and artificial intelligence, coined the term machine learning in 1959 while at IBM. Evolved from the study of pattern recognition and computational learning theory in artificial intelligence,[3] machine learning explores the study and construction of algorithms that can learn from and make predictions on data[4] – such algorithms overcome following strictly static program instructions by making data-driven predictions or decisions,[5]:2 through building a model from sample inputs. Machine learning is employed in a range of computing tasks where designing and programming explicit algorithms with good performance is difficult or infeasible; example applications include email filtering, detection of network intruders or malicious insiders working towards a data breach,[6] optical character recognition (OCR),[7] learning to rank, and computer vision."
# train word2vec on the sentences
model = Word2Vec(sentences, min_count=1)
vocab = list(model.wv.vocab.keys())
print(vocab[:10])

Однако для словаря я получаю вывод одного символа.

['M', 'a', 'c', 'h', 'i', 'n', 'e', ' ', 'l', 'r']

Пожалуйста, помогите мне получить most_similar_words с помощью model.most_similar


person Community    schedule 07.09.2017    source источник


Ответы (1)


Класс Word2Vec ожидает, что его корпус sentences будет итерируемым источником отдельных элементов, каждый из которых представляет собой список токенов слов.

Вы предоставляете одну строку. Если он перебирает это, он получает отдельные символы. Если затем он попытается интерпретировать эти отдельные символы как список токенов, он все равно получит один символ, поэтому единственные «слова», которые он видит, — это отдельные символы.

По крайней мере, вы бы хотели, чтобы ваш корпус был построен примерно так:

sentences = [
    "Machine learning is the subfield of computer science that, according to Arthur Samuel, gives computers the ability to learn without being explicitly programmed.[1][2][verify] Samuel, an American pioneer in the field of computer gaming and artificial intelligence, coined the term machine learning in 1959 while at IBM. Evolved from the study of pattern recognition and computational learning theory in artificial intelligence,[3] machine learning explores the study and construction of algorithms that can learn from and make predictions on data[4] – such algorithms overcome following strictly static program instructions by making data-driven predictions or decisions,[5]:2 through building a model from sample inputs. Machine learning is employed in a range of computing tasks where designing and programming explicit algorithms with good performance is difficult or infeasible; example applications include email filtering, detection of network intruders or malicious insiders working towards a data breach,[6] optical character recognition (OCR),[7] learning to rank, and computer vision.".split(),
]

Это по-прежнему всего одно «предложение», но оно будет разделено на пробелы на слова-токены.

Также обратите внимание, что полезные результаты word2vec требуют больших, разнообразных образцов текста — примеры размером с игрушку обычно не показывают виды сходства слов или расположения слов относительно слов, которыми славится word2vec.

person gojomo    schedule 07.09.2017
comment
Спасибо за ответ. Разделяя слова, модель рассматривает машинное обучение как машинное обучение». не так ли? Одним из решений может быть использование биграмм. Но тогда я могу пропустить три слова слова словосочетания? Следовательно, что я могу сделать для таких словосочетаний в этом отношении? - person ; 07.09.2017
comment
Кстати, я попробовал функцию split(). Тем не менее, я все еще получаю символ по символу вывода :( - person ; 07.09.2017
comment
Да, простая токенизация разделила бы «Машину» и «обучение». Вам решать, как вы предварительно обработаете свои данные, чтобы определить токены, которые передаются Word2Vec. Gensim включает класс Phrases, который может преобразовывать некоторые парные токены в биграммы на основе статистических частот; его можно применять в несколько проходов, чтобы затем создавать большие n-граммы. Но это отдельная тема от операции Word2Vec. - person gojomo; 07.09.2017
comment
sentences должен быть списком элементов, где каждый элемент сам является списком строк. Код, который я предоставил, должен работать; если вы все еще видите односимвольные словарные слова, вы уверены, что сделали то же самое? Если вы все сделали правильно, то печать sentences[0][0] должна вернуть "Machine". - person gojomo; 07.09.2017