//
// 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>
// 一個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
// 定義最大的句子長度
#define MAX_SENTENCE_LENGTH 1000
// 定義最長的霍夫曼編碼長度
#define MAX_CODE_LENGTH 40
// 哈希,線性探測,開放定址法,裝填係數0.7
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;
// 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--; // 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 = 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
// 將單詞添加到詞彙表中
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; // 返回添加的單詞在詞彙表中的存儲位置
}
// Used later for sorting by word counts
// 比較函數,詞彙表需使用詞頻進行排序(qsort)
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); // 對詞彙表進行快速排序
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)); // 分配的多餘空間收回
// 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; // 最後剩下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++;
}
// 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'
// 每次尋找兩個最小的點做合併,最小的點爲0,詞小的點爲1
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 存儲的是word vectors
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; // 是個回車
// The subsampling randomly discards frequent words while keeping the ranking same
// 這裏的亞採樣是指 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
// 將窗口內的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++) 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' 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) { // 當前詞的分類器應當輸出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;
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;
// 累計誤差項清零
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' is the gradient multiplied by the learning rate
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;
}