學習Word2vec


  有感於最近接觸到的一些關於深度學習的知識,遂打算找個東西來加深理解。首選的就是以前有過接觸,且火爆程度非同一般的word2vec。嚴格來說,word2vec的三層模型還不能算是完整意義上的深度學習,本人確實也是學術能力有限,就以此為例子,打算更全面的了解一下這個工具。在此期間,參考了[1][2][3]的博文,尤其以[1]的注釋較為精彩。本文不涉及太多原理,想要對word2vec有更深入的了解,可以閱讀Mikolov在2013年的兩篇文章[4][5]。同時文獻[6]對word2vec中的模型和一些小技巧進行了詳細說明。

  目前來說,詞向量還是一個比較火的東西,今天還在微博上看到一些大牛在轉發斯坦福關於“深度學習和自然語言處理”的課程,里面就講到這些。同時,在參加老板組織的一個國際會議優秀論文報告會上也發現,今年(2015)的ACL和IJCAI也有一些關於詞向量的優質論文。詞向量,顧名思義,就是用一個向量來表示一個單詞,這個向量不是隨便的一個,而是根據單詞在語料中的上下文而產生,具有意義的向量。而word2vec就是根據語料來生成單詞向量的一個工具。生成單詞向量有什么用?最主要的一點就是用來計算相似度。直接計算兩個詞的余弦值便可以得到。還有一個用途就是機器翻譯,如圖1所示是英語的數字1-5和西班牙語的數字1-5的詞向量,經過主成份分析(PCA)在二維空間上的映射。可以發現,兩種語言的1-5對應的位置相差無幾,這說明兩種不同語言對應向量空間的結果之間具有相似性。當然,詞向量的作用還有很多很多,此處不一一介紹。

圖1. 五個詞在兩個向量空間中的位置

  說實話,之前也看過一些word2vec的講義,大多是講數序模型,公式推導之類的。很難理清思路,看過兩三遍之后還是沒能理清他具體是怎么進行的,一開始最讓小白我困惑的是Skip-gram模型和CBOW模型,什么用上下文預測中間詞,用中間詞預測上下文,這語料哪涉及到預測啊!?后來看了源碼發現,其實這是模型訓練的一種思路,用這兩種思路進行調參。兩者的區別除了在於:

  cbow模型是用上下文預測中間的詞,並且參數是用的上下文詞向量的和

  skip-gram模型是中間的詞預測上下文,並且參數是中間詞的詞向量

  下面小白我就對word2vec的源碼做一些解析,是在[1]的基礎上,結合了一些自己的理解。主要包含一些輔助函數的作用,參數的設置和訓練的過程:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
// 一個word的最大長度
#define MAX_STRING 100 
// 對f的運算結果進行緩存,存儲1000個,需要用的時候查表
#define EXP_TABLE_SIZE 1000
// 最大計算到6 (exp^6 / (exp^6 + 1)),最小計算到-6 (exp^-6 / (exp^-6 + 1))
#define MAX_EXP 6
// 定義最大的句子長度,句子以</s>結束,如果沒有結束符,則長度最長為1000
#define MAX_SENTENCE_LENGTH 1000
// 定義最長的霍夫曼編碼長度
#define MAX_CODE_LENGTH 40

// 哈希,線性探測,開放定址法,裝填系數0.7
const int vocab_hash_size = 30000000;  // 詞庫中最多有30 * 0.7 = 21M個單詞
typedef float real;                    // 浮點數精度
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;
// binary 0則vectors.bin輸出為二進制(默認),1則為文本形式
// cbow 1使用cbow框架,0使用skip-gram框架
// debug_mode 大於0,加載完畢后輸出匯總信息,大於1,加載訓練詞匯的時候輸出信息,訓練過程中輸出信息
// window 窗口大小,在cbow中表示了word vector的最大的sum范圍,在skip-gram中表示了max space between words(w1,w2,p(w1 | w2))
// min_count 刪除長尾詞的詞頻標准
// num_threads 線程數
// min_reduce ReduceVocab刪除詞頻小於這個值的詞,因為哈希表總共可以裝填的詞匯數是有限的
int binary = 0, cbow = 0, debug_mode = 2, window = 5, min_count = 5, num_threads = 1, min_reduce = 1;
int *vocab_hash; // 詞匯表的hash存儲,下標是詞的hash,內容是詞在vocab中的位置,a[word_hash] = word index in vocab
// vocab_max_size 詞匯表的最大長度,動態擴增,每次擴1000
// vocab_size 詞匯表的現有長度,接近vocab_max_size的時候會擴容
// layer1_size 隱層的節點數/詞向量大小
long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100;
// train_words 訓練的單詞總數(詞頻累加)
// word_count_actual 已經訓練完的word個數
// file_size 訓練文件大小,ftell得到
// classes 輸出word clusters的類別數
long long train_words = 0, word_count_actual = 0, file_size = 0, classes = 0;
// alpha BP算法的學習速率,過程中自動調整
// starting_alpha 初始alpha值
// sample 亞采樣概率的參數,亞采樣的目的是以一定概率拒絕高頻詞,使得低頻詞有更多出鏡率,默認為0,即不進行亞采樣
real alpha = 0.025, starting_alpha, sample = 0;
// syn0 單詞的向量輸入 concatenate word vectors
// syn1 hs(hierarchical softmax)算法中隱層節點到霍夫曼編碼樹非葉結點的映射權重
// syn1neg ns(negative sampling)中隱層節點到分類問題的映射權重
// expTable 預先存儲f函數結果,算法執行中查表
real *syn0, *syn1, *syn1neg, *expTable;
// start 算法運行的起始時間,會用於計算平均每秒鍾處理多少詞
clock_t start;
// hs 采用hs還是ns的標志位,默認采用hs
int hs = 1, negative = 0;
// table_size 靜態采樣表的規模
// table 采樣表
const int table_size = 1e8;
int *table;

// 根據詞頻生成采樣表,詞頻越高,占據在表中的數目越大,用於表示詞頻分布
void InitUnigramTable() {
  int a, i;
  long long train_words_pow = 0;
  real d1, power = 0.75; // 概率與詞頻的power次方成正比
  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
// 每次從fin中讀取一個單詞
void ReadWord(char *word, FILE *fin) {
  int a = 0, ch;
  while (!feof(fin)) {
    ch = fgetc(fin);
    if (ch == 13) continue;
    // ASCII值為8、9、10 和13 分別轉換為退格、制表、換行和回車字符
    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--; // 如果單詞過長 } word[a] = 0; } // 獲取單詞的哈希值 int GetWordHash(char *word) { unsigned long long a, hash = 0; for (a = 0; a < strlen(word); a++)
    hash = hash * 257 + word[a]; // hash計算方法 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; // 應該到不了這里吧…… } // 獲取單詞的索引值 int ReadWordIndex(FILE *fin) { char word[MAX_STRING]; ReadWord(word, fin); if (feof(fin)) return -1; return SearchVocab(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)); // 單詞存儲 strcpy(vocab[vocab_size].word, word); vocab[vocab_size].cn = 0; // 在調用函數之外賦值1 vocab_size++; // 詞匯表現有單詞數 // Reallocate memory if needed if (vocab_size + 2 >= vocab_max_size) { vocab_max_size += 1000; // 每次增加1000個詞位 vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); } hash = GetWordHash(word); // 獲得hash表示 while (vocab_hash[hash] != -1)     hash = (hash + 1) % vocab_hash_size; // 線性探索hash vocab_hash[hash] = vocab_size - 1; // 記錄在詞匯表中的存儲位置 return vocab_size - 1; // 返回添加的單詞在詞匯表中的存儲位置 } // 比較函數,詞匯表需使用詞頻進行排序(qsort) int VocabCompare(const void *a, const void *b) { return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; } // 對單詞按照詞頻排序 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); // 對詞匯表進行快速排序 for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; // 詞匯重排了,哈希記錄的index也亂了,所有的hash記錄清除,下面會重建 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) { // 清除長尾詞 vocab_size--; free(vocab[vocab_size].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; vocab_hash[hash] = a; train_words += vocab[a].cn; // 詞頻累加 } } vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word)); // 分配的多余空間收回 // 給霍夫曼編碼和路徑的詞匯表索引分配空間 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)); } }

  此處,有些人可能不理解為什么要重排。這里我就列一下單詞和哈希值在代碼里面的數據關系,就比較好理解了。所以一旦單詞表重排,單詞的位置相應改變,哈希記錄表vocab_hash就要重新構造。

// 刪除詞頻不大於min_reduce的詞
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; // 最后剩下b個詞,詞頻均大於min_reduce
  	// 重新分配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;
   	 vocab_hash[hash] = a;
  }
  fflush(stdout);
  min_reduce++;
}
// 根據詞頻生成霍夫曼樹
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++) {
    // 每次尋找兩個最小的點做合並,最小的點的分支為0,詞小的點的分支為1
  //由於是已經按照詞頻高低排好序的,最后的兩個單詞就是詞頻最低的
  //pos1控制葉子節點,pos2控制非葉子節點
  //min1i是左分支,min2i是右分支
    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;
    }
    // 以下要注意的是,同樣的位置,point總比code深一層
    vocab[a].codelen = i; // 編碼長度賦值,少1,沒有算根節點
    vocab[a].point[0] = vocab_size - 2; // 逆序,把第一個賦值為root(即2*vocab_size - 2 - vocab_size)
    for (b = 0; b < i; b++) { // 逆序處理
      vocab[a].code[i - b - 1] = code[b]; // 編碼逆序,沒有根節點,左子樹0,右子樹1
      vocab[a].point[i - b] = point[b] - vocab_size; // 其實point數組最后一個是負的,用不到,point的長度是編碼的真正長度,比code長1
    }
  }
  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>"); // 首先添加的是回車
  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) { // 如果這個單詞不存在,我們將其加入hash表
      a = AddWordToVocab(word);
      vocab[a].cn = 1;
    } else vocab[i].cn++; // 否則詞頻加一
    if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); // 如果超出裝填系數,將詞匯表擴容
  }
  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() {
  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;
  // posix_memalign() 成功時會返回size字節的動態內存,並且這塊內存的地址是alignment(這里是128)的倍數
  // syn0 存儲的是就是單詞向量
  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) { // hierarchical softmax
     // hs中,用syn1
    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 (b = 0; b < layer1_size; b++) 
  for (a = 0; a < vocab_size; a++)
     	syn1[a * layer1_size + b] = 0;
  }
  if (negative>0) { // negative sampling
    // ns中,用syn1neg
    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 (b = 0; b < layer1_size; b++) 
    for (a = 0; a < vocab_size; a++)   syn1neg[a * layer1_size + b] = 0; } for (b = 0; b < layer1_size; b++)
  for (a = 0; a < vocab_size; a++)   syn0[a * layer1_size + b] = (rand() / (real)RAND_MAX - 0.5) / layer1_size; // 隨機初始化word vectors CreateBinaryTree(); // 創建霍夫曼樹 } void *TrainModelThread(void *id) { // word 向sen中添加單詞用,句子完成后表示句子中的當前單詞 // last_word 上一個單詞,輔助掃描窗口 // sentence_length 當前句子的長度(單詞數) // sentence_position 當前單詞在當前句子中的index long long a, b, d, word, last_word, sentence_length = 0, sentence_position = 0; // word_count 已訓練語料總長度 // last_word_count 保存值,以便在新訓練語料長度超過某個值時輸出信息 // sen 單詞數組,表示句子 long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1]; // l1 ns中表示word在concatenated word vectors中的起始位置,之后layer1_size是對應的word vector,因為把矩陣拉成長向量了 // l2 cbow或ns中權重向量的起始位置,之后layer1_size是對應的syn1或syn1neg,因為把矩陣拉成長向量了 // c 循環中的計數作用 // target ns中當前的sample // label ns中當前sample的label long long l1, l2, c, target, label; // id 線程創建的時候傳入,輔助隨機數生成 unsigned long long next_random = (long long)id; // f e^x / (1/e^x),fs中指當前編碼為是0(父親的左子節點為0,右為1)的概率,ns中指label是1的概率 // g 誤差(f與真實值的偏離)與學習速率的乘積 real f, g; // 當前時間,和start比較計算算法效率 clock_t now; real *neu1 = (real *)calloc(layer1_size, sizeof(real)); // 隱層節點 real *neu1e = (real *)calloc(layer1_size, sizeof(real)); // 誤差累計項,其實對應的是Gneu1 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)(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) { // 如果當前句子長度為0 while (1) { word = ReadWordIndex(fi); if (feof(fi)) break; // 讀到文件末尾 if (word == -1) continue; // 沒有這個單詞 word_count++; // 單詞計數增加 if (word == 0) break; // 是個回車 // 這里的亞采樣是指 Sub-Sampling,Mikolov 在論文指出這種亞采樣能夠帶來 2 到 10 倍的性能提升,並能夠提升低頻詞的表示精度。 // 低頻詞被丟棄概率低,高頻詞被丟棄概率高 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; } sen[sentence_length] = word; sentence_length++; if (sentence_length >= MAX_SENTENCE_LENGTH) break; } sentence_position = 0; // 當前單詞在當前句中的index,起始值為0 } if (feof(fi)) break; // 照應while中的break,如果讀到末尾,退出 if (word_count > train_words / num_threads) break; // 已經做到了一個thread應盡的工作量,就退出 word = sen[sentence_position]; // 取句子中的第一個單詞,開始運行BP算法 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到window-1,指定了本次算法操作實際的窗口大小 // cbow 框架 if (cbow) { //train the cbow architecture // in -> hidden // 從輸入層到隱層所進行的操作實際就是窗口內上下文向量的加和 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++) neu1[c] += syn0[c + last_word * layer1_size]; } // hs if (hs) for (d = 0; d < vocab[word].codelen; d++) { // 這里的codelen其實是少一個的,所以不會觸及point里面最后一個負數 f = 0; l2 = vocab[word].point[d] * layer1_size; // 路徑上的點 // Propagate hidden -> output // 准備計算f for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2]; // 不在expTable內的舍棄掉,作者說計算精度有限,怕有不好印象,但這里改成太小的都是0,太大的都是1,運行結果還是有差別的 // if (f <= -MAX_EXP) continue; // else if (f >= MAX_EXP) continue; if (f <= -MAX_EXP) f = 0; else if (f >= MAX_EXP) f = 1; // 從expTable中查找,快速計算 else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; // g 實際為負梯度中公共的部分與 Learning rate alpha 的乘積

           

        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) { // 當前詞的分類器應當輸出1
          target = word;
          label = 1;
        } else { // 采樣使得與target不同,不然continue,label為0,也即最多采樣negative個negative sample
          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];
        // 這里直接上0、1,沒有考慮計算精度問題
        if (f > MAX_EXP) g = (label - 1) * alpha;
        else if (f < -MAX_EXP) g = (label - 0) * alpha;
    // g 並非梯度,可以看做是一個乘了學習率的 error(label與輸出f的差)。損失函數Loss=-log Likehood = -label•logf-(1-lable)•log(1-f),推導同上。
        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
      // 根據隱層節點累積誤差項,更新word vectors
      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; 
        // 每次循環neu1e都被置零了
        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
          // 待預測單詞的 word vecotr 和 隱層-霍夫曼樹非葉節點權重 的內積
          for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2];
          // 同cbow中hs的討論
          // if (f <= -MAX_EXP) continue;
          // else if (f >= MAX_EXP) continue;
          if (f <= -MAX_EXP) f = 0;
          else if (f >= MAX_EXP) f = 1;
          // 以下內容同之前的cbow
          else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
          //  g 就是梯度中的公共部分與學習率的乘積,此處損失函數的計算方式有別於CBOW模型,具體參考文獻[6]。
          g = (1 - vocab[word].code[d] - f) * alpha; // 這里的code[d]其實是下一層的,code錯位了,point和code是錯位的!
          // 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];
          // 以下內容同之前的cbow
          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));
  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(); // 開始計時
  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) { // 保存 word vectors
    // Save the word vectors
    fprintf(fo, "%lld %lld\n", vocab_size, layer1_size); // 詞匯量,vector維數
    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-means算法
    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.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"); // 指定輸出文件,以存儲word vectors,或者單詞類
    printf("\t\tUse <file> to save the resulting word vectors / word clusters\n");
    printf("\t-size <int>\n"); // word vector的維數,對應 layer1_size,默認是100
    printf("\t\tSet size of word vectors; default is 100\n");
    // 窗口大小,在cbow中表示了word vector的最大的疊加范圍,在skip-gram中表示了max space between words(w1,w2,p(w1 | w2))
    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");
    printf("\t-hs <int>\n"); // 使用hs求解,默認為1
    printf("\t\tUse Hierarchical Softmax; default is 1 (0 = not used)\n");
    printf("\t-negative <int>\n"); // 使用ns的時候采樣的樣本數
    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");
    printf("\t-alpha <float>\n"); // 初始的學習速率,默認為0.025
    printf("\t\tSet the starting learning rate; default is 0.025\n");
    printf("\t-classes <int>\n"); // 輸出單詞類別數,默認為0,也即不輸出單詞類
    printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n");
    printf("\t-debug <int>\n"); // 調試等級,默認為2
    printf("\t\tSet the debug mode (default = 2 = more info during training)\n");
    printf("\t-binary <int>\n"); // 是否將結果輸出為二進制文件,默認為0,即不輸出為二進制
    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"); // 詞匯表加載文件,則可以不指定trainfile
    printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n");
    printf("\t-cbow <int>\n"); // 使用cbow框架
    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;
  // 參數與變量的對應關系
  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));
  // 提前產生e^-6 到 e^6 之間的f值 ,便於提高運算效率
  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;
}

[1]   http://blog.sina.com.cn/s/blog_64ac3ab10102uwjo.html

[2]   http://xiaoquanzi.net/?p=156

[3]   http://bbs.byr.cn/#!article/ML_DM/12813?au=wechat

[4]   Mikolov T, Sutskever I, Chen K, et al. Distributed representations of words and phrases and t heir compositionality[C]//Advances in Neural Information Processing Systems. 2013:    3111-3119.

[5]   Mikolov T, Chen K, Corrado G, et al. Efficient estimation of word representations in vector space[J]. arXiv preprint arXiv:1301.3781, 2013.

[6]   http://techblog.youdao.com/?p=915

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM