word2vec的代码注释

来源:互联网 发布:md5解密java代码 32位 编辑:程序博客网 时间:2024/06/04 18:07


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>#define MAX_STRING 100 //假设最大的单词长度100#define EXP_TABLE_SIZE 1000#define MAX_EXP 6#define MAX_SENTENCE_LENGTH 1000#define MAX_CODE_LENGTH 40const int vocab_hash_size = 30000000;  // Maximum 30 * 0.7 = 21M words in the vocabularytypedef float real;                    // Precision of float numbersstruct vocab_word{  long long cn;//词频  int *point;//huffman编码对应内节点的路径  char *word, *code, codelen;//huffman编码};char train_file[MAX_STRING], output_file[MAX_STRING];//save_vocab_file[MAX_STRING]:保存存储训练文件的位置,用于保存词汇表到save_vocab_filechar save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING];//*vocab:词汇表,保存所有词汇struct vocab_word *vocab;//min_count:低于该词频的词在排序时将被丢弃//min_reduce:记录缩减词汇表的次数//不懂得degug等级会在不同的地方打印信息//debug_mode>2 会在中间过程打印一些信息,如ReadVocab()中会打印词汇表大小和训练文件词汇量//debug_mode>1 会在读训练文件时没10万次打印一次信息int binary = 0, cbow = 0, debug_mode = 2, window = 5, min_count = 5, num_threads = 1, min_reduce = 1;//vocab_hash:词汇哈希表,保存某个词在词汇表中的下表int *vocab_hash;//vocab_size:缩减词汇表时,低于此阈值将会被删除//vocab_size:词表大小long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100;//file_size:训练文件大小long long train_words = 0, word_count_actual = 0, file_size = 0, classes = 0;//sample:>0会对高频词会采用下采样,相当于平滑real alpha = 0.025, starting_alpha, sample = 0;real *syn0, *syn1, *syn1neg, *expTable;clock_t start;int hs = 1, negative = 0;//table_size:负采样概率表的大小,概率越大的词在表中所占位置越大const int table_size = 1e8;int *table;//生成负采样的概率表,采用轮盘赌的思想,如图://   0.2  0.3      0.5        :概率//  |__|______|____________|  :table范围////  词频越大,占用table位置越多,table的界限是通过累加比较实现的,即:(tablesize,word2vec默认是1e8)//  边界a1 <= 0.2 * tablesize,边界a2 <= (0.2+0.3) * tablesize,边界a3 <=Math.min(tablesize,(0.2+0.3+0.5)*tablesize) 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,这里使用的0.75次幂,没有直接用词频  train_words_pow += pow(vocab[a].cn, power);  i = 0;//表示从第0个单词开始  d1 = pow(vocab[i].cn, power) / (real)train_words_pow;//表示已遍历的词占总值的比例  for (a = 0; a < table_size; a++)//遍历table。a表示table的位置,i表示词汇表的位置  {    table[a] = i;//单词i占用table的a位置    //table反映的是一个单词的分布,一个单词越大,所占用的table的位置越多    if (a / (real)table_size > d1)//这里表示从单词0到i所占用table的所有位置的比例如果大于他应该有的比例    {      i++;//移动到下一个词      d1 += pow(vocab[i].cn, power) / (real)train_words_pow;//记录下之前所有词所占的比例  //这里无论是d1还是a都采用累加的方式更新,即统计前n个的概率,以及前n个的占用table的大小    }    if (i >= vocab_size) i = vocab_size - 1;//不能大于内存  }}// Reads a single word from a file, assuming space + tab + EOL to be word boundaries//从文件中读取一个词,假设空格、tab和EOL是词的边界(因为针对英文)中文得先分词,这里//首先,会在词库中增 加一个“< /s>”的词,同时,在读取文本的过程中,将换行符“\n”也表示成该该词void ReadWord(char *word, FILE *fin) {  int a = 0, ch;  while (!feof(fin)) {    ch = fgetc(fin);    if (ch == 13) continue;//13是回车,回车就继续,注意回车和换行不是一回事’\n‘换行是10,回车是13    if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {//碰到了认为的结束标志对于空格和tab,就认为是普通的结束//但是对于'\n'而言,word2vec也要把它保存起来,用</s>代替'\n'      if (a > 0) {//如果已经读过字符,比如“abc\n”,因为要保留‘\n’,所以把读到的'\n'退回输入流,等下次以’\n‘开头时再处理        if (ch == '\n') ungetc(ch, fin);//c中函数,ungetc(ch, stdin)将你读到的字符回退到输入流中        break;//已经遇到结束符,所以跳出循环      }      if (ch == '\n') {//开头即是’\n‘,用</s>替换,因为\n就是结束符,所以结束返回。        strcpy(word, (char *)"</s>");        return;      } else continue;//以空格、tab开头,则无视他们,因为相当于一个字符没读到,就继续往下读,只有读到实际的字符的时候才以他们作为结束符    }    word[a] = ch;//保存,没什么可说的    a++;    if (a >= MAX_STRING - 1) a--;   // Truncate too long words,超过最大长度截断,即“aaa...bbbc”可能变成“aa...ac”  }  word[a] = 0;//开都就是文件结束符,就返回null}// Returns hash value of a word返回一个词的hash值,一个词跟hash值一一对应(可能冲突)//每个词存放分为两个部分:词汇表(存放词的结构体)、词汇hash表(存放着词在词汇表的下标位置)//所以计算出词的hash值后,先去hash表中找到词在此汇表中的下表,再通过下标去查找词汇表中的位置int GetWordHash(char *word){  unsigned long long a, hash = 0;  for (a = 0; a < strlen(word); a++)  hash = hash * 257 + word[a];//采取257进制  hash = hash % vocab_hash_size;  return hash;}// Returns position of a word in the vocabulary; if the word is not found, returns -1// 返回一个词在词汇表中的位置,如果不存在则返回-1int SearchVocab(char *word){  unsigned int hash = GetWordHash(word);  while (1)  {    if (vocab_hash[hash] == -1) return -1;//没找到,返回-1    if (!strcmp(word, vocab[vocab_hash[hash]].word))//找到,返回词汇在词汇表中的下标    return vocab_hash[hash];    hash = (hash + 1) % vocab_hash_size;//可能会有hash冲突,采用开放寻址法,查找下一个位置,直到没有找到  }  return -1;}// Reads a word and returns its index in the vocabulary// 从文件流中读取一个词,并返回这个词在词汇表中的位置int ReadWordIndex(FILE *fin){  char word[MAX_STRING];  ReadWord(word, fin);//读一个词,以假设空格、tab和EOL是词的边界  if (feof(fin)) return -1;  return SearchVocab(word);//返回词在词汇表中的位置,通过查询vocab_hash表实现的,vocab_hash通过hash表存放词在词汇表的下标}// Adds a word to the vocabulary // 将一个词添加到一个词汇中// 如果词过长,就截取到MAX_STRINGint 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));//分配内存  strcpy(vocab[vocab_size].word, word);//保存  vocab[vocab_size].cn = 0;//词频初始化为0  vocab_size++;  // Reallocate memory if needed  // 词汇表大小即将达到阈值时,扩大阈值(+1000),扩展表  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);//计算word哈希值  while (vocab_hash[hash] != -1)//如果hash值冲突了  hash = (hash + 1) % vocab_hash_size;//使用开放地址法解决冲突  vocab_hash[hash] = vocab_size - 1;//词汇表的排序位置添加到词的hash值所在位置  return vocab_size - 1;}// Used later for sorting by word counts// 比较词频,返回词a与词b词频的差值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// 根据词频排序,会自动删除低于阈值的词// 有意思的是词汇表vocab的第一个位置vocab[0]不参与排序void SortVocab(){  int a, size;  unsigned int hash;  // Sort the vocabulary and keep </s> at the first position  //编译器函数库自带的快速排序函数  //void qsort(void*base,size_t num,size_t width,int(__cdecl*compare)(const void*,const void*));  //各参数:1 待排序数组首地址 2 数组中待排序元素数量 3 各元素的占用空间大小 4 指向函数的指针  qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare);  for (a = 0; a < vocab_hash_size; a++)//排序后因为每个词在词汇表中的下标已经改变,所以保存词-下标对的哈希表也要重新计算  vocab_hash[a] = -1;  size = vocab_size;  train_words = 0;//累计词汇表vocab的词频总数  for (a = 0; a < size; a++)  {    // Words occuring less than min_count times will be discarded from the vocab//出现太少的词直接丢弃//min_count:低于该词频的词丢弃    if (vocab[a].cn < min_count)    {      vocab_size--;      free(vocab[vocab_size].word);    }    else    {      // Hash will be re-computed, as after the sorting it is not actual      // 重新计算hash查找。vocab_hash是由hash值找到该词所在位置      hash=GetWordHash(vocab[a].word);      while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;//因为hash可能有冲突,所以开放寻址继续往下找直至没有冲突      vocab_hash[hash] = a;//vocab_hash表更新下标      train_words += vocab[a].cn;//累计词汇表vocab的词频总数    }  }  vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word));//排序后因为有词语会因为小于min_count阈值而被丢弃  //所以调整一下内存  // Allocate memory for the binary tree construction  //为Hierarchical softmax中的Huffman树结构分配内存  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++)//用了两个下标a、b,思路是把大于阈值的词向上提覆盖掉之前位置的词  if (vocab[a].cn > min_reduce)//a为扫描下标,b为已经排好序的词的最后位置  {    vocab[b].cn = vocab[a].cn;    vocab[b].word = vocab[a].word;    b++;  }  else free(vocab[a].word);//有意思的是不满足阈值就当场释放掉,不是做标记全完成后释放。这样节省内存。  vocab_size = b;  //只要是位置有变化,就要从新计算vocab_hash中的位置信息  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;//处理hash冲突    vocab_hash[hash] = a;  }  fflush(stdout);//这步没看出来为什么??  min_reduce++;//记录缩减词汇表的次数}// Create binary Huffman tree using the word counts根据词频创建huffman树// Frequent words will have short uniqe binary codes词频越大的单词有越短的huffman编码// 注意,已知,词库中的词是按照降序排列的!!!!!!这点很重要,要不下面构建Huffman数就看不懂了// 切记切记,我在这研究半天233333void CreateBinaryTree() {//min1i、min2i表示每一轮生成huffman树时的左右两只,min2i是值大的那支,编码为1;这与我们习惯上的Huffman树略有不同  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));//count存放各个词的词频(节点值),包括生成的非叶子节点  long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));//binary存放各个节点对应的哈夫曼编码  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;//用词频初始化一下,对于尚未生成的父节点,则用1e15初始化  for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15;//(下面用词语中,父节点用非叶子节点说明,原有词表示的节点用叶子节点说明)  pos1 = vocab_size - 1;//用于生成Huffman飞叶子节点的两个下标pos1,pos2  pos2 = vocab_size;//放在了第一个值为1e15的点上  // Following algorithm constructs the Huffman tree by adding one node at a time  for (a = 0; a < vocab_size - 1; a++)  { //这里有意思的min1i是小于min2i的,也就是说,大的支编码为1,小的支编码为0    // First, find two smallest nodes 'min1, min2' 找出目前权值最小的两个节点// 注意,词典是有序的,且count[i]>=count[i+1],i属于[0,vocab_size - 2],所以下面的方法才能构建Huffman树    if (pos1 >= 0)//寻找第一个权值最小的节点    {//pos1>=0表示叶子节点还没有遍历完,这一轮最小的两个节点可能是叶子节点或者非叶子节点      if (count[pos1] < count[pos2])//所以当前pos1位置一定是叶子节点中值最小者,pos2一定是非叶子节点中值最小者(因为新生成的      {//非叶子节点一定比之前生成的大,未生成的节点被初始化成了1e15)        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++;    }//得到的min1i、min2i即为此轮的最小者    count[vocab_size + a] = count[min1i] + count[min2i];    parent_node[min1i] = vocab_size + a;    parent_node[min2i] = vocab_size + a;    binary[min2i] = 1;//节点编码为1,之前默认是0。  }  // Now assign binary code to each vocabulary word  for (a = 0; a < vocab_size; a++)//对于每个叶子节点(词语)开始编码  {    b = a;//b用于记录路径,初始化为叶子节点    i = 0;//从第0个节点开始    while (1)//对每个叶子(词语),一直编码到根节点    {      code[i] = binary[b];//记录本节点编码      point[i] = b;//记录路径      i++;//从叶子到根的方向,向上移一层,反应到code[]、point[]上就是下标+1      b = parent_node[b];//下一次记录的就是父节点的信息      if (b == vocab_size * 2 - 2) break;//因为Huffman树的节点数为2*n-1,n= vocab_size,所以b == vocab_size * 2 - 2就表示到达根节点,    }//于是跳出循环,注意,根节点没有存到point里,这也是为什么下面先单独存放根节点,也是//vocab[a].code[i - b - 1]= code[b]与vocab[a].point[i - b] = point[b] - vocab_size 左侧下标差1的原因    vocab[a].codelen = i;//完成上述操作时,i从0开始多加了1次,刚好是编码长度//因为刚才编码的时候是从叶子到根编码的,Huffman编码是从跟到叶子,所以要再颠倒一下    vocab[a].point[0] = vocab_size - 2;//最开始在这一点不是很理解,这难道是什么特殊数字???????????????????????//后来发现,Haffman路径中存储的中间节点编号要在现在得到的基础上减去vocab_size,即不算叶子结点,单纯在中间节点中的编号      //所以现在根节点的编号为(vocab_size*2-2) - vocab_size = vocab_size - 2      for (b = 0; b < i; b++)    {      vocab[a].code[i - b - 1] = code[b];//这么看着和习惯不太一样,因为i是编码长度,所以写成vocab[a].code[length - 1 - i] = code[i];      vocab[a].point[i - b] = point[b] - vocab_size;//减去vocab_size,即不算叶子结点,单纯在中间节点中的编号,vocab[a].point[length - i] = point[length] - vocab_size    }//point:0-i-1,所以vocab[a].point[1] =point[i-1] ,vocab[a].point[i] = point[0] - vocab_size//细心观察可能会有这个疑问:当b=0时,由于point[0] = a(因为b的初值为a),若a=0,那么point[b]-vocab_size == 0-vocab_size<0//分析发现因为有vocab[a].codelen = i这句,而且vocab[a].point[0]也被赋值为vocab_size - 2,所以这个位置相当于多算了一个位置(超出了codelen范围),即使为负数也并未使用  }  free(count);//使用完毕,可以释放了,以下同理  free(binary);  free(parent_node);}//从分词文件中统计每个单词的词频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>");//有意思的是一开始就添加</s>,即排头一个,这个在后来训练的时候有用,返回下表为0时  //就表示读到了回车,认为一句话结束了  while (1)  {    ReadWord(word, fin);//从fin读一个词    if (feof(fin)) break;    train_words++;//许梿单词数    if ((debug_mode > 1) && (train_words % 100000 == 0))//每十万次打印一次信息    {      printf("%lldK%c", train_words / 1000, 13);//这个13是回车      fflush(stdout);////这步没看出来为什么??又刷新?    }    i = SearchVocab(word);//返回该词在词汇表中的位置,判断是否已存在,这和下面ReadVocab()是有区别的//搜索的vocab_hash    if (i == -1)//该词之前不存在    {      a = AddWordToVocab(word);//把该词添加到词汇表中      vocab[a].cn = 1;    }    else vocab[i].cn++;//更新词频    if (vocab_size > vocab_hash_size * 0.7)//如果词汇表太庞大,就缩减,装填因子0.7    ReduceVocab();  }  SortVocab();//根据词频排序词汇表  if (debug_mode > 0)  {    printf("Vocab size: %lld\n", vocab_size);    printf("Words in train file: %lld\n", train_words);  }  //函数 ftell 用于得到文件位置指针当前位置相对于文件首的偏移字节数。在随机方式存取文件时,由于文件位置频繁的前后移动,程序不容易确定文件的当前位置。  //该函数对大于231-1文件,即:2.1G以上的文件操作时可能出错  file_size = ftell(fin);  fclose(fin);}void SaveVocab() {  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);}//从文件读取词汇,该文件已经统计好了每个词汇的词频//从词汇表文件中读词并构建词表和hash表  //由于词汇表中的词语不存在重复,因此与LearnVocabFromTrainFile相比没有做重复词汇的检测  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);//从fin进入一个词到word中    if (feof(fin)) break;    a = AddWordToVocab(word);//把该词添加到词汇中,并返回该词的位置//函数原型为int fscanf(FILE*stream, constchar*format, [argument...]); 其功能为根据数据格式(format)从输入流(stream)中写入数据(argument);//与fgets的差别在于:fscanf遇到空格和换行时结束,注意空格时也结束,fgets遇到空格不结束。    fscanf(fin, "%lld%c", &vocab[a].cn, &c);//是因为写入的时候多写了一个"\n"//就是在上面的那个savevocab()中fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn);//那还多写了“ ”呢?因为在ReadWord()函数里如果“ ”开头就无视,继续往下读了    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);  }  //int fseek(FILE *stream, long offset, int fromwhere);函数设置文件指针stream的位置。  //如果执行成功,stream将指向以fromwhere为基准,偏移offset(指针偏移量)个字节的位置,函数返回0。  //如果执行失败(比如offset超过文件自身大小),则不改变stream指向的位置,函数返回一个非0值。  fseek(fin, 0, SEEK_END);  //函数 ftell 用于得到文件位置指针当前位置相对于文件首的偏移字节数。在随机方式存取文件时,由于文件位置频繁的前后移动,程序不容易确定文件的当前位置。  //该函数对大于231-1文件,即:2.1G以上的文件操作时可能出错  file_size = ftell(fin);//两个函数组合用于获取vocab的大小   fclose(fin);}void InitNet(){  //在大多数情况下,编译器和C库透明地帮你处理对齐问题。POSIX 标明了通过malloc( ), calloc( ), 和realloc( ) 返回的地址  //对于任何的C类型来说都是对齐的。在Linux中,这些函数返回的地址在32位系统是以8字节为边界对齐,  //在64位系统是以16字节为边界对齐的。有时候,对于更大的边界,例如页面,程序员需要动态的对齐。  //虽然动机是多种多样的,但最常见的是直接块I/O的缓存的对齐或者其它的软件对硬件的交互  long long a, b;  a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real));  //先知道这个也是申请动态数组,对齐还有128这个参数以后再了解  //syn0存储的是词表中每个词的词向量  if (syn0 == NULL)  {  printf("Memory allocation failed\n"); exit(1);  }  if (hs)//采用多层softmax  {    a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real));    //layer1_size是词向量的长度//syn1是映射层到输出层的权重if (syn1 == NULL)    {    printf("Memory allocation failed\n"); exit(1);    }//大小为 :vocab_size * layer1_size    for (b = 0; b < layer1_size; b++)    for (a = 0; a < vocab_size; a++)    syn1[a * layer1_size + b] = 0;  }  if (negative>0)//还有负样本  {    a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real));    //syn1neg是映射层到输出层负采样的权重if (syn1neg == NULL)    {    printf("Memory allocation failed\n"); exit(1);    }//大小为 :vocab_size * layer1_size    for (b = 0; b < layer1_size; b++)    for (a = 0; a < vocab_size; a++)    syn1neg[a * layer1_size + b] = 0;  }  //大小为 :vocab_size * layer1_size  for (b = 0; b < layer1_size; b++)  for (a = 0; a < vocab_size; a++)  //随机初始化,过程:[0,1] -> [-0.5,0.5] -> [-layer1_size/0.5,layer1_size/0.5],我看到的这个版本好像初始化的这个位置和别人的略有不同  syn0[a * layer1_size + b] = (rand() / (real)RAND_MAX - 0.5) / layer1_size;  CreateBinaryTree();//建立huffman树,对每个单词进行编码}//这个线程函数执行之前,已经做好了一些工作:根据词频排序的词汇表,每个单词的huffman编码void *TrainModelThread(void *id){  long long a, b, d, 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;  unsigned long long next_random = (long long)id;  real f, g;  clock_t now;  //neu1:输入词向量,早CBOW中是上下文各个词向量之和,在skipgram中是中心词向量  real *neu1 = (real *)calloc(layer1_size, sizeof(real));  //neu1e:累积误差项  real *neu1e = (real *)calloc(layer1_size, sizeof(real));  FILE *fi = fopen(train_file, "rb");  //每个线程对应一段文本。根据线程id找到自己负责的文本的初始位置  //注意:这边的多线程分割方式并不能保证每一个线程分到的文件是互斥的。  //在实现多线程的过程中,作者并没有加锁的操作,而是对模型参数和词向量的修改可以任意执行,、  //这一点类似于基于随机梯度的方法,训练的过程与训练样本的训练是没有关系的,这样可以大大加快对词向量的训练。  //抛开多线程的部分,在每一个线程内执行的是对模型和词向量的训练。  fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);  while (1)  {    if (word_count - last_word_count > 10000)    {//word_count:当前线程当前时刻已训练的长度 //last_word_count:当前线程上一次记录时已训练的语料长度 //word_count_actual:所有线程已训练的长度      word_count_actual += word_count - last_word_count;      last_word_count = word_count;//更新一下      if ((debug_mode > 1))//根据debug等级显示训练信息      {        now=clock();//输出:当前学习率alpha//当前总进度:(总计已训练词/总词数 +1)//每秒速度,(有人说是每个线程每秒速度,但我不这么觉得)        printf("%cAlpha: %f  Progress: %.2f%%  Words/thread/sec: %.2fk  ", 13, alpha,         word_count_actual / (real)(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)(train_words + 1));      if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;    }//从训练样本中读取一个句子    if (sentence_length == 0)    {      while (1)      {//读一个词,这里的word是下标,是查vocb_hash得到的,具体实现在上面了        word = ReadWordIndex(fi);//从文件流中读取一个词,并返回这个词在词汇表中的位置        if (feof(fi)) break;//-1是读取失败        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;  //以ran的概率保留这个词  //下采样取的低16位,这里有个细节,下采样和负采样随机数取法略有不同          if (ran < (next_random & 0xFFFF) / (real)65536) continue;        }//sen里保存的是词的下标        sen[sentence_length] = word;        sentence_length++;        //太长了剩余词就丢弃。        if (sentence_length >= MAX_SENTENCE_LENGTH) break;      }  //定位到句首      sentence_position = 0;    }//注意!不同版本此处略有不同    if (feof(fi)) break;//这个位置是这一大段的出口,找了办天,每次以句为单位,逐词训练,读到文件结束或者下面这个条件跳出循环    if (word_count > train_words / num_threads) break;//如果当前线程已处理的单词超过了 阈值,则退出。    //读取第一个单词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取一个随机数范围是[0,window-1],所以窗口不是严格的ngram,这是一个trick    b = next_random % window;    if (cbow)    {  //train the cbow architecture      // in -> hidden  //一个词的窗口为[setence_position - window + b, sentence_position + window - b]        //因此窗口总长度为 2*window - 2*b + 1        for (a = b; a < window * 2 + 1 - b; a++) if (a != window)//扫描目标单词的左右几个单词,  //不要中心词,是我们要得到的      { //sentence_position:句子的位置,从0开始的        c = sentence_position - window + a;//窗口内的当前词        if (c < 0) continue;//限制一下不要越界        if (c >= sentence_length) continue;//限制一下不要越界        last_word = sen[c];//取出,得到当前词在词汇表中的下标        if (last_word == -1) continue;//下标是-1表示这个词是回车,不理会//计算窗口内的词向量和        for (c = 0; c < layer1_size; c++)//layer1_size词向量的维度,默认值是100        neu1[c] += syn0[c + last_word * layer1_size];//因为last_word是下标,所以这么算      }  //我这版本里用的不是求平均!!是求和  //下面是分层softmax的核心部分,也是对应伪代码第三部分的地方      if (hs) for (d = 0; d < vocab[word].codelen; d++)//开始遍历huffman树,每次一个节点      {        f = 0;//l2为当前遍历到的中间节点的向量在syn1中的起始位置          l2 = vocab[word].point[d] * layer1_size;//point应该记录的是huffman的路径。找到当前节点,并算出偏移        // Propagate hidden -> output//f为输入向量neu1与中间结点向量的内积        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))];//内积之后sigmoid函数        // 'g' is the gradient multiplied by the learning rate//g是梯度和学习率的乘积          //学习率越大,则错误分类的惩罚也越大,对中间向量的修正量也越大          //注意!word2vec中将Haffman编码为1的节点定义为负类,而将编码为0的节点定义为正类          //即一个节点的label = 1 - d          g = (1 - vocab[word].code[d] - f) * alpha;//偏导数的一部分        //layer1_size是向量的维度        // Propagate errors output -> hidden 反向传播误差,从huffman树传到隐藏层。下面就是把当前内节点的误差传播给隐藏层,syn1[c + l2]是偏导数的一部分。        for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];        // Learn weights hidden -> output 更新当前内节点的向量,后面的neu1[c]其实是偏导数的一部分        for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c];      }      // NEGATIVE SAMPLING  //如果采用负采样优化        //遍历所有正负样本(1个正样本+negative个负样本)      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;//负样本        }//下面的计算和多层softmax的更新很像,对应负采样的伪代码//注意:neule要在syn1neg前更新        l2 = target * layer1_size;        f = 0;        for (c = 0; c < layer1_size; c++)        f += neu1[c] * syn1neg[c + l2];//f为输入向量neu1与中间结点向量的内积        if (f > MAX_EXP)//这里与分层softmax不同,不在范围的更新直接指定。为什么?那为什么        g = (label - 1) * alpha;//计算加速,softmax的性质界定当超过范围是计算变化不大,但为什么有区别?        else if (f < -MAX_EXP)        g = (label - 0) * alpha;        else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;        //neule对应伪代码中的efor (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];//更新负样本向量      }  //分层softmax与负采样的伪码第四部分是相同的,所以公用      // hidden -> in  //对应分层softmax伪代码的第四部分      for (a = b; a < window * 2 + 1 - b; a++)      if (a != window)//cbow模型 更新的不是中间词语的向量,而是周围几个词语的向量。      {        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];//更新词向量      }    }//总结一下:syn0对应伪码中的v,syn1neg对应,neu1e对应e//下面的skip-gram和上面的crow的实现上很相似    else    {  //train skip-gram   //因为要依据中心词预测周为的词,所以还是需要对窗口进行扫描       for (a = b; a < window * 2 + 1 - b; a++)//对于窗口,这与CROW不同   //因为当然不同啊,需求不用啊,这里就是要预测这几个词啊!       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; //l1为当前单词的词向量在syn0中的起始位置        for (c = 0; c < layer1_size; c++)//初始化累积误差        neu1e[c] = 0;        // HIERARCHICAL SOFTMAX        if (hs)        for (d = 0; d < vocab[word].codelen; d++)//根据Haffman树上从根节点到当前词的叶节点的路径,遍历所有经过的中间节点        {          f = 0;  //l2为当前遍历到的中间节点的向量在syn1中的起始位置            l2 = vocab[word].point[d] * layer1_size;//point记录的是huffman的路径          // 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)//这个同cbow差不多        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;  //创建多线程,线程数为num_threads   pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t));  printf("Starting training using file %s\n", train_file);  //设置初始学习率    starting_alpha = alpha;  if (read_vocab_file[0] != 0)  ReadVocab();//从文件读入词汇  else  LearnVocabFromTrainFile();//或者从训练文件学习词汇  if (save_vocab_file[0] != 0)//根据需要,可以将词表中的词和词频输出到文件   SaveVocab();//保存词汇  if (output_file[0] == 0)//没指定输出文件就返回了  return;  //初始化训练网络   InitNet();  //如果使用负采样优化,则需要初始化采样的概率表   if (negative > 0) InitUnigramTable();  //计个时  start = clock();  //创建多线程,关于c的多线不是很熟  for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a);  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 //使用k-means进行聚类  {    // Run K-means on the word vectors//classes为最后要分成的类的个数    int clcn = classes, iter = 10, closeid;    int *centcn = (int *)malloc(classes * sizeof(int));//该类别的数量    int *cl = (int *)calloc(vocab_size, sizeof(int));//词到类别的映射    real closev, x;//cent:每个类的中心向量    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++)//iter轮迭代,默认是10    {      for (b = 0; b < clcn * layer1_size; b++)      cent[b] = 0;//质心清零      for (b = 0; b < clcn; b++)      centcn[b] = 1;//初始化每个类含有的单词数为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]]++;//类别数量加1      }      for (b = 0; b < clcn; b++)//遍历所有类别      {//closev:用来最大的内积,即距离最近          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//经过多次迭代后,逐渐会将词向量向正确的类靠拢      //输出K-means聚类结果到文件中    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.1b\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");    //词向量的维度,默认值是100    printf("\t-size <int>\n");    printf("\t\tSet size of word vectors; default is 100\n");    //窗口大小,默认是5    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");    printf(" in the training data will be randomly down-sampled; default is 0 (off), useful value is 1e-5\n");    //是否采用softmax体系    printf("\t-hs <int>\n");    printf("\t\tUse Hierarchical Softmax; default is 1 (0 = not used)\n");    //负样本的数量,默认是0,通常使用5-10。0表示不使用。    printf("\t-negative <int>\n");    printf("\t\tNumber of negative examples; default is 0, common values are 5 - 10 (0 = not used)\n");    //开启的线程数量    printf("\t-threads <int>\n");    printf("\t\tUse <int> threads (default 1)\n");    //最小阈值。对于出现次数少于该值的词,会被抛弃掉。    printf("\t-min-count <int>\n");    printf("\t\tThis will discard words that appear less than <int> times; default is 5\n");    //学习速率初始值,默认是0.025    printf("\t-alpha <float>\n");    printf("\t\tSet the starting learning rate; default is 0.025\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");    //debug模式,默认是2,表示在训练过程中会输出更多信息    printf("\t-debug <int>\n");    printf("\t\tSet the debug mode (default = 2 = more info during training)\n");    //是否用binary模式保存数据,默认是0,表示否。    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");    //是否采用continuous bag of words算法。默认是0,表示采用另一个叫skip-gram的算法。    printf("\t-cbow <int>\n");    printf("\t\tUse the continuous bag of words model; default is 0 (skip-gram model)\n");    //工具使用样例    printf("\nExamples:\n");    printf("./word2vec -train data.txt -output vec.txt -debug 2 -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1\n\n");    return 0;  }  output_file[0] = 0;  save_vocab_file[0] = 0;  read_vocab_file[0] = 0;  //classes:表示如果使用k-means聚类的话的聚类数  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 ((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]);  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 *)"-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));    //对sigmod函数的预处理部分,对[-MAX_EXP,MAX_EXP)区间内分为了EXP_TABLE_SIZE份,对每份内的sigmod值预先算出  //作为近似计算,具体操作是: 在[0,1]区间内均分EXP_TABLE_SIZE份,然后*2-1扩大、平移到[-1,1],在*MAX_EXP扩大到[-MAX_EXP,MAX_EXP)  for (i = 0; i < EXP_TABLE_SIZE; i++)  {//expTable[i] = exp((i -500)/ 500 * 6) 即 e^-6 ~ e^6    expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table    //expTable[i] = 1/(1+e^6) ~ 1/(1+e^-6)即 0.01 ~ 1 的样子    expTable[i] = expTable[i] / (expTable[i] + 1);                   // Precompute f(x) = x / (x + 1)  }  TrainModel();  return 0;}


原创粉丝点击