word2vec源码解读
一、Word2Vec程序解析
word2vec主要的层次结构
vocab是一个结构体数组。
*Vocab_hash是一个hash链表。
vocab存入词的时候实际是按照先后顺序存储的。为了方便查找,在词存入的时候顺便把词在链表中的位置存入到vocab_hash中,而该词的vocab_hash位置有hash(word)决定,这样查找起来很快。
ReadWord:逐个字符读入词(一个汉字是不是拆成两个字符读入呢?)
GetWordHash: hash = hash*257+word[i];
SearchVocab: 在vocab中查找对应的词,返回-1是没有找到,否则返回vocab_hash[hash]。
ReadWordIndex: 返回词在vocab中的位置。
AddWordToVocab:向vocab中插入新词,并在vocab_hash中插入新词的位置。
SortVocab:把vocab中的所有词整理了一遍,出现次数少于最低次数的丢掉,并重新分配了空间。
ReduceVocab:也是重新整理,将出现次数少的词干掉,只是并不重新分配空间,只是将次数不达标的词对应的vocab空间free掉。每被执行一次,min_reduce自增一次。(此函数是为保证vocab最大容量为21M而做的,如果trainfile里的词量太大,只有保留频次高的词。)
LearnVocabFromTrainFile:
SaveVocab:将vocab中的word和cn写入到输出文件中。
TrainModel:
其实网络的实现都是在TrainModelThread中,神经网络分成多线程计算,计算完成之后再进行k-mean聚类。TrainModel生成线程,配置线程。
InitNet:给第一层syn0、syn1、syn1neg分配空间。并给syn0赋初始值。并生成二叉树。
CreateBinaryTree:生成一棵节点数为2*vocab_size+1个节点的huffman树,并根据词频给给每个词设定其在huffman树的位置。
TrainModelThread:实现神经网络。(下一节细看这块。)
1. TrainModelTread的流程图
总的来说是这样的:
(1).所有训练集中的词被等分成n份(n为线程数),所有的词都会迭代5次(5次是默认值,这个可以在参数中设置),因此,每个线程会反复读5次自己管辖内的词。
(2).每次按照句子来读入词,一次读入一句,一句读入后,逐个词进入神经网络训练。等这句话的所有词都训练完成后,再读入下一句。
(3).当读到线程管辖文件尾时,迭代计数器自减,如果减为0了,则跳出最外层循环,整个训练结束;如果还没有减到0,则将读文件的指针移到线程管辖文件的头部。重新开始下一次迭代。
(4).每处理10000个词,就需要更新1次alpha。
(5). 逐个词进入神经网络训练,虽然设置了window,但是,并不是5个词进行一次神经网络训练,而是在in->hidden做向量累加时,随机计算窗口量,窗口数量有window这么多种(3-11个之间),以当前输入词为中心,累加其前后的词的向量。
(窗口大小随机,但有范围,以当前词为中心,(除最开始,和最末尾))。
2. 神经网络对应程序推导
以下推导是根据神经网络中主要的算式为主线,红色为其后备推导过程,以此来分析整个神经网络。
这里,首先,在intiNet()定义syn0是一个V*L维度的大矩阵,L为每个词的向量维度。它存的是vocab中所有词的L维的向量,已经给此矩阵负了随机初始值。Word是词在vocab中的位置。
在上一节提到,在做in->hidden的累加时,词窗口大小是随机的。这里neu1[c]就是窗口中词的向量累加。(c为维度计数,L范围内循环,W为窗口词个数)。
cw是窗口中词的数量,这里相当于是把做成平均值。
其中piont为词在huffman树中到根结点的路径,point[d]是其往上推的第d个父结点。这个内积和为其自身向量与各父结点的内积和,取这样一个内积和的好处目前还没有搞清楚。
这是求f的sigmoid函数输出。这里没有直接计算,而是换成了查表的方式,应该是为了加快速度。但是查表就意味着把这个函数离散化了,就会存在离散误差。这里,给f定了取值范围为(-6,6),而定了表的元素总量为1000。带入可得
这个公式怎么就是sigmoid函数了呢?
首先来看看,是如何定义的
- for (i = 0; i < EXP_TABLE_SIZE; i++) {
- expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
- expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
- }
也就是
再来看看sigmoid函数的定义
其取值范围为(0,1)。可转化为
那么
i的范围(0,1000),z的范围为(-6,6),离散化后步长为12/1000。
那么中各元素的值就是(0.0024726232,0.99752737768)之间非线性增加的值。
接下来令P=(f+6)*1000/12,f取值范围(-6,6),P的取值范围正好是(0,1000),覆盖表中所有的元素。
因此,④就是sigmoid函数的离散化形式。
code是父结点的标签,1为右结点,0为左结点。d依然是往上推的第d个父结点。这是梯度计算公式。由于0<f<1,>0,这样的话,父结点为左结点对应的梯度为正,为右结点的梯度为负。
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];
- for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c];
更新向量。Neu1e[],每个词的向量误差为各父结点各次迭代向量乘梯度的和。然后把父结点的向量叠加到该词当前向量值中,实际上,向量误差就是自己前面d次迭代出来的向量参数乘梯度。
- for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
- c = sentence_position - window + a;
- if (c < 0) continue;
- if (c >= sentence_length) continue;
- last_word = sen[c];
- if (last_word == -1) continue;
- for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c];
把误差叠加到每个词的向量当中。这个误差实际上是各父结点的向量乘梯度,包含了该父结点所有叶子结点的向量,因此,不但同一个父结点下来的两个子结点有关联了,连与叶子结点出现在同一个句子,且位置相近的词也关联起来了。
第三部分、word2vec之TrainModelThread程序详细注解
- <pre name="code" class="cpp">void *TrainModelThread(void *id) {
- long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0;
- long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];
- long long l1, l2, c, target, label, local_iter = iter;
- unsigned long long next_random = (long long)id;
- real f, g;
- clock_t now;
- real *neu1 = (real *)calloc(layer1_size, sizeof(real)); //只有输入层需要,隐含层是一个累加和,输出层存入huffman树中。
- real *neu1e = (real *)calloc(layer1_size, sizeof(real));
- FILE *fi = fopen(train_file, "rb");
- fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
- while (1) {
- /************每10000个词左右重新计算一次alpha.**********************/
- if (word_count - last_word_count > 10000) {
- word_count_actual += word_count - last_word_count;
- last_word_count = word_count;
- if ((debug_mode > 1)) {
- now=clock();
- printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha,
- word_count_actual / (real)(iter * train_words + 1) * 100,
- word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));
- fflush(stdout);
- }
- alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1));
- if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;
- }
- /**********************读入一个句子,或者文章长于1000,则分成两句***************************************/
- //将句子中每个词的vocab位置存入到sen[]
- //每次读入一句,但读一句后等待这句话处理完之后再读下一句。
- if (sentence_length == 0) { //只有在一句执行完之后,,才会取下一句
- while (1) {
- word = ReadWordIndex(fi); //读fi中的词,返回其在vocab中的位置。
- if (feof(fi)) break;
- if (word == -1) continue;
- word_count++;
- if (word == 0) break; // 第0个词存的是句子结束符</s>,因此,这里一次性送入sen的就是一个句子或一篇文章。
- // The subsampling randomly discards frequent words while keeping the ranking same
- if (sample > 0) {
- //
- real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn;
- next_random = next_random * (unsigned long long)25214903917 + 11;
- if (ran < (next_random & 0xFFFF) / (real)65536) continue; //(next_random & 0xFFFF) / (real)65536 应该是个小于1的值。也就是说ran 应该大于1.
- }
- sen[sentence_length] = word; //sen存的是词在vocab中的位置。
- sentence_length++;
- if (sentence_length >= MAX_SENTENCE_LENGTH) break; //文章超过1000个词则分成两个句子。
- }
- sentence_position = 0;
- }
- /**************************************************处理到文件尾的话,迭代数递减,***********************************/
- //所有的词(这里单个线程处理其对应的词)会被执行local_iter次。这5次神经网络的参数不是重复的,而是持续更新的,像alpha、syn0。
- //单个线程处理的词是一样的,这个后续可以看看有没可优化的地方。
- if (feof(fi) || (word_count > train_words / num_threads)) { //train_file被读到末尾了,或者一个线程已经完成了它的份额。
- word_count_actual += word_count - last_word_count;
- local_iter--; //读完所有词之后进行5次迭代是个啥意思? 也就是这些词不是过一次这个网络就行了,而是5词。
- if (local_iter == 0) break; //只有这里才是跳出最外层循环的地方。
- word_count = 0;
- last_word_count = 0;
- sentence_length = 0;
- //移动文件流读写位置,从距文件开头file_size / (long long)num_threads * (long long)id 位移量为新的读写位置
- fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); //将文件读指针重新移到到此线程所处理词的开头。
- continue;
- }
- /*******************************进入神经网络******************************/
- word = sen[sentence_position]; //从句首开始,虽然window=5,或别的,但是,以
- if (word == -1) continue;
- for (c = 0; c < layer1_size; c++) neu1[c] = 0;
- for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
- next_random = next_random * (unsigned long long)25214903917 + 11;
- //这个点没有固定下来,导致窗口也是随机的,可以看看这点是否可以优化。
- b = next_random % window; //b取0-4之间的随机值。
- if (cbow) { //train the cbow architecture
- // in -> hidden
- cw = 0;
- //窗口大小随机,但有范围(3-11,窗口大小为单数,一共5种,因此,window实际可以理解为窗口变化的种数),以当前词为中心,(除最开始,和最末尾)
- for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
- c = sentence_position - window + a; //给c赋值
- if (c < 0) continue;
- if (c >= sentence_length) continue;
- last_word = sen[c];
- if (last_word == -1) continue;
- //累加词对应的向量。双重循环下来就是窗口额定数量的词每一维对应的向量累加。
- //累加后neu1的维度依然是layer1_size。
- //从输入层过度到隐含层。
- for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size];
- cw++; //进入隐含层的词个数。
- }
- if (cw) {
- for (c = 0; c < layer1_size; c++) neu1[c] /= cw; //归一化处理。
- //遍历该叶子节点对应的路径,也就是每个父结点循环一次,这是什么原理呢?
- //这样一来,越是词频低的词,迭代层数越多,
- //每个词都要从叶子结点向根结点推一遍。
- //这样的话可以通过父结点,建立叶子结点之间的联系。
- if (hs) for (d = 0; d < vocab[word].codelen; d++) {
- f = 0;
- l2 = vocab[word].point[d] * layer1_size;
- // Propagate hidden -> output
- for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2]; //做内积 这个内积是什么原理呢?
- if (f <= -MAX_EXP) continue; //不在范围内的内积丢掉
- else if (f >= MAX_EXP) continue; //-6<f<6
- else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; //sigmod函数, f=expTab[(int)((f+6)*1000/12)]
- // 'g' is the gradient multiplied by the learning rate
- g = (1 - vocab[word].code[d] - f) * alpha; //计算梯度
- // Propagate errors output -> hidden
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; //计算向量误差,实际就是各父结点的向量和乘梯度。
- // Learn weights hidden -> output
- for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c]; //更新父结点们的向量值,父结点的向量就是各叶子结点各次向量的累加。
- //关系就是这样建立起来的,各叶子结点的向量都累加进入了每一个父结点中,因此,拥有相同父结点的词就会联系起来了。
- }
- // NEGATIVE SAMPLING
- if (negative > 0) for (d = 0; d < negative + 1; d++) { //有负样本,处理负样本
- if (d == 0) {
- target = word;
- label = 1; //正样本
- } else {
- next_random = next_random * (unsigned long long)25214903917 + 11;
- target = table[(next_random >> 16) % table_size];
- if (target == 0) target = next_random % (vocab_size - 1) + 1;
- if (target == word) continue;
- label = 0; //负样本
- }
- l2 = target * layer1_size;
- f = 0; //以下和上面差不多。
- for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2];
- if (f > MAX_EXP) g = (label - 1) * alpha;
- else if (f < -MAX_EXP) g = (label - 0) * alpha;
- else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
- for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c];
- }
- // hidden -> in
- for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
- c = sentence_position - window + a;
- if (c < 0) continue;
- if (c >= sentence_length) continue;
- last_word = sen[c];
- if (last_word == -1) continue;
- for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c]; //用误差更新向量(输入层参数),直接将误差叠加到输入向量上,这样好吗?
- }
- }
- } else { //train skip-gram
- for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
- c = sentence_position - window + a;
- if (c < 0) continue;
- if (c >= sentence_length) continue;
- last_word = sen[c];
- if (last_word == -1) continue;
- l1 = last_word * layer1_size; //和cbw相比少了做输入向量累加。
- for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
- // HIERARCHICAL SOFTMAX
- if (hs) for (d = 0; d < vocab[word].codelen; d++) {
- f = 0;
- l2 = vocab[word].point[d] * layer1_size;
- // Propagate hidden -> output
- for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2]; //做内积
- if (f <= -MAX_EXP) continue;
- else if (f >= MAX_EXP) continue;
- else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
- // 'g' is the gradient multiplied by the learning rate
- g = (1 - vocab[word].code[d] - f) * alpha;
- // Propagate errors output -> hidden
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];
- // Learn weights hidden -> output
- for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c + l1];
- }
- // NEGATIVE SAMPLING
- if (negative > 0) for (d = 0; d < negative + 1; d++) {
- if (d == 0) {
- target = word;
- label = 1;
- } else {
- next_random = next_random * (unsigned long long)25214903917 + 11;
- target = table[(next_random >> 16) % table_size];
- if (target == 0) target = next_random % (vocab_size - 1) + 1;
- if (target == word) continue;
- label = 0;
- }
- l2 = target * layer1_size;
- f = 0;
- for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2];
- if (f > MAX_EXP) g = (label - 1) * alpha;
- else if (f < -MAX_EXP) g = (label - 0) * alpha;
- else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
- for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1];
- }
- // Learn weights input -> hidden
- for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];
- }
- }
- sentence_position++;
- if (sentence_position >= sentence_length) {
- sentence_length = 0;
- continue;
- }
- }
- fclose(fi);
- free(neu1);
- free(neu1e);
- pthread_exit(NULL);
- }
第四部分
word2vec之霍夫曼树的实现
1. 霍夫曼树的基本要点
判定过程最优的二叉树是霍夫曼树。
路径:树中一个结点到另一个结点之间的分支构成这两个结点之间的路径。
路径长度:路径上的分支数目称为路径长度。
树的路径长度:从根结点到每一个叶子结点的路径长度之和就是这棵树的路径长度。
带权值的路径长度:如果树中每一个叶子结点都带有一个权值,则把树中所有叶子的带权路径长度之和称为树的带权路径长度。
树的带权值路径长度:
带权路径最小的二叉树就是判定过程最优二叉树,即霍夫曼二叉树。其中,权值越大的叶子结点越接近根结点。
2. Word2vec中霍夫曼树的实现
其中,count存各个词的词频,就是叶子结点的权值;binary存霍夫曼编码,parent_node存各父结点的位置。由于满二叉树的节点数m=2n-1, n为叶子结点数,所以以上3个数组的元素个数均为2*vocab_size-1.前n个存叶子结点,后n-1个存父结点。
具体步骤:
以后各次循环如步骤2,直到2n-1也被赋值,整棵树建立完成。
程序如下:
- void CreateBinaryTree() {
- long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH];
- char code[MAX_CODE_LENGTH];
- long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); //节点的权重,叶子节点的权重为cn,父节点的权重为其子结点权重和。
- long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); //表明左右结点,左结点为0,右节点为1.
- long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); //父结点。
- for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn;
- for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15;
- pos1 = vocab_size - 1;
- pos2 = vocab_size;
- // Following algorithm constructs the Huffman tree by adding one node at a time
- for (a = 0; a < vocab_size - 1; a++) {
- // First, find two smallest nodes 'min1, min2'
- if (pos1 >= 0) {
- if (count[pos1] < count[pos2]) { //根据词频来确定位置 词频作为权值?
- min1i = pos1;
- pos1--;
- } else {
- min1i = pos2;
- pos2++;
- }
- } else {
- min1i = pos2;
- pos2++;
- }
- if (pos1 >= 0) {
- if (count[pos1] < count[pos2]) {
- min2i = pos1;
- pos1--;
- } else {
- min2i = pos2;
- pos2++;
- }
- } else {
- min2i = pos2;
- pos2++;
- }
- count[vocab_size + a] = count[min1i] + count[min2i]; //把权值赋给父结点
- parent_node[min1i] = vocab_size + a; //定义上面两点的父结点。
- parent_node[min2i] = vocab_size + a;
- binary[min2i] = 1; //给右结点贴标签。
- }
- // Now assign binary code to each vocabulary word
- for (a = 0; a < vocab_size; a++) {
- b = a;
- i = 0;
- while (1) {
- code[i] = binary[b]; //code存huffman编码。
- point[i] = b; //point专门存父结点
- i++;
- b = parent_node[b];
- if (b == vocab_size * 2 - 2) break;
- }
- vocab[a].codelen = i; //huffman编码的长度。 code和codelen可以用于定位词的位置。
- vocab[a].point[0] = vocab_size - 2;
- for (b = 0; b < i; b++) { //将每个词对应的huffman路径写到point里。
- vocab[a].code[i - b - 1] = code[b];
- vocab[a].point[i - b] = point[b] - vocab_size; //每个结点都存入其所有的父结点的位置。
- }
- }
- free(count);
- free(binary);
- free(parent_node);
- }
word2vec源代码解析
- // Copyright 2013 Google Inc. All Rights Reserved.
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <math.h>
- #include <pthread.h>
- #include <time.h>
- #define MAX_STRING 100
- #define EXP_TABLE_SIZE 1000
- #define MAX_EXP 6
- #define MAX_SENTENCE_LENGTH 1000
- #define MAX_CODE_LENGTH 40
- const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary
- typedef float real; // Precision of float numbers
- struct vocab_word {
- long long cn;
- int *point;
- char *word, *code, codelen;
- };
- char train_file[MAX_STRING], output_file[MAX_STRING];
- char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING];
- struct vocab_word *vocab;
- int binary = 0, cbow = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1;
- int *vocab_hash;
- long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100;
- long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0;
- real alpha = 0.025, starting_alpha, sample = 1e-3;
- real *syn0, *syn1, *syn1neg, *expTable;
- clock_t start;
- int hs = 0, negative = 5; //右参数决定。
- const int table_size = 1e8;
- int *table;
- void InitUnigramTable() {
- int a, i;
- long long train_words_pow = 0;
- real d1, power = 0.75;
- table = (int *)malloc(table_size * sizeof(int));
- for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);
- i = 0;
- d1 = pow(vocab[i].cn, power) / (real)train_words_pow;
- for (a = 0; a < table_size; a++) {
- table[a] = i;
- if (a / (real)table_size > d1) {
- i++;
- d1 += pow(vocab[i].cn, power) / (real)train_words_pow;
- }
- if (i >= vocab_size) i = vocab_size - 1;
- }
- }
- // Reads a single word from a file, assuming space + tab + EOL to be word boundaries
- void ReadWord(char *word, FILE *fin) {
- int a = 0, ch;
- while (!feof(fin)) {
- ch = fgetc(fin);
- if (ch == 13) continue;
- if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {
- if (a > 0) {
- if (ch == '\n') ungetc(ch, fin);
- break;
- }
- if (ch == '\n') {
- strcpy(word, (char *)"</s>");
- return;
- } else continue;
- }
- word[a] = ch;
- a++;
- if (a >= MAX_STRING - 1) a--; // Truncate too long words
- }
- word[a] = 0;
- }
- // Returns hash value of a word
- int GetWordHash(char *word) {
- unsigned long long a, hash = 0;
- for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];
- hash = hash % vocab_hash_size;
- return hash;
- }
- // Returns position of a word in the vocabulary; if the word is not found, returns -1
- int SearchVocab(char *word) {
- unsigned int hash = GetWordHash(word);
- while (1) {
- if (vocab_hash[hash] == -1) return -1;
- if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash];
- hash = (hash + 1) % vocab_hash_size;
- }
- return -1;
- }
- // Reads a word and returns its index in the vocabulary
- int ReadWordIndex(FILE *fin) {
- char word[MAX_STRING];
- ReadWord(word, fin);
- if (feof(fin)) return -1;
- return SearchVocab(word);
- }
- // Adds a word to the vocabulary
- //vocb存入词的时候实际是按照先后顺序存储的。
- //为了方便查找,在词存入的时候顺便把词在链表中的位置存入到vocab_hash中,
- //而该词的vocab_hash位置有hash(word)决定,这样查找起来很快。
- int AddWordToVocab(char *word) {
- unsigned int hash, length = strlen(word) + 1;
- if (length > MAX_STRING) length = MAX_STRING;
- vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); //为词分配一个对应大小的空间,并赋给vocab.word。
- strcpy(vocab[vocab_size].word, word);
- vocab[vocab_size].cn = 0;
- vocab_size++;
- // Reallocate memory if needed
- if (vocab_size + 2 >= vocab_max_size) {
- vocab_max_size += 1000;
- vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word));
- }
- hash = GetWordHash(word);
- while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
- vocab_hash[hash] = vocab_size - 1;
- return vocab_size - 1;
- }
- // Used later for sorting by word counts
- int VocabCompare(const void *a, const void *b) {
- return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; //比较词频
- }
- // Sorts the vocabulary by frequency using word counts
- void SortVocab() {
- int a, size;
- unsigned int hash;
- // Sort the vocabulary and keep </s> at the first position
- qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); //根据词频对vocab中的词进行排序。
- for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; //所有vocab_hash清0。
- size = vocab_size;
- train_words = 0;
- for (a = 0; a < size; a++) {
- // Words occuring less than min_count times will be discarded from the vocab
- if ((vocab[a].cn < min_count) && (a != 0)) { //vocab中出现次数少于最小次数的词丢掉。(这是个办法)。
- vocab_size--;
- free(vocab[a].word);
- } else {
- // Hash will be re-computed, as after the sorting it is not actual
- hash=GetWordHash(vocab[a].word);
- while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; //其实前面已经全部清为-1了。
- vocab_hash[hash] = a;
- train_words += vocab[a].cn; //累积训练词的数量。
- }
- }
- vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word)); //重新分配空间做啥?
- // Allocate memory for the binary tree construction
- for (a = 0; a < vocab_size; a++) {
- vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char));
- vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int));
- }
- }
- // Reduces the vocabulary by removing infrequent tokens
- void ReduceVocab() {
- int a, b = 0;
- unsigned int hash;
- for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { //如果一个单词的出现次数大于最小削减次数,才能保留下来。
- vocab[b].cn = vocab[a].cn;
- vocab[b].word = vocab[a].word;
- b++;
- } else free(vocab[a].word);
- vocab_size = b;
- for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
- for (a = 0; a < vocab_size; a++) {
- // Hash will be re-computed, as it is not actual
- hash = GetWordHash(vocab[a].word);
- while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
- vocab_hash[hash] = a;
- }
- fflush(stdout);
- min_reduce++; //如果下次再次调用此函数,说明词汇量又大了,min_reduce不增加,则满足不了下次reduce的量了。
- }
- // Create binary Huffman tree using the word counts
- // Frequent words will have short uniqe binary codes
- void CreateBinaryTree() {
- long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH];
- char code[MAX_CODE_LENGTH];
- long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
- long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
- long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
- for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn;
- for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15;
- pos1 = vocab_size - 1;
- pos2 = vocab_size;
- // Following algorithm constructs the Huffman tree by adding one node at a time
- for (a = 0; a < vocab_size - 1; a++) {
- // First, find two smallest nodes 'min1, min2'
- if (pos1 >= 0) {
- if (count[pos1] < count[pos2]) { //根据词频来确定位置
- min1i = pos1;
- pos1--;
- } else {
- min1i = pos2;
- pos2++;
- }
- } else {
- min1i = pos2;
- pos2++;
- }
- if (pos1 >= 0) {
- if (count[pos1] < count[pos2]) {
- min2i = pos1;
- pos1--;
- } else {
- min2i = pos2;
- pos2++;
- }
- } else {
- min2i = pos2;
- pos2++;
- }
- count[vocab_size + a] = count[min1i] + count[min2i];
- parent_node[min1i] = vocab_size + a;
- parent_node[min2i] = vocab_size + a;
- binary[min2i] = 1;
- }
- // Now assign binary code to each vocabulary word
- for (a = 0; a < vocab_size; a++) {
- b = a;
- i = 0;
- while (1) {
- code[i] = binary[b];
- point[i] = b;
- i++;
- b = parent_node[b];
- if (b == vocab_size * 2 - 2) break;
- }
- vocab[a].codelen = i;
- vocab[a].point[0] = vocab_size - 2;
- for (b = 0; b < i; b++) { //将每个词对应的huffman路径写到point里。
- vocab[a].code[i - b - 1] = code[b];
- vocab[a].point[i - b] = point[b] - vocab_size;
- }
- }
- free(count);
- free(binary);
- free(parent_node);
- }
- //这个函数主要是把训练集中的词读入vocab;
- //如果词量超出了最大限制,则根据word出现的次数reduce掉次数少的词。
- //读完后整理vocab,将出现次数未达到最小次数的词丢掉。
- void LearnVocabFromTrainFile() {
- char word[MAX_STRING];
- FILE *fin;
- long long a, i;
- for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
- fin = fopen(train_file, "rb");
- if (fin == NULL) {
- printf("ERROR: training data file not found!\n");
- exit(1);
- }
- vocab_size = 0;
- AddWordToVocab((char *)"</s>");
- while (1) {
- ReadWord(word, fin);
- if (feof(fin)) break;
- train_words++;
- if ((debug_mode > 1) && (train_words % 100000 == 0)) {
- printf("%lldK%c", train_words / 1000, 13);
- fflush(stdout);
- }
- i = SearchVocab(word);
- if (i == -1) {
- a = AddWordToVocab(word);
- vocab[a].cn = 1;
- } else vocab[i].cn++;
- if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); //保证vocab里面的词汇量小于21M。
- }
- SortVocab();
- if (debug_mode > 0) {
- printf("Vocab size: %lld\n", vocab_size);
- printf("Words in train file: %lld\n", train_words);
- }
- file_size = ftell(fin);
- fclose(fin);
- }
- void SaveVocab() { //将Vocab中的word和cn存入输出文件
- long long i;
- FILE *fo = fopen(save_vocab_file, "wb");
- for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn);
- fclose(fo);
- }
- void ReadVocab() {
- long long a, i = 0;
- char c;
- char word[MAX_STRING];
- FILE *fin = fopen(read_vocab_file, "rb");
- if (fin == NULL) {
- printf("Vocabulary file not found\n");
- exit(1);
- }
- for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
- vocab_size = 0;
- while (1) {
- ReadWord(word, fin);
- if (feof(fin)) break;
- a = AddWordToVocab(word);
- fscanf(fin, "%lld%c", &vocab[a].cn, &c);
- i++;
- }
- SortVocab();
- if (debug_mode > 0) {
- printf("Vocab size: %lld\n", vocab_size);
- printf("Words in train file: %lld\n", train_words);
- }
- fin = fopen(train_file, "rb");
- if (fin == NULL) {
- printf("ERROR: training data file not found!\n");
- exit(1);
- }
- fseek(fin, 0, SEEK_END);
- file_size = ftell(fin);
- fclose(fin);
- }
- void InitNet() {
- long long a, b;
- unsigned long long next_random = 1;
- a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real));//分配空间?
- if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);}
- if (hs) {
- a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real));
- if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);}
- for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) //syn1[vocab_size*layer1_size]
- syn1[a * layer1_size + b] = 0;
- }
- if (negative>0) { //有负样本的话
- a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real));
- if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);}
- for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++)
- syn1neg[a * layer1_size + b] = 0;
- }
- for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) {
- next_random = next_random * (unsigned long long)25214903917 + 11; //等同于rand()
- syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size; //给syn0赋初始值,。
- }
- CreateBinaryTree(); //生成二叉树。
- }
- void *TrainModelThread(void *id) {
- long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0;
- long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];
- long long l1, l2, c, target, label, local_iter = iter;
- unsigned long long next_random = (long long)id;
- real f, g;
- clock_t now;
- real *neu1 = (real *)calloc(layer1_size, sizeof(real)); //只有输入层需要,隐含层是一个累加和,输出层存入huffman树中。
- real *neu1e = (real *)calloc(layer1_size, sizeof(real));
- FILE *fi = fopen(train_file, "rb");
- fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
- while (1) {
- if (word_count - last_word_count > 10000) {
- word_count_actual += word_count - last_word_count;
- last_word_count = word_count;
- if ((debug_mode > 1)) {
- now=clock();
- printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha,
- word_count_actual / (real)(iter * train_words + 1) * 100,
- word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));
- fflush(stdout);
- }
- alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1));
- if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;
- }
- //读入句子。
- if (sentence_length == 0) { //句首?是从句首开始读。
- while (1) {
- word = ReadWordIndex(fi); //读fi中的词,返回其在vocab中的位置。
- if (feof(fi)) break;
- if (word == -1) continue;
- word_count++;
- if (word == 0) break;
- // The subsampling randomly discards frequent words while keeping the ranking same
- if (sample > 0) {
- //
- real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn;
- next_random = next_random * (unsigned long long)25214903917 + 11;
- if (ran < (next_random & 0xFFFF) / (real)65536) continue; //(next_random & 0xFFFF) / (real)65536 应该是个小于1的值。也就是说ran 应该大于1.
- }
- sen[sentence_length] = word;
- sentence_length++;
- if (sentence_length >= MAX_SENTENCE_LENGTH) break;
- }
- sentence_position = 0;
- }
- if (feof(fi) || (word_count > train_words / num_threads)) { //train_file被读到末尾了,或者一个线程已经完成了它的份额。
- word_count_actual += word_count - last_word_count;
- local_iter--;
- if (local_iter == 0) break;
- word_count = 0;
- last_word_count = 0;
- sentence_length = 0;
- //移动文件流读写位置,从距文件开头file_size / (long long)num_threads * (long long)id 位移量为新的读写位置
- fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
- continue;
- }
- word = sen[sentence_position];
- if (word == -1) continue;
- for (c = 0; c < layer1_size; c++) neu1[c] = 0;
- for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
- next_random = next_random * (unsigned long long)25214903917 + 11;
- b = next_random % window; //b取1-4之间的随机值。
- if (cbow) { //train the cbow architecture
- // in -> hidden
- cw = 0;
- for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
- c = sentence_position - window + a; //给c赋值
- if (c < 0) continue;
- if (c >= sentence_length) continue;
- last_word = sen[c];
- if (last_word == -1) continue;
- //累加词对应的向量。双重循环下来就是窗口额定数量的词每一维对应的向量累加。
- //累加后neu1的维度依然是layer1_size。
- //从输入层过度到隐含层。
- for (c = 0; c < layer1_size; c++) neu1[c] += syn0[c + last_word * layer1_size];
- cw++; //进入隐含层的词个数。
- }
- if (cw) {
- for (c = 0; c < layer1_size; c++) neu1[c] /= cw; //归一化处理。
- if (hs) for (d = 0; d < vocab[word].codelen; d++) { //遍历huffman树叶子节点
- f = 0;
- l2 = vocab[word].point[d] * layer1_size;
- // Propagate hidden -> output
- for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2]; //做内积
- if (f <= -MAX_EXP) continue; //不在范围内的内积丢掉
- else if (f >= MAX_EXP) continue;
- else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; //sigmod函数
- // 'g' is the gradient multiplied by the learning rate
- g = (1 - vocab[word].code[d] - f) * alpha; //计算梯度
- // Propagate errors output -> hidden
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; //计算隐含层到输出层神经元的误差
- // Learn weights hidden -> output
- for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c]; //更新输出参数。
- }
- // NEGATIVE SAMPLING
- if (negative > 0) for (d = 0; d < negative + 1; d++) { //有负样本,处理负样本
- if (d == 0) {
- target = word;
- label = 1; //正样本
- } else {
- next_random = next_random * (unsigned long long)25214903917 + 11;
- target = table[(next_random >> 16) % table_size];
- if (target == 0) target = next_random % (vocab_size - 1) + 1;
- if (target == word) continue;
- label = 0; //负样本
- }
- l2 = target * layer1_size;
- f = 0; //以下和上面差不多。
- for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2];
- if (f > MAX_EXP) g = (label - 1) * alpha;
- else if (f < -MAX_EXP) g = (label - 0) * alpha;
- else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
- for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c];
- }
- // hidden -> in
- for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
- c = sentence_position - window + a;
- if (c < 0) continue;
- if (c >= sentence_length) continue;
- last_word = sen[c];
- if (last_word == -1) continue;
- for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c]; //用误差更新向量(输入层参数),直接将误差叠加到输入向量上,这样好吗?
- }
- }
- } else { //train skip-gram
- for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
- c = sentence_position - window + a;
- if (c < 0) continue;
- if (c >= sentence_length) continue;
- last_word = sen[c];
- if (last_word == -1) continue;
- l1 = last_word * layer1_size; //和cbw相比少了做输入向量累加。
- for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
- // HIERARCHICAL SOFTMAX
- if (hs) for (d = 0; d < vocab[word].codelen; d++) {
- f = 0;
- l2 = vocab[word].point[d] * layer1_size;
- // Propagate hidden -> output
- for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2]; //做内积
- if (f <= -MAX_EXP) continue;
- else if (f >= MAX_EXP) continue;
- else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
- // 'g' is the gradient multiplied by the learning rate
- g = (1 - vocab[word].code[d] - f) * alpha;
- // Propagate errors output -> hidden
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];
- // Learn weights hidden -> output
- for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c + l1];
- }
- // NEGATIVE SAMPLING
- if (negative > 0) for (d = 0; d < negative + 1; d++) {
- if (d == 0) {
- target = word;
- label = 1;
- } else {
- next_random = next_random * (unsigned long long)25214903917 + 11;
- target = table[(next_random >> 16) % table_size];
- if (target == 0) target = next_random % (vocab_size - 1) + 1;
- if (target == word) continue;
- label = 0;
- }
- l2 = target * layer1_size;
- f = 0;
- for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2];
- if (f > MAX_EXP) g = (label - 1) * alpha;
- else if (f < -MAX_EXP) g = (label - 0) * alpha;
- else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
- for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
- for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1];
- }
- // Learn weights input -> hidden
- for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];
- }
- }
- sentence_position++;
- if (sentence_position >= sentence_length) {
- sentence_length = 0;
- continue;
- }
- }
- fclose(fi);
- free(neu1);
- free(neu1e);
- pthread_exit(NULL);
- }
- void TrainModel() {
- long a, b, c, d;
- FILE *fo;
- pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t)); //用于声明线程ID。
- printf("Starting training using file %s\n", train_file);
- starting_alpha = alpha;
- if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile(); //读入词到vocab。
- if (save_vocab_file[0] != 0) SaveVocab();
- if (output_file[0] == 0) return;
- InitNet(); //初始化Net
- if (negative > 0) InitUnigramTable();
- start = clock();
- for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a); //pthread是线程,这里生成线程
- for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL); //让主线程等待子线程执行结束后,主线程再结束。这样,防止主线程很快执行完后,退出,上一行创建的子线程没有机会执行。
- fo = fopen(output_file, "wb");
- if (classes == 0) {
- // Save the word vectors
- fprintf(fo, "%lld %lld\n", vocab_size, layer1_size);
- for (a = 0; a < vocab_size; a++) {
- fprintf(fo, "%s ", vocab[a].word);
- if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo);
- else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", syn0[a * layer1_size + b]);
- fprintf(fo, "\n");
- }
- } else {
- // Run K-means on the word vectors //K-Mean后续再看具体过程
- int clcn = classes, iter = 10, closeid;
- int *centcn = (int *)malloc(classes * sizeof(int));
- int *cl = (int *)calloc(vocab_size, sizeof(int));
- real closev, x;
- real *cent = (real *)calloc(classes * layer1_size, sizeof(real));
- for (a = 0; a < vocab_size; a++) cl[a] = a % clcn;
- for (a = 0; a < iter; a++) {
- for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0;
- for (b = 0; b < clcn; b++) centcn[b] = 1;
- for (c = 0; c < vocab_size; c++) {
- for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d];
- centcn[cl[c]]++;
- }
- for (b = 0; b < clcn; b++) {
- closev = 0;
- for (c = 0; c < layer1_size; c++) {
- cent[layer1_size * b + c] /= centcn[b];
- closev += cent[layer1_size * b + c] * cent[layer1_size * b + c];
- }
- closev = sqrt(closev);
- for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev;
- }
- for (c = 0; c < vocab_size; c++) {
- closev = -10;
- closeid = 0;
- for (d = 0; d < clcn; d++) {
- x = 0;
- for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b];
- if (x > closev) {
- closev = x;
- closeid = d;
- }
- }
- cl[c] = closeid;
- }
- }
- // Save the K-means classes
- for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", vocab[a].word, cl[a]);
- free(centcn);
- free(cent);
- free(cl);
- }
- fclose(fo);
- }
- int ArgPos(char *str, int argc, char **argv) {
- int a;
- for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) {
- if (a == argc - 1) {
- printf("Argument missing for %s\n", str);
- exit(1);
- }
- return a;
- }
- return -1;
- }
- int main(int argc, char **argv) {
- int i;
- if (argc == 1) {
- printf("WORD VECTOR estimation toolkit v 0.1c\n\n");
- printf("Options:\n");
- printf("Parameters for training:\n");
- printf("\t-train <file>\n");
- printf("\t\tUse text data from <file> to train the model\n");
- printf("\t-output <file>\n");
- printf("\t\tUse <file> to save the resulting word vectors / word clusters\n");
- printf("\t-size <int>\n");
- printf("\t\tSet size of word vectors; default is 100\n");
- printf("\t-window <int>\n");
- printf("\t\tSet max skip length between words; default is 5\n");
- printf("\t-sample <float>\n");
- printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n");
- printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n");
- printf("\t-hs <int>\n");
- printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n");
- printf("\t-negative <int>\n");
- printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n");
- printf("\t-threads <int>\n");
- printf("\t\tUse <int> threads (default 12)\n");
- printf("\t-iter <int>\n");
- printf("\t\tRun more training iterations (default 5)\n");
- printf("\t-min-count <int>\n");
- printf("\t\tThis will discard words that appear less than <int> times; default is 5\n");
- printf("\t-alpha <float>\n");
- printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n");
- printf("\t-classes <int>\n");
- printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n");
- printf("\t-debug <int>\n");
- printf("\t\tSet the debug mode (default = 2 = more info during training)\n");
- printf("\t-binary <int>\n");
- printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n");
- printf("\t-save-vocab <file>\n");
- printf("\t\tThe vocabulary will be saved to <file>\n");
- printf("\t-read-vocab <file>\n");
- printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n");
- printf("\t-cbow <int>\n");
- printf("\t\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n");
- printf("\nExamples:\n");
- printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\n\n");
- return 0;
- }
- output_file[0] = 0;
- save_vocab_file[0] = 0;
- read_vocab_file[0] = 0;
- if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);
- if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]);
- if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]);
- if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]);
- if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);
- if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]);
- if ((i = ArgPos((char *)"-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]);
- if (cbow) alpha = 0.05;
- if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]);
- if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]);
- if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]); //窗口大小,也就是n
- if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]);
- if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]);
- if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]);
- if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]); //线程数
- if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]); //迭代
- if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); //设定词最少出现次数。
- if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]);
- vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word));
- vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int));
- expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real));
- for (i = 0; i < EXP_TABLE_SIZE; i++) {
- expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table
- expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1)
- }
- TrainModel();
- return 0;
- }
word2vec源码解读相关推荐
- Bert系列(二)——源码解读之模型主体
本篇文章主要是解读模型主体代码modeling.py.在阅读这篇文章之前希望读者们对bert的相关理论有一定的了解,尤其是transformer的结构原理,网上的资料很多,本文内容对原理部分就不做过多 ...
- Bert系列(三)——源码解读之Pre-train
https://www.jianshu.com/p/22e462f01d8c pre-train是迁移学习的基础,虽然Google已经发布了各种预训练好的模型,而且因为资源消耗巨大,自己再预训练也不现 ...
- linux下free源码,linux命令free源码解读:Procps free.c
linux命令free源码解读 linux命令free源码解读:Procps free.c 作者:isayme 发布时间:September 26, 2011 分类:Linux 我们讨论的是linux ...
- nodeJS之eventproxy源码解读
1.源码缩影 !(function (name, definition) { var hasDefine = typeof define === 'function', //检查上下文环境是否为AMD ...
- PyTorch 源码解读之即时编译篇
点击上方"AI遇见机器学习",选择"星标"公众号 重磅干货,第一时间送达 作者丨OpenMMLab 来源丨https://zhuanlan.zhihu.com/ ...
- Alamofire源码解读系列(九)之响应封装(Response)
本篇主要带来Alamofire中Response的解读 前言 在每篇文章的前言部分,我都会把我认为的本篇最重要的内容提前讲一下.我更想同大家分享这些顶级框架在设计和编码层次究竟有哪些过人的地方?当然, ...
- Feflow 源码解读
Feflow 源码解读 Feflow(Front-end flow)是腾讯IVWEB团队的前端工程化解决方案,致力于改善多类型项目的开发流程中的规范和非业务相关的问题,可以让开发者将绝大部分精力集中在 ...
- spring-session源码解读 sesion
2019独角兽企业重金招聘Python工程师标准>>> spring-session源码解读 sesion 博客分类: java spring 摘要: session通用策略 Ses ...
- 前端日报-20160527-underscore 源码解读
underscore 源码解读 API文档浏览器 JavaScript 中加号操作符细节 抛弃 jQuery,拥抱原生 JS 从 0 开始学习 GitHub 系列之「加入 GitHub」 js实现克隆 ...
最新文章
- 使用 SQL Server Mobile 创建移动应用程序
- 动视暴雪员工大罢工:因CEO被曝多次包庇高管性侵下属、本人曾性骚扰助理
- PHP的echo和print小谈
- Rancher upgrade webhook之CI/CD
- spring中使用注解代替xml配置
- SAP Spartacus 的页面设计思路
- 瞒不住了,难怪.NET进大厂这么难!
- 配置apache支持PHP(win7)
- Codeforces Round #368 (Div. 2) C. Pythagorean Triples
- 小说网jsp源码_基于jsp+mysql的JSP小说网
- 表单的提交方式POST和GET
- 005-垃圾收集算法
- 推荐一款源代码统计分析、开发工作量估算、测试缺陷预测的开发工具 —— 代码统计分析工具(SourceCounter)
- as3 greensock_GreenSock 3 Web动画:了解GSAP的新功能
- 中国移动彩信业务资料集合
- 好东西都在这里,不点下看看吗(博客目录导航,持续更新中...)
- SMAA算法详解 - SMAAEdgeDetectionVS
- PWM电流源型逆变器
- JavaScript:原生JS实现Facebook实时消息抓捕
- phpyun人才系统 短信配置教程
热门文章
- python——温度换算(以字母结尾)
- Python 之圆周率 π 的计算
- Ncut源码编译错误的解决方法
- python调用百度AI接口实现人像分割
- android+模拟人体扫描,人体模型模拟器app
- 從turtle海龜動畫 學習 Python - 高中彈性課程系列 10.2 藝術畫 Python 製作生成式藝術略覽
- 人工智能资料整理总结
- python 酷炫效果_六种酷炫Python运行进度条效果的实现代码
- “猪”事大吉 | 为什么猪是最后一个生肖?
- Matlab 斜率和曲率,曲率_与闪电共舞_新浪博客