Continuous bag of word

В этой статье подробно разбирается алгоритм обучения архитектуры CBOW (Continuous Bag of Words), которая появилась в 2013 году и дала сильный толчок в решении задачи векторного представления слов, т.к. в первый раз на практике использовался подход на основе нейронных сетей. Архитектура CBOW не столь требовательна к наличию GPU и вполне может обучаться на ЦП (хотя и более медленно). Большие готовые модели, обученные на википедии или новостных сводках, вполне могут работать на 4-х ядерном процессоре, показывая приемлемое время отклика.

Архитектура CBOW

CBOW архитектура была предложена группой исследователей из компании Google в 2013 году совместно с Skip-gram моделью. Логика CBOW архитектуры очень проста: предсказать слово в зависимости от контекста, в котором находится это слово. Пример архитектуры нейронной сети в самом простом варианте реализации CBOW при использовании всего одного слова (контекста) перед целевым словом приведен на рисунке 1. В дальнейшем в статье мы перейдем от простой модели на основе одного слова к большему контексту.

Рисунок 1. Архитектура CBOW при одном слове в контексте.

Рисунок 1. Архитектура CBOW при одном слове в контексте.

Архитектура нейронной сети состоит из одного слоя размерности  корпуса текста, иначе говоря, длина словаря. Скрытый слой имеет размерность N. Выходной слой имеет такую же размерность, как и входной слой. Функция активации скрытого слоя является линейной, а в выходном слое – обобщенной логистической функцией активации:

Матрица весов между входным слоем и скрытым обозначена буквой W и имеет размерность V x N. Веса между скрытым слоем и выходным обозначим W’, они будут иметь размерность N x V. Стоит отметить, что перед обучением необходимо векторизовать слова. Сделать это можно с помощью простого унитарного кода или, например, статистической меры TFIDF.

Рассмотрим, как будет рассчитываться выходное значение, исходя из архитектуры, представленной на рисунке 1. Вначале веса инициализируются с помощью стандартного нормального распределения. Затем рассчитываются значения в скрытом слое по формуле:

Точно так же рассчитываются значения после прохождения скрытого слоя, но до попадания в функцию активации выходного слоя.

Выбор функции потерь для оценки выходного слоя нейронной сети основывается на получении диапазона значений в промежутке от 0 до 1. При этом, учитывая, что на выходе мы имеем логистическую функцию активации, которую в данной задаче можно интерпретировать как условную вероятность появления слова после определенного контекста, функцию потерь мы можем задать следующим образом:

где  wt – целевое слово,  wc – контекстное слово.

Немного преобразовав, можно получить более простую запись:

Для решения поставленной задачи нам требуется минимизировать данную функцию потерь и максимизировать вероятность того, что модель предсказывает целевое слово с учетом контекста (на данном этапе состоящего из одного слова).

Обучение CBOW при одном слове в контексте

Получив выражение функции потерь, необходимо найти минимизирующие её значения W и W’. Проблема оптимизации нейронных сетей чаще всего решается с помощью градиентного спуска. Для того чтобы реализовать алгоритм обратного распространения ошибки, основанный на градиентном спуске, необходимо найти частные производные

Проще всего установить взаимосвязь между W, W’ и функцией потерь через вектор

то есть можно записать следующее соотношение:

Таким образом, для частных производных будет справедливо:

Этих соотношений достаточно для обучения CBOW архитектуры.

Рассмотрим возможности упрощения модели. Заметим, что вес W’ij, который является элементом W’, соединяет узел i скрытого слоя с узлом j выходного слоя. То есть W’ij влияет только на оценку uj (а также yj) как показано на рисунке 2. Это происходит из-за того, что в упрошенной модели (при использовании одного слова в контексте) вектор x, подающийся на вход нейронной сети, будет содержать нули с x0 до xV включительно за исключением точки xk, где будет стоять единица. То есть после прохождения функции активации все веса W’ij за исключением hj, будут равны 0. Данное предположение справедливо в случае использования векторизации на основе унитарного кода.

Рисунок 2. Влияние xk на W’.

Рисунок 2. Влияние xk на W’.

Исходя из вышесказанного, можно предположить, что частная производная

 равна нулю везде, кроме k = j. Тогда можно переписать производную следующим образом:

Преобразуем теперь

как

где

– дельта Кронекера – функция от 2 переменных, которая равна 1, когда , а в остальных случаях равна 0. Для второй части уравнения мы имеем:

Тогда после объединения левой и правой части получаем:

Аналогично можно выполнить те же операции для производной

однако стоит отметить, что после фиксации входа xk выход в узле j будет зависеть от всех элементов матрицы W, как показано на рисунке 3.

Рисунок 3. Влияние xk на W.

Рисунок 3. Влияние xk на W.

Перед тем как преобразовать

можно отдельно выписать uk из вектора u:

Из этого уравнения легко можно выписать производную

так как единственный член, который останется после действия суммы, будет тот, в котором l = i и m = j. Таким образом,

Собирая все воедино, получаем:

Проведя все преобразования, мы получили все необходимые соотношения для реализации первого «обучающего» прохода для алгоритма градиентного спуска. Для того чтобы применить алгоритм градиентного спуска, необходимо теперь выбрать скорость обучения

В общем случае скорость обучения является гиперпараметром к любой модели машинного обучения или нейронных сетей. С выбором параметра могут возникнуть трудности, а именно: при выборе большого параметра алгоритм может перепрыгнуть точку минимума функции или вообще «застрять», прыгая из стороны в сторону, но так и не достигнув минимума. В случае же более низких значений скорость обучения будет очень медленной. Однако стоит отметить, что в данном случае пропустить точку минимума очень трудно. Рекомендуется использовать коэффициент в диапазоне

Обновление весов W и W’ происходит по следующей формуле:

Одного шага для нахождения минимума даже такой простой архитектуры, как CBOW, недостаточно. Поэтому при обучении нейронных сетей имеется еще один важный параметр, а именно количество эпох.

Эпоха – один полный цикл обучения, то есть прохождение всех обучающих примеров ровно 1 раз. Выбор количества эпох зависит только от исследователя и от того, сколько он намерен ждать, пока его сеть обучится. При наличии возможности выбора большого количества эпох коэффициент обучения выбирается близким к нулю.

Обучение CBOW в общем виде

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

Рисунок 4. Архитектура CBOW в общем случае.

Рисунок 4. Архитектура CBOW в общем случае.

Входные данные представляют собой контекстные слова, закодированные унитарно. Количество контекстных слов C зависит от нашего выбора (сколько контекстных слов мы хотим использовать). Скрытый слой становится средним значением, полученным из каждого контекстного слова.

Общая архитектура CBOW имеет те же уравнения, что и архитектура из одного слова, но только обобщенная на случай использования произвольного количества контекстных слов C:

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

Производные функции потерь вычисляются так же, как и при использовании одного слова в контексте, за исключением того, что входной вектор

заменяется на среднее по входному вектору

Как видно, общая архитектура и процесс обучения легко могут быть выведены из простой модели, использующей всего  одно слово в контексте.

Алгоритм векторизации текста на основе CBOW архитектуры может применяться и в современных системах, потому что в отличии от BERTa и ELMo обладает более высокой скоростью работы при использовании CPU. Особенно часто такие реализации можно встретить у клиентов, не обладающих достаточными вычислительными мощностями. Более подробно об одном таком случае вы можете прочитать в нашей следующей статье.

To implement Word2Vec, there are two flavors which are — Continuous Bag-Of-Words (CBOW) and continuous Skip-gram (SG)

In this post I will explain only Continuous Bag of Word (CBOW) model with a one-word window to understand continuous bag of word (CBOW) clearly. If you can understand CBOW with single word model then multiword CBOW model will be so easy to you.

While explaining, I will present a few small examples with a text containing a few words. However, keep in mind that word2vec is typically trained with billions of words.

It attempts to guess the output (target word) from its neighboring words (context words). You can think of it like fill in the blank task, where you need to guess word in place of blank by observing nearby words.

Continuous Bag of Words (CBOW) single-word model:

In this section we will be implementing the CBOW for single-word architecture of Word2Vec. The content is broken down into the following steps:

Data Preparation: Defining corpus by tokenizing text.

Generate Training Data: Build vocabulary of words, one-hot encoding for words, word index.

Train Model: Pass one hot encoded words through forward pass, calculate error rate by computing loss, and adjust weights using back propagation.

Output: By using trained model calculate word vector and find similar words.

I will explain CBOW steps without code but if you want full working code of CBOW with numpy from scratch, I have separate post for that, you can always jump into that.

Also Read:

  • Word2vecSkip-gram Explained
  • Continuous Bag ofWords (CBOW) – Multi Word Model – How It Works 

1. Data Preparation:

Let’s say we have a text like below:

i like natural language processing

To make it simple I have chosen a sentence without capitalization and punctuation. Also I will not remove any stop words (“and”, “the” etc.) but for real world implementation you should do lots of cleaning task like stop word removal, replacing digits, remove punctuation etc.

After pre-processing we will convert the text to list of tokenized word.

[“i”, “like”, “natural”, “language”, “processing”]

2. Generate training data:

Unique vocabulary: Find unique vocabulary list. As we don’t have any duplicate word in our example text, so unique vocabulary will be:

[“i”, “like”, “natural”, “language”, “processing”]

Now to prepare training data for single word CBOW model, we define “target word” as the word which follows a given word in the text (which will be our “context word”). That means we will be predicting next word for a given word.

Now let’s construct our training examples, scanning through the text with a window will prepare a context word and a target word, like so:

For example, for context word “i” the target word will be “like”. For our example text full training data will looks like:

One-hot encoding: We need to convert text to one-hot encoding as algorithm can only understand numeric values.

For example encoded value of the word “i”, which appears first in the vocabulary, will be as the vector [1, 0, 0, 0, 0]. The word “like”, which appears second in the vocabulary, will be encoded as the vector [0, 1, 0, 0, 0]

So let’s see overall set of context-target words in one hot encoded form:

So as you can see above table is our final training data, where encoded target word is Y variablefor our model and encoded context word is X variable for our model.

Now we will move on to train our model.

3. Training Model:

So far, so good right? Now we need to pass this data into the basic neural network with one hidden layer and train it. Only one thing to note is that the desire vector dimension of any word will be the number of hidden nodes.

For this tutorial and demo purpose my desired vector dimension is 3. For example:

“i” => [0.001, 0.896, 0.763]  so number of hidden layer node will be 3.

Dimension (n): It is dimension of word embedding you can treat embedding as number of features or entity like organization, name, gender etc. It can be 10, 20, 100 etc. Increasing number of embedding layer will explain a word or token more deeply. Just for an example Google pre-trained word2vec have dimension of 300.

1. Create model Architecture

2. Forward Propagation

3. Error Calculation

4. Weight tuning using backward pass

3.1 Model Architecture:

Let’s look back to our example text “I like natural language processing”. Suppose we are training the model against the first training data point where the context word is “i” and the target word is “like”. 

Ideally, the values of the weights should be such that when the input x=(1,0,0,0) – which is for the word “i” is given to the model –it will produce output which should close to y=(0,1,0,0) – which is the word “like”.

So now let’s create weight matrix for input to hidden layer (w).

Above picture shows how I have created weighted matrix for first two input nodes. So in the similar manner if we are creating weight matrix for all input nodes it should looks like below, whose dimension will be [3 X 5], in different way it’s 

[N x V]

Where: 

N: Number of embedding layer/ hidden unit

V: Number of unique vocabulary size

cbow equation

Now let’s create weight matrix for hidden to output layer (w/).

So in the similar manner (shown in the above picture) if we are creating weight matrix for all hidden nodes it should looks like below, whose dimension will be [5 X 3], in different way it’s [V X N] 

cbow formula in hand

So final vectorized form of CBOW model should look like below:

CBOW Vectorized form:

Where V is number of unique vocabulary and N is number of embedding layers (number of hidden units)

Please refer to picture of CBOW vectorized form, if you have any confusion in below calculations.

Calculate hidden layer matrix (h):

So now:

cbow hidden layer calculation

Calculate output layer matrix (u):

So now:

cbow python

Calculate final Softmax output (y):

So:

y1 = Softmax (u1)

y2 = Softmax (u2)

y3 = Softmax (u3)

y4 = Softmax (u4)

y5 = Softmax (u5)

Now as you know softmax calculate probability for every possible class. Softmax function uses exponential as we want to get output from softmax in a range between 0 to 1.

Let’s have a look for only one (first) output from softmax function:

cbow architecture

So now if we want to generalize above equation (as the above equation for first output from softmax) we can write:

cbow output layer

3.3 Error Calculation:

As we have done with forward propagation, now we need to calculate error to know how accurately our model is performing and update weights (w and w/) accordingly.

As you know to calculate error we must have an actual value. That actual value needs to compare with predicted value.

For single word model next word is the target word for previous word.

Here we will be using log loss function to calculate error. First let’s have a look at generalized equation to minimize error/ log loss:

[E=-log(w_t|w_c)]

Where 

wt = Target word

wc = Context word

So now let’s calculate error / loss for first iteration only. For the first iteration “like” will be the target word and its position is 2.

So,

cbow error calculation from beginning

So now if we want to generalize above equation we can write like this:

error of Continuous Bag of Words

Where j* is the index of the actual word (target word) in the output layer. For first iteration index of target word is 2. So for first iteration j* will be 2 as position of word “like” is 2.

3.5 Back Propagation:

As we have done with forward propagation and error calculation now we need to tune weight matrices through back propagation.

Back propagation is required to update weight matrices (w and w/). To update weight we need to calculate derivative of loss with respect to each weight and subtract those derivatives with their corresponding weight. It’s called gradient descent technique to tune weight.

Let’s take a look for only one example to update second weight (w/).

In this back propagation phase we will update weight of all neurons from hidden layer to output (w/11 , w/12, w/13 …. w/15)

Step1: Gradient of E with respect to w/11:

derivative of Continuous Bag of Words

Now as we know

total loss of cbowgradient descent in cbow

Derivative of log function with chain rule.

error calculation of cbow

We can generalize above derivative as:

Taking derivative of E with respect to uj:

final loss of cbow from scrach

Note: tj=1 if tj = tj* else tj = 0

That means tj is the actual output and yj is the predicted output. So ej is the error.

So for first iteration,

cbow output formulaContinuous Bag of Words formula

Now finally coming back to main derivative which we were trying to solve:

Continuous Bag of Words equation

So generalized form will looks like below:

Continuous Bag of Words from scratch

Step2: Updating the weight of w/11:

weight calculation cbow

Note: To keep it simple I am not considering any learning rate here.

Similarly we can update weight of w/12, w/13 …. w/35.

Now let’s update 1stweight which (w).

Step1: Gradient of E with respect to w11:

In this back propagation phase we will update weight of all neurons from input layer to hidden layer (w11, w12, …..w53)

Again I will take you through only first weigh (w11)

cbow error

As to change E with respect to h1, u1to u5 all are involved.

So,

cbow in numpy

As for u1 and h1,

cbow in pythonmath behind cbow

Now finally:

cbow loss

Step2: Updating the weight of w11:

weight function of cbow

Note: Again to keep it simple I am not considering any learning rate here.

Similarly we can update weight of w12, w13 … W53.

Final CBOW Word2Vec:

After doing above training process for many iteration final trained model comes with tuned and proper weights. At the end of entire training process we will consider first weight matrix (w) as our vector for our given sentence.

For example:

Our sentence or document wasi like natural language processing

And let’s say first weight of our trained model is:

weight of cbow

So word2vce of word “i” will be [w11, w12, w13]

Similarly word2vec for all word will be as follows:

Also Read:

  • Word2vecSkip-gram Explained
  • Continuous Bag ofWords (CBOW) – Multi Word Model – How It Works 

Conclusion:

Now to conclude let’s recall our generalized equations:

Forward Propagation:

cbow

Back Propagation:

1. Update second weight (w/11):

cbow explained

General Vector Notation:

Continuous Bag of Words explained

Note:Symbol  denotes the outer product. In Python this can be obtained using the numpy.outermethod

2. Update second weight (w11):

cbow architecture explained

General Vector Notation:

cbow formula explained

Note:Symbol  denotes the outer product. In Python this can be obtained using the numpy.outer method

If you have any question or suggestion regarding this topic see you in comment section. I will try my best to answer.

Word2vec is considered one of the biggest breakthroughs in the development of natural language processing. The reason behind this is because it is easy to understand and use. Word2vec is basically a word embedding technique that is used to convert the words in the dataset to vectors so that the machine understands. Each unique word in your data is assigned to a vector and these vectors vary in dimensions depending on the length of the word. 

The word2vec model has two different architectures to create the word embeddings. They are:

  1. Continuous bag of words(CBOW)
  2. Skip-gram model 

In this article, we will learn about what CBOW is, the model architecture and the implementation of a CBOW model on a custom dataset. 

AIM Daily XO

Join our editors every weekday evening as they steer you through the most significant news of the day, introduce you to fresh perspectives, and provide unexpected moments of joy

Your newsletter subscriptions are subject to AIM Privacy Policy and Terms and Conditions.

What is the CBOW Model?

The CBOW model tries to understand the context of the words and takes this as input. It then tries to predict words that are contextually accurate. Let us consider an example for understanding this. Consider the sentence: ‘It is a pleasant day’ and the word ‘pleasant’ goes as input to the neural network. We are trying to predict the word ‘day’ here. We will use the one-hot encoding for the input words and measure the error rates with the one-hot encoded target word. Doing this will help us predict the output based on the word with least error. 

The Model Architecture

cbow

The CBOW model architecture is as shown above. The model tries to predict the target word by trying to understand the context of the surrounding words. Consider the same sentence as above, ‘It is a pleasant day’.The model converts this sentence into word pairs in the form (contextword, targetword). The user will have to set the window size. If the window for the context word is 2 then the word pairs would look like this: ([it, a], is), ([is, pleasant], a),([a, day], pleasant). With these word pairs, the model tries to predict the target word considered the context words. 


Download our Mobile App


If we have 4 context words used for predicting one target word the input layer will be in the form of four 1XW input vectors. These input vectors will be passed to the hidden layer where it is multiplied by a WXN matrix. Finally, the 1XN output from the hidden layer enters the sum layer where an element-wise summation is performed on the vectors before a final activation is performed and the output is obtained. 

Implementation of the CBOW Model

For the implementation of this model, we will use a sample text data about coronavirus. You can use any text data of your choice. But to use the data sample I have used click here to download the data.

Now that you have the data ready, let us import the libraries and read our dataset. 

import numpy as np
import keras.backend as K
from keras.models import Sequential
from keras.layers import Dense, Embedding, Lambda
from keras.utils import np_utils
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
import gensim
data=open('/content/gdrive/My Drive/covid.txt','r')
corona_data = [text for text in data if text.count(' ') >= 2]
vectorize = Tokenizer()
vectorize.fit_on_texts(corona_data)
corona_data = vectorize.texts_to_sequences(corona_data)
total_vocab = sum(len(s) for s in corona_data)
word_count = len(vectorize.word_index) + 1
window_size = 2

In the above code, I have also used the built-in method to tokenize every word in the dataset and fit our data to the tokenizer. Once that is done, we need to calculate the total number of words and the total number of sentences as well for further use. As mentioned in the model architecture, we need to assign the window size and I have assigned it to 2. 

The next step is to write a function that generates pairs of the context words and the target words. The function below does exactly that. Here we have generated a function that takes in window sizes separately for target and the context and creates the pairs of contextual words and target words. 

def cbow_model(data, window_size, total_vocab):
    total_length = window_size*2
    for text in data:
        text_len = len(text)
        for idx, word in enumerate(text):
            context_word = []
            target   = []            
            begin = idx - window_size
            end = idx + window_size + 1
            context_word.append([text[i] for i in range(begin, end) if 0 <= i < text_len and i != idx])
            target.append(word)
            contextual = sequence.pad_sequences(context_word, total_length=total_length)
            final_target = np_utils.to_categorical(target, total_vocab)
            yield(contextual, final_target) 

Finally, it is time to build the neural network model that will train the CBOW on our sample data.

model = Sequential()
model.add(Embedding(input_dim=total_vocab, output_dim=100, input_length=window_size*2))
model.add(Lambda(lambda x: K.mean(x, axis=1), output_shape=(100,)))
model.add(Dense(total_vocab, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
for i in range(10):
    cost = 0
    for x, y in cbow_model(data, window_size, total_vocab):
        cost += model.train_on_batch(contextual, final_target)
    print(i, cost)

cbow

Once we have completed the training its time to see how the model has performed and test it on some words. But to do this, we need to create a file that contains all the vectors. Later we can access these vectors using the gensim library. 

dimensions=100
vect_file = open('/content/gdrive/My Drive/vectors.txt' ,'w')
vect_file.write('{} {}n'.format(total_vocab,dimensions))

Next, we will access the weights of the trained model and write it to the above created file. 

weights = model.get_weights()[0]
for text, i in vectorize.word_index.items():
    final_vec = ' '.join(map(str, list(weights[i, :])))
    vect_file.write('{} {}n'.format(text, final_vec))
vect_file.close()

Now we will use the vectors that were created and use them in the gensim model. The word I have chosen in ‘virus’.

cbow_output = gensim.models.KeyedVectors.load_word2vec_format('/content/gdrive/My Drive/vectors.txt', binary=False)
cbow_output.most_similar(positive=['virus'])

nlp

The output shows the words that are most similar to the word ‘virus’ along with the sequence or degree of similarity. The words like symptoms and incubation are contextually very accurate with the word virus which proves that CBOW model successfully understands the context of the data. 

Conclusion

In the above article, we saw what a CBOW model is and how it works. We also implemented the model on a custom dataset and got good output. The purpose here was to give you a high-level idea of what word embeddings are and how CBOW is useful. These can be used for text recognition, speech to text conversion etc. 

Introduction

In this article, we’ll talk about CBOW(Continuous Bag of words ) Model ,and how does this model works internally.

CBOW is a variant of the word2vec model predicts the center word from (bag of) context words. So given all the words in the context window (excluding the middle one), CBOW would tell us the most likely the word at the center.

For example, say we have a window size of 2 on the following sentence. Given the words (“PM”, “American”, “and”), we want the network to predict “Modi”.

The input of the Skip-gram network needs to change to take in multiple words. Instead of a “one hot” vector as the input, we use a “bag-of-words” vector. It’s the same concept, except that we put 1s in multiple positions (corresponding to the context words).

CBOW Model Architecture-

The CBOW architecture then looks like the following:

CBOW Architecture                                          Fig : CBOW Architecture

The training samples for CBOW look different than those generated for skip-gram.

Training Samples examples for CBOW

Fig: Training Samples examples for CBOW

The second activation function that you need is softmax. This function is used to calculate the values of the output layer of the neural network, using the following formulas:

begin{align} mathbf{z_2} &= mathbf{W_2}mathbf{h} + mathbf{b_2} tag{3} \ mathbf{hat y} &= mathrm{softmax}(mathbf{z_2}) tag{4} \ end{align}

To calculate softmax of a vector (mathbf{z}), the i-th component of the resulting vector is given by:

[ textrm{softmax}(textbf{z})_i = frac{e^{z_i} }{sumlimits_{j=1}^{V} e^{z_j} } tag{5} ]

Let’s work through an example.

z = numpy.array([9, 8, 11, 10, 8.5])
print(z)
[ 9.   8.  11.  10.   8.5]

You’ll need to calculate the exponentials of each element, both for the numerator and for the denominator.

e_z = numpy.exp(z)

print(e_z)
[ 8103.08392758  2980.95798704 59874.1417152  22026.46579481
  4914.7688403 ]

The denominator is equal to the sum of these exponentials.

sum_e_z = numpy.sum(e_z)
print(f"{sum_e_z:,.2f}")
97,899.42

And the value of the first element of (textrm{softmax}(textbf{z})) is given by:

print(f"{e_z[0]/sum_e_z:0.4f}")
0.0828

This is for one element. You can use numpy’s vectorized operations to calculate the values of all the elements of the (textrm{softmax}(textbf{z})) vector in one go.

Implement the softmax function.

def softmax(z: numpy.ndarray) -> numpy.ndarray:
    """Calculate Softmax for the input

    Args:
     v: array of values

    Returns:
     array of probabilities
    """
    e_z = numpy.exp(z)
    sum_e_z = numpy.sum(e_z)
    return e_z / sum_e_z

Now check that it works.

actual = softmax([9, 8, 11, 10, 8.5])
print(actual)
expected = numpy.array([0.08276948,
                        0.03044919,
                        0.61158833,
                        0.22499077,
                        0.05020223])

expect(numpy.allclose(actual, expected)).to(be_true)
[0.08276948 0.03044919 0.61158833 0.22499077 0.05020223]

Notice that the sum of all these values is equal to 1.

expect(numpy.sum(softmax([9, 8, 11, 10, 8.5]))).to(equal(1))

continuous-bag-of-words

The Continuous Bag-of-Words model (CBOW) is frequently used in NLP deep learning. It is a model that tries to predict words given the context of a few words before and a few words after the target word.
This is distinct from language modeling, since CBOW is not sequential and does not have to be probabilistic. Typically, CBOW is used to quickly train word embeddings, and these embeddings are used to initialize the embeddings of some more complicated model. Usually, this is referred to as pretraining embeddings. It almost always helps performance a couple of percent.

This is the solution of the final exercise of this great tutorial on NLP in PyTorch.

Example

Corpus

We are about to study the idea of a computational process.
Computational processes are abstract beings that inhabit computers.
As they evolve, processes manipulate other abstract things called data.
The evolution of a process is directed by a pattern of rules
called a program. People create programs to direct processes. In effect,
we conjure the spirits of the computer with our spells.

Context

People, create, to, direct

Output

Continuous Bag-of-Words Word2Vec is an architecture for creating word embeddings that uses $n$ future words as well as $n$ past words to create a word embedding. The objective function for CBOW is:

$$ J_theta = frac{1}{T}sum^{T}_{t=1}log{p}left(w_{t}mid{w}_{t-n},ldots,w_{t-1}, w_{t+1},ldots,w_{t+n}right) $$

In the CBOW model, the distributed representations of context are used to predict the word in the middle of the window. This contrasts with Skip-gram Word2Vec where the distributed representation of the input word is used to predict the context.


Source: Efficient Estimation of Word Representations in Vector Space

Papers


Paper Code Results Date Stars

Tasks


Usage Over Time


This feature is experimental;
we are continuously improving our matching algorithm.

Components


Component Type


Add


Remove

🤖 No Components Found You can add them if they exist; e.g. Mask R-CNN uses RoIAlign

Categories


Одно горячее кодирование

Одноразовое кодирование — это одноразовое кодирование, также известное как однобитовое эффективное кодирование. Метод заключается в использовании N-битных регистров состояния для кодирования N состояний. Каждое состояние имеет свой собственный независимый бит регистра, и в любой момент только Один действительный. Например, предположим, что у нас есть четыре образца (строки), и каждый образец имеет три функции (столбца), как показано на рисунке:

Наша характеристика_1 имеет два возможных значения, например, мужской / женский, где мужчина представлен 1, а женский — 2. Есть 4 значения (состояния) для feature_2 и feature_3. Одноразовое кодирование гарантирует, что только 1 бит отдельной функции в каждом образце находится в состоянии 1, а остальные — в 0. Вышеупомянутое состояние кодируется одним-горячим, как показано на рисунке ниже:

Анализ достоинств и недостатков

преимущество: Один состоит в том, чтобы решить проблему того, что классификатор не подходит для обработки дискретных данных, а другой — в расширении функции до определенной степени.

Недостаток: Некоторые недостатки в представлении текстовых функций очень заметны. Во-первых, это модель набора слов, которая не учитывает порядок между словами (порядок слов в тексте также очень важен); во-вторых, она предполагает, что слова не зависят друг от друга (в большинстве случаев слова и слова Взаимно влияют); наконец, функции, которые он получает, дискретны и редки.

Почему полученные характеристики дискретны и разрежены?

Приведенный выше пример относительно прост, но реальная ситуация может быть иной. Например, если названия всех городов мира используются как корпус, то этот вектор будет слишком разреженным и вызовет катастрофу размеров.

Ханчжоу [0,0,0,0,0,0,0,1,0, ……, 0,0,0,0,0,0,0]
Шанхай [0,0,0,0,1,0,0,0,0, ……, 0,0,0,0,0,0,0]
Нинбо [0,0,0,1,0,0,0,0,0, ……, 0,0,0,0,0,0,0]
Пекин [0,0,0,0,0,0,0,0,0, ……, 1,0,0,0,0,0,0]

В корпусе Ханчжоу, Шанхай, Нинбо и Пекин соответствуют вектору. Только один из векторов равен 1, а остальные — 0.

Можно ли уменьшить размерность вектора слов?

Распределенное представление может решить проблему одного горячего представления.Его идея состоит в том, чтобы отобразить каждое слово в более короткий вектор слов посредством обучения. Все эти векторы слов составляют векторное пространство, и тогда отношения между словами можно изучать обычными статистическими методами. Какова размерность этого более короткого словарного вектора? Обычно это необходимо указать во время обучения.

Этот процесс называетсявложение слов, То есть встраивание многомерных векторов слов в низкоразмерное пространство. Кстати я нашла картинку

word2vec

Модель word2vec на самом деле представляет собой упрощенную нейронную сеть. (Если вы не разбираетесь в нейронных сетях, выполните поиск самостоятельно)

В качестве входных данных используется One-Hot Vector, скрытый слой не имеет функции активации, это линейная единица. Измерение выходного слоя такое же, как измерение входного слоя, с использованием регрессии Softmax. Когда модель обучена, мы не будем использовать обученную модель для обработки новых задач. Что нам действительно нужно, так это параметры, полученные моделью через обучающие данные, такие как матрица весов скрытого слоя.

Как эта модель определяет ввод и вывод данных? Обычно делятся на две модели CBOW (Continuous Bag-of-Words и Skip-Gram). Обучающий вход модели CBOW — это вектор слова, соответствующий контекстному слову определенного ключевого слова, а выход — это вектор слова этого конкретного слова. Идеи модели Skip-Gram и CBOW перевернуты, то есть вход — это вектор слова определенного слова, а выход — вектор контекстного слова, соответствующий определенному слову. CBOW больше подходит для небольших баз данных, а Skip-Gram — для больших. Лучшая производительность в корпусе.

CBOW(Continuous Bag-of-Words)

Модель обучения CBOW представлена ​​на рисунке.

1 Входной уровень: одно слово контекста. {Предположим, что размер векторного пространства слов равен V, а количество контекстных слов равно C}
2 Все единичные числа умножаются на общую входную матрицу весов W. {VМатрица N, N — число, которое вы установили, инициализируйте матрицу весов W}
3. Результирующий вектор {потому что это onehot, поэтому это вектор} сложите и усредните как вектор скрытого слоя с размером 1
N.
4 Умножьте выходную матрицу весов W ‘{NV}
5 Получите вектор {1
V} Функция активации обрабатывается для получения распределения вероятностей V-dim {PS: поскольку это односконечное, каждое его измерение представляет слово}
6 Слово, указанное индексом с наибольшей вероятностью, является прогнозируемым средним словом (целевым словом) для сравнения с одним словом истинной метки, чем меньше ошибка, тем лучше (обновите матрицу весов в соответствии с ошибкой)

Следовательно, необходимо определить функцию потерь (обычно функцию стоимости кросс-энтропии) и использовать алгоритм градиентного спуска для обновления W и W ‘. После обучения вектор, полученный путем умножения каждого слова во входном слое на матрицу W, является вектором слов (встраивание слов), которое мы хотим. Эта матрица (вложение всех слов в слова) также называется таблицей поиска (на самом деле, умный вы Как видите, эта таблица поиска на самом деле является самой матрицей W), то есть одно слово любого слова, умноженное на эту матрицу, получит свой собственный вектор слов. С помощью таблицы поиска вы можете избежать процесса обучения и напрямую искать в таблице вектор слова.

Дайте каштан:

Размер окна равен 2, что означает, что первые два слова и следующие два слова кофе выбраны как входные слова.

Предполагая, что распределение вероятностей, которое мы получаем в это время, достигло установленного количества итераций, тогда таблица поиска, которую мы сейчас обучили, должна быть матрицей W. То есть любое горячее представление слова, умноженного на эту матрицу, получит собственное вложение слова.

Skip-Gram

С интуитивного понимания Skip-Gram — это заданное входное слово для предсказания контекста.

Далее мы посмотрим, как обучить нашу нейронную сеть. Допустим, у нас есть предложение «Собака лаяла на почтальона».

Сначала мы выбираем слово в середине предложения в качестве входного слова, например, мы выбираем «собака» в качестве входного слова;

Во входном слове мы определяем другой параметр skip_window, который представляет количество слов, которые мы выбираем с одной стороны (левой или правой) текущего входного слова. Если мы установим skip_window = 2, то окончательно получимСлова в окне (включая входное слово)То есть [«тот», «собака», «лаял», «у»]. skip_window = 2 означает, что нужно выбрать 2 слова слева и 2 слова справа от левого входного слова для входа в наше окно, поэтому весь размер окна span = 2×2 = 4. Другой параметр называется num_skips, который представляет, сколько разных слов мы выбираем из всего окна в качестве выходного слова. Когда skip_window = 2 и num_skips = 2, мы получим два набора (входное слово, выходное слово) форм Данные обучения: (‘собака’, ‘лай’), (‘собака’, ‘the’).

Нейронная сеть выдаст распределение вероятностей на основе этих обучающих данных.Эта вероятность представляет собой вероятность того, что каждое слово в нашем словаре является выходным словом. Это предложение немного запутанное, давайте посмотрим на каштан. На втором этапе мы получили два набора обучающих данных с skip_window и num_skips = 2. Если мы сначала используем набор данных («собака», «гавкнул») для обучения нейронной сети, то модель сообщит нам вероятность того, что каждое слово в словаре будет «лаять», изучив эту обучающую выборку.

Выходная вероятность модели представляет, насколько вероятно, что каждое слово в нашем словаре появится одновременно с входным словом. Например, если мы введем слово «Китай» в модель нейронной сети, то выходная вероятность окончательной модели, такой как «Великобритания», «Россия», и вероятность связанных слов будет намного выше, чем у «Apple», » «Кузнечик» вероятность несвязанных слов. Потому что «Великобритания» и «Россия» чаще появляются в окошке «Китай» в тексте. Мы обучим нейронную сеть завершать упомянутый выше расчет вероятности путем ввода пар слов в текст.

На рисунке выше показаны некоторые примеры наших обучающих выборок. Мы выбираем предложение «Быстрая коричневая лиса перепрыгивает через ленивую собаку» и устанавливаем размер нашего окна равным 2 (window_size = 2), что означает, что мы выбираем только два слова до и после входного слова и входного слова для объединения. На рисунке ниже синий цвет представляет входное слово, а прямоугольник представляет слово, находящееся в окне. Обучающие образцы (вход, выход)

Наша модель будет изучать статистику по количеству вхождений каждой пары слов. Например, наша нейронная сеть может получить больше пар обучающих выборок, подобных («Китай», «Великобритания»), но редко видеть комбинацию («Великобритания», «Киддид»). Следовательно, когда наша модель обучается, при вводе слова «Китай» в качестве входных данных будет назначен выходной результат «Великобритания» или «Россия», чем «Киддид».

Опять же, в конечном итоге нам нужна обученная матрица весов.

К настоящему времени я изучил три успешных силы word2vec, и путь впереди долог, и я дорожу им.

Автор: if Пакистан
Ссылка: https://www.jianshu.com/p/471d9bfbd72f
Источник: Цзяньшу
Авторские права на короткую книгу принадлежат автору. Для любой формы перепечатки свяжитесь с автором для авторизации и укажите источник.

Понравилась статья? Поделить с друзьями:
  • Continue в excel что это
  • Continue the rows of word groups common species
  • Continue the rows of word combinations an attentive child
  • Continue the rows of word combinations a silent listener audience
  • Contingency tables in excel