word2vec源码断断续续看了好几遍了,基本理清了流程和一些trick,添加了注释。 具体很多细节可以参考文末的参考链接,很详细。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#define MAX_STRING 100 //词最大长度
#define EXP_TABLE_SIZE 1000 //sigmoid函数近似区域的切割段数
#define MAX_EXP 6 //sigmoid 近似区间 -6~6
#define MAX_CODE_LENGTH 40 //huffman编码的最大长度
const int vocab_hash_size = 30000000; //词汇hash表大小 30*0.7 = 21M 词
typedef float real;
struct vocab_word
{
long long cn; //词频
int *point; // huffman编码对应内节点的路径
char *word, *code, codelen; //词,huffman编码,编码长度
};
char train_file[MAX_STRING], output_file[MAX_STRING];
char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING];
struct vocab_word *vocab;
//是否将Mode保存到二进制文件中、cbow模型、调试模式、窗口大小、最小词频、线程数、去除词频小余某值的词频
int binary = 0, cbow = 0, debug_mode = 2, window = 5, min_count = 5, num_thread = 12, min_reduce = 1;
int *vocab_hash; //存放词在字典中的位置。 例如,'a'计算出的hash为10000, 则vocab_hash[10000]存放的是'a'在词典中的位置。区分hash值和词典中的索引值
//定义词的最大数量(不足时会增加), 词汇数量, 词向量纬度
long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100;
//训练词数量(词*词频之和)、当前已处理过的词数、迭代次数、文件数目、是否需要将词汇使用k-means归类
long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0;
//学习率, 起始学习率,词频阈值(用来将词频过大的词去除)
real alpha = 0.025, starting_alpha, sample = 1e-3;
//词向量数组、huffman非叶子节点的向量、negitive 模式下的非叶子节点的向量,sigmoid查询表
real *syn0, *syn1, *syn1neg, *expTable;
clock_t start;
//是否hierarchical softmax, 负采样数量
int hs = 0, negative = 5;
//负采样使用的表及大小
const int table_size = 1e8;
int *table;
//如果是采用负采样的方法,此时还需要初始化每个词被选中的概率。在所有的词构成的词典中,每一个词出现的频率有高有低,
//我们希望,对于那些高频的词,被选中成为负样本的概率要大点,同时,对于那些出现频率比较低的词,我们希望其被选中成为负样本的频率低点
//每个单词的能量分布表,table在负样本抽样中用到
void InitUnigramTable()
{
int a, i;
double train_words_pow = 0;
double d1, power = 0.75;
table = (int *)malloc(table_size * sizeof(int));
//遍历词汇表,统计词的能量总值。 pow(x, y)函数用于求x的y次方
for (a = 0; a < vocab_size; a++)
train_words_pow += pow(vocab[a].cn, power);
i = 0;
d1 = pow(vocab[i].cn, power) / train_words_pow;
for (a = 0; a < table_size; a++)
{
table[a] = i;
if (a / (double)table_size > d1)
{
i++;
d1 += pow(vocab[i].cn, power) / train_words_pow;
}
if (i >= vocab_size)
i = vocab_size - 1;
}
}
//从文件中读取一个词
void ReadWord(char *word, FILE *fin)
{
int a = 0, ch;
while (!feof(fin))
{
ch = fgetc(fin);
if (ch == 13) //回车键
continue;
if ((ch == ' ') || (ch == '\t') || (ch == '\n'))
{
if (a > 0)
{
if (ch == '\n') //读到换行符,将它回吐,以便下次添加"</s>"
ungetc(ch, fin);
break; //已经有了有效的字符,则函数退出
}
if (ch == '\n')
{
strcpy(word, (char *)"</s>"); //添加新文本开始标志
return;
}
else
continue;
}
word[a] = ch;
a++;
if (a >= MAX_STRING - 1)
a--; //最后一个字符会被反复覆盖。 最后还会被0覆盖,所以应该可以直接返回了
}
word[a] = 0;
}
//返回一个词的hash值。 可能会冲突
int GetWordHash(char *word)
{
unsigned long long a, hash = 0;
for (a = 0; a < strlen(word); a++)
hash = hash * 257 + word[a];
hash = hash % vocab_hash_size;
return hash;
}
//返回一个词在词汇表中的位置,如果不存在则返回-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; //+1 是因为strlen不包含'/0'
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;
vocab_size++;
//如果需要重新分配内存. reallocate memory if needed
if (vocab_size + 2 >= vocab_max_size)
{
vocab_max_size += 1000;
vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(vocab_word));
}
hash = GetWordHash(word);
while (vocab_hash[hash] != -1)
hash = (hash + 1) % vocab_hash_size; //开放地址法解决冲突
vocab_hash[hash] = vocab_size - 1;
return vocab_size - 1;
}
//词按照词频排序
int VocabCompare(const char *w1, const char *w2)
{
return ((struct vocab_word *)w1)->cn - ((struct vocab_word *)w2)->cn;
}
//排序
void SortVocab()
{
int a, size;
unsigned int hash;
//sort the vocabulary and keep </s> at the first palce
qsort(&vocab[1], vocab_size - 1, sizeof(vocab_word), Vocabcompare);
for (a = 0; a < vocab_hash_size; a++)
vocab_hash[a] = -1;
size = vocab_size;
train_words = 0;
for (a = 0; a < size; a++)
{
//词频太小删除
if (vocab[a].cn < min_count)
{
vocab_size--;
free(vocab[a].word);
}
else
{
//计算hash 值
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));
//增加数组大小,为创建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));
}
}
//再次移除词频过小的词,缩减词汇表
void ReduceVocab()
{
int a, b = 0;