关于神经网络训练的部分还没有看完,之后会陆续补全。
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
#define EXP_TABLE_SIZE 1000
#define MAX_EXP 6
#define MAX_SENTENCE_LENGTH 1000
#define MAX_CODE_LENGTH 40 //point域和code域大小
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; //声明词汇表结点指针vocab,此时还没有获得内存空间
//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;
long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100;
long long train_words = 0, word_count_actual = 0, file_size = 0, classes = 0;
real alpha = 0.025, starting_alpha, sample = 0;
real *syn0, *syn1, *syn1neg, *expTable;//浮点型指针
clock_t start; //可使用clock()/CLOCKS_PER_SEC来计算时间
int hs = 1, negative = 0;
const int table_size = 1e8;
int *table;
void InitUnigramTable() {
int a, i;
long long train_words_pow = 0;
real d1, power = 0.75;
table = (int *)malloc(table_size * sizeof(int));
for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);
i = 0;
d1 = pow(vocab[i].cn, power) / (real)train_words_pow;
for (a = 0; a < table_size; a++) {
table[a] = i;
if (a / (real)table_size > d1) {
i++;
d1 += pow(vocab[i].cn, power) / (real)train_words_pow;
}
if (i >= vocab_size) i = vocab_size - 1;
}
}
// Reads a single word from a file, assuming space + tab + EOL to be word boundaries
//从训练文件中读取一个单词,假定space + tab + EOL是词边界,并且在单词的结尾处添加一个空字符作为结束符
void ReadWord(char *word, FILE *fin) {
int a = 0, ch;//初始化下标a,ch是单个字符的ascii码,按%c可格式输出字符,%d输出ascii码
while (!feof(fin)) { //fin是训练文件的指针
ch = fgetc(fin);//逐字符读取文本
//以下判断当前字符ch
if (ch == 13) continue;//如果扫描到回车符,continue,再读一个字符来判断,对应回车符是'\r\n'的情况
if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {//判断词边界space+tab+EOL
if (a > 0) {//a>0时表示word[]里已经装了单词,下标a>0
if (ch == '\n') ungetc(ch, fin);//如果单词后直接接'\n',就把这个'\n'回退到输入流中,下次读会再次读出来,对应回车符是'\n'的情况
break; //下一步直接存到word[]里即可
}
//回车符可能是'\r\n'或者一个单纯的'\n'
if (ch == '\n') {//能走到这部说明a=0,开始处理回车,情况1:上一次读取的字符是回车符ascii=13 情况2:上一次把'\n'回退到了输入流中
strcpy(word, (char *)"</s>");//将回车符都替换成"</s>",并且"</s>"在vocab中索引是[0]
return;
} else continue;//这里表明出错,跳过当前字符再读一个字符 情况1:'\r'后没接'\n',接了' '或'\t'
//情况2:' '和'\t'交替出现或者多个' '或者多个'\t'连续出现时,跳过中间的' '或'\t'
}
word[a] = ch;//将读到的有效文本的字符存在word[]中,最大100个字符
a++;//word[]下标+1
//裁剪长度过长的单词,a=99时自减1,即长度过长的单词实际只存储了word[0]~word[97],word[98]=NUL结束符
if (a >= MAX_STRING - 1) a--; // Truncate too long words
}
word[a] = 0;//在单词的结尾加上空字符以便后来的判断
}
// Returns hash value of a word
int GetWordHash(char *word) {//根据单词作为关键词返回地址Addr
//散列函数的规则是,当前hash乘以257与单词的当前字符ascii码相加,遍历单词的每个字符,到最后再取模
unsigned long long a, hash = 0;//hash就是Addr,初始为0,一般为正
for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];//直接定址法H(key)=a*key+b
hash = hash % vocab_hash_size;//取模,vocab_hash_size默认是30000000
return hash;//返回散列地址
}
// Returns position of a word in the vocabulary; if the word is not found, returns -1
//返回一个词在词汇表vocab中的索引,如果不在词汇表中,返回-1
int SearchVocab(char *word) {
unsigned int hash = GetWordHash(word);//根据关键字获得词在vocab_hash表中的索引hash
while (1) {//循环查找
if (vocab_hash[hash] == -1) return -1;//说明vocab_hash表中的值是-1,没有这个单词
//如果值不是-1,说明有内容,开始比较并查找
if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash];//如果匹配到了,就返回vocab的索引
hash = (hash + 1) % vocab_hash_size;//否则线性探测,继续向下查找
}
return -1;//感觉这个return有点多余,while循环跳出的条件就是一定return了一个值
}
// 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) {
//将char*型的字符串(词语)加入到词汇表中,char*是传字符串首址,同时还更新了Hash表,以便实现快速查找
//函数同时更新了全局变量vocab_size:下标下移
unsigned int hash, length = strlen(word) + 1;//hash,length是传入单词的长度+1
if (length > MAX_STRING) length = MAX_STRING;//如果传入单词的字符数+1>100,则取length=100
vocab[vocab_size].word = (char *)calloc(length, sizeof(char));//将vocab结点的word指针指向存储单词的内容结点(实质是开辟内存空间)
strcpy(vocab[vocab_size].word, word);//将传入单词字符串的真实内容加入词汇表(基本就是申请空间-->赋值这个流程)
vocab[vocab_size].cn = 0;//初始化单词的出现次数为0
vocab_size++;//vocab[]结点下标+1,准备下一次的添加
// Reallocate memory if needed(必要时重新分配内存)
if (vocab_size + 2 >= vocab_max_size) {//当vocab_size增加到预设的最大值(1000)时,
vocab_max_size += 1000;//最大下标+1000,以1000为单位申请,不浪费内存
//realloc(要改变内存大小的指针名,新的总大小=数量*每个结点所占空间);
vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word));//扩大vocab的内存所占空间,复制到新申请的区域再free
}
hash = GetWordHash(word);//通过函数获得哈希表地址,传入的是单词字符串(首址),Hash表下标为正值,范围0~65535
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;//如果Hash表当前位置已满,就向下探测直到遇到一个空位置为止
vocab_hash[hash] = vocab_size - 1;//在Hash表中找到空位置后,设置值为词汇表中的当前下标vocab_size,自加后再减1,对应正确的下标
return vocab_size - 1;//返回对应当前单词位置在Hash表中的内容
}
// Used later for sorting by word counts
int VocabCompare(const void *a, const void *b) {//参数形式是固定的,a,b是指针
return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn;//按照cn域由大到小排序
}
// Sorts the vocabulary by frequency using word counts
//以出现次数(cn域)为关键字对vocab表进行排序,删减出现次数<min_count的单词的结点,并且为之后的二叉树结构申请内存空间(code域和point域)
void SortVocab() {
int a, size;//size用来保存当前vocab表大小
unsigned int hash;//仍然用来保存Hash表索引
// Sort the vocabulary and keep </s> at the first position
//排序时,保证'</s>'仍然出现在vocab表的第一位即vocab[0],故从vocab[1]开始
//qsort是自带的快排函数qsort(void *base,int nelem,int width,int (*comp)(const void *,const void *))
/***
*base:待排序数组首地址,nelem:数组中待排序元素数量,width:各元素的占用空间大小,(*comp)指向函数的指针,用于确定排序的顺序
***/
//带排序的元素数量正好是vocab[1]~vocab[vocab_size - 1],共有vocab_size - 1个元素
qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare);//vocab=&vocab[0],对结构体数组进行排序应该返回大的那个指针
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;//排序后,重新初始化Hash表
size = vocab_size;//size保存词汇表大小
train_words = 0;//重新计算train_words数量
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);//释放底部的单词的word域,注意cn域还在,即从后往前删除(下标a和vocab_size相向而行)
} 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;//写入新vocab索引到哈希表中
train_words += vocab[a].cn;//直接累计cn域的值即可获得新train_words值,实质上减掉了<min_count的那些单词的cn
}
}
//重新分配vocab表的大小是vocab_size + 1个内存空间,实质是释放了<min_count那些单词的所有域(cn+word)
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));//分配40个char型空间,code指向起始地址
vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int));//分配40个int型空间,point指向起始地址
}
}
// Reduces the vocabulary by removing infrequent tokens
//通过移除稀有词汇来减少词汇表的规模,留下出现频繁的词
void ReduceVocab() {
int a, b = 0;//a遍历词汇表,b作为新的下标
unsigned int hash;
for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) {//遍历词汇表,找出现次数大于min_reduce的单词,min_reduce默认是1
vocab[b].cn = vocab[a].cn;//复制出现次数cn到新下标
vocab[b].word = vocab[a].word;//复制单词指针到新下标
b++;//新下标下移
} else free(vocab[a].word);//else属于for循环,将那些出现次数<=min_reduce的单词的内存空间(只是word域)全部释放掉
vocab_size = b;//更新缩减后的词汇表长度
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;
//更新完vocab索引后,哈希表也需要重新计算,因为现在的哈希表中的内容是错误的
for (a = 0; a < vocab_size; a++) {//遍历当前词汇表
// Hash will be re-computed, as it is not actual
hash = GetWordHash(vocab[a].word);//得到每个单词在hash表中的索引
while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;//探测当前Hash值是否为空,如果空,向下探测直到找到一个空位置为止
vocab_hash[hash] = a;//将当前单词的vocab索引写入Hash表中
}
fflush(stdout);//强制缓冲区向外输出,这里没有printf()感觉没有必要吧
min_reduce++;//这里考虑的是,次数<=1的都被free了,如果下次还需要缩减规模的话,判断的次数至少应为2
}
// Create binary Huffman tree using the word counts
// Frequent words will have short uniqe binary codes
void CreateBinaryTree() {
long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH];
char code[MAX_CODE_LENGTH];
long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long));
for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn;
for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15;
pos1 = vocab_size - 1;
pos2 = vocab_size;
// Following algorithm constructs the Huffman tree by adding one node at a time
for (a = 0; a < vocab_size - 1; a++) {
// First, find two smallest nodes 'min1, min2'
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min1i = pos1;
pos1--;
} else {
min1i = pos2;
pos2++;
}
} else {
min1i = pos2;
pos2++;
}
if (pos1 >= 0) {
if (count[pos1] < count[pos2]) {
min2i = pos1;
pos1--;
} else {
min2i = pos2;
pos2++;
}
} else {
min2i = pos2;
pos2++;
}
count[vocab_size + a] = count[min1i] + count[min2i];
parent_node[min1i] = vocab_size + a;
parent_node[min2i] = vocab_size + a;
binary[min2i] = 1;
}
// Now assign binary code to each vocabulary word
for (a = 0; a < vocab_size; a++) {
b = a;
i = 0;
while (1) {
code[i] = binary[b];
point[i] = b;
i++;
b = parent_node[b];
if (b == vocab_size * 2 - 2) break;
}
vocab[a].codelen = i;
vocab[a].point[0] = vocab_size - 2;
for (b = 0; b < i; b++) {
vocab[a].code[i - b - 1] = code[b];
vocab[a].point[i - b] = point[b] - vocab_size;
}
}
free(count);
free(binary);
free(parent_node);
}
void LearnVocabFromTrainFile() {
//从给定纯文本文件中(已经过分词,词语之间以空格为界),学习出一个词汇表vocab
char word[MAX_STRING];//每个单词默认MAX_STRING=100个字符
FILE *fin;//文件指针
long long a, i;//循环控制变量
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;//哈希表(int型)全部初始化为-1
fin = fopen(train_file, "rb");//只读二进制方式打开文本文件
if (fin == NULL) {//检测是否可以打开训练文件
printf("ERROR: training data file not found!\n");
exit(1);
}
vocab_size = 0;//vocab_size是全局变量,即为vovab[vocab_size]的下标,初始是0
AddWordToVocab((char *)"</s>");//将词语(char*型的字符串)加入到词汇表vocab中,并同时更新Hash表,更新vocab_size
//注意,这里AddWordToVocab函数之后没有设置cn域,仍是0,因为文本中还没出现"</s>"
while (1) {
ReadWord(word, fin);//从训练文本中读取1个单词到word[],word[]末尾加一个空字符作为结束符
if (feof(fin)) break;//如果到达文件尾,就break
train_words++;//train_words默认是0,从1开始计数
//debug_mode默认是2,循环时的词数达到10w的整数倍时,输出调试信息
if ((debug_mode > 1) && (train_words % 100000 == 0)) {
printf("%lldK%c", train_words / 1000, 13);//ascii=13的字符是'\r',输出%c后回到这行的开始覆盖上次输出,显示训练了多少K个单词
fflush(stdout);//在printf()后使用,强制立刻输出,避免输出错误
}
i = SearchVocab(word);//得到的i是word在vocab表中的索引
//单词去重
if (i == -1) {//如果词汇表中没有当前单词
a = AddWordToVocab(word);//把当前单词加入到词汇表中,加入后返回在vocab中的索引a,且vocab_size++
vocab[a].cn = 1;//同时更新单词的出现次数为1
} else vocab[i].cn++;//如果在词汇表中找到了当前单词,只刷新出现次数即cn域即可
if (vocab_size > vocab_hash_size * 0.7) ReduceVocab();//检查当前vocab的容量是否大于21million,若是则减小规模
}
//读取文件结束,此时哈希表和vocab表都已经生成好
SortVocab();//按cn由大到小排序,排序后删减<min_count的,然后申请二叉树内存空间
if (debug_mode > 0) {//debug_mode默认=2,肯定输出
printf("Vocab size: %lld\n", vocab_size);//输出最新的vocab_size,经过去重后的总词数
printf("Words in train file: %lld\n", train_words);//输出训练的词数(包括重复的),之前train_words经过+=cn域来统计
}
file_size = ftell(fin);//经过while循环的break,此时文件指针一定移到了文件尾,然后ftell即可获得当前文件的长度,保存起来
fclose(fin);//关闭训练文件指针
}
//遍历排好序的词汇表,每行写单词+空格+出现次数,其中vocab表已经经过排序和删减
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);//关闭文件指针
}
//从给定文件中读取并建立词汇表,方法类似LearnVocabFromTrainFile()
//文件的格式为每行:单词+' '+次数,其中第一行的词应该必须是</s>,与生成时的思路一致,且次数cn可乱序,因为ReadVocab()中又进行了排序
void ReadVocab() {
long long a, i = 0;//循环控制变量
char c; //c用来读取每行的回车符
char word[MAX_STRING];//用来存读到的单词
FILE *fin = fopen(read_vocab_file, "rb");//打开词汇表文件的指针
if (fin == NULL) {//如果打开失败,输出信息并返回
printf("Vocabulary file not found\n");
exit(1);//exit(1)表示异常退出,exit(0)表示正常退出,exit终止全部程序并退出,return只终止子程序
}
for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1;//初始化Hash表,因为SortVocab()中会对保留下来的单词重新计算Hash值
vocab_size = 0;//记录词汇表大小,同时也是vocab[]的下标
while (1) {//循环读取
ReadWord(word, fin);//读取每行第一个数据:单词,并赋给word[]保存
if (feof(fin)) break;//如果已经读到文件尾,退出循环
a = AddWordToVocab(word);//将读到的单词添加进vocab结构中,返回a是当前word在vocab中对应的下标
fscanf(fin, "%lld%c", &vocab[a].cn, &c);//读取每行的第二个数据,同时更新当前单词的cn域,处理了一下每行结尾的回车符&c
i++;//这个i感觉没有用到
}
//到这里vocab结构已经建立好,可能是排好序的,如果不是通过LearnVocabFromTrainFile生成的话也可能是乱序的
SortVocab();//关于cn降序排序,删减<min_count,并申请二叉树结构内存空间
if (debug_mode > 0) {
printf("Vocab size: %lld\n", vocab_size);//输出vocab表的大小
printf("Words in train file: %lld\n", train_words);//输出train_words的大小(包括重复的),实际是+=cn来计算的
}
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);//获得"训练"文件包含的全部字节数,交给file_size保存,下面会用到
fclose(fin);//关闭文件指针
}
void InitNet() {
long long a, b;
//layer1_size是词向量的维度
a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real));
if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);}
if (hs) {
a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real));
if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);}
for (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));
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;
CreateBinaryTree();
}
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;
real *neu1 = (real *)calloc(layer1_size, sizeof(real));
real *neu1e = (real *)calloc(layer1_size, sizeof(real));
FILE *fi = fopen(train_file, "rb");
fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET);
while (1) {
if (word_count - last_word_count > 10000) {
word_count_actual += word_count - last_word_count;
last_word_count = word_count;
if ((debug_mode > 1)) {
now=clock();
printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha,
word_count_actual / (real)(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 = 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
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;
}
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 = next_random % window;
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];
}
if (hs) for (d = 0; d < vocab[word].codelen; d++) {
f = 0;
l2 = vocab[word].point[d] * layer1_size;
// Propagate hidden -> output
for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2];
if (f <= -MAX_EXP) continue;
else if (f >= MAX_EXP) continue;
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) {
target = word;
label = 1;
} else {
next_random = next_random * (unsigned long long)25214903917 + 11;
target = table[(next_random >> 16) % table_size];
if (target == 0) target = next_random % (vocab_size - 1) + 1;
if (target == word) continue;
label = 0;
}
l2 = target * layer1_size;
f = 0;
for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2];
if (f > MAX_EXP) g = (label - 1) * alpha;
else if (f < -MAX_EXP) g = (label - 0) * alpha;
else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c];
}
// hidden -> in
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a;
if (c < 0) continue;
if (c >= sentence_length) continue;
last_word = sen[c];
if (last_word == -1) continue;
for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c];
}
} else { //train skip-gram
for (a = b; a < window * 2 + 1 - b; a++) if (a != window) {
c = sentence_position - window + a;
if (c < 0) continue;
if (c >= sentence_length) continue;
last_word = sen[c];
if (last_word == -1) continue;
l1 = last_word * layer1_size;
for (c = 0; c < layer1_size; c++) neu1e[c] = 0;
// HIERARCHICAL SOFTMAX
if (hs) for (d = 0; d < vocab[word].codelen; d++) {
f = 0;
l2 = vocab[word].point[d] * layer1_size;
// Propagate hidden -> output
for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2];
if (f <= -MAX_EXP) continue;
else if (f >= MAX_EXP) continue;
else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];
// 'g' is the gradient multiplied by the learning rate
g = (1 - vocab[word].code[d] - f) * alpha;
// Propagate errors output -> hidden
for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];
// Learn weights hidden -> output
for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c + l1];
}
// NEGATIVE SAMPLING
if (negative > 0) for (d = 0; d < negative + 1; d++) {
if (d == 0) {
target = word;
label = 1;
} else {
next_random = next_random * (unsigned long long)25214903917 + 11;
target = table[(next_random >> 16) % table_size];
if (target == 0) target = next_random % (vocab_size - 1) + 1;
if (target == word) continue;
label = 0;
}
l2 = target * layer1_size;
f = 0;
for (c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2];
if (f > MAX_EXP) g = (label - 1) * alpha;
else if (f < -MAX_EXP) g = (label - 0) * alpha;
else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;
for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];
for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1];
}
// Learn weights input -> hidden
for (c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];
}
}
sentence_position++;
if (sentence_position >= sentence_length) {
sentence_length = 0;
continue;
}
}
fclose(fi);
free(neu1);
free(neu1e);
pthread_exit(NULL);
}
void TrainModel() {
long a, b, c, d;//普通for循环控制变量
FILE *fo;//文件指针
//类似地,可以把pt[]看作pthread_t型的数组
pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t));//pthread_t用于声明线程id,num_threads是线程的数量,可手动设置
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();//将已排好序,经过删减后的词汇表输出到文件中保存以备下次直接读取,除第一行</s>外,其余的降序排列
if (output_file[0] == 0) return;//若没有指定输出文件名则直接返回
//词表vocab和哈希表vocab_hash都建立好了,开始训练神经网络
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) {
// 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, " %ld:%lf", b+1,syn0[a * layer1_size + b]);
fprintf(fo, "\n");
}
} else {
// Run K-means on the word vectors
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) {
//寻找参数在命令行的位置,找到返回位置,否则返回-1
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");
printf("\t-size <int>\n");
printf("\t\tSet size of word vectors; default is 100\n");
printf("\t-window <int>\n");
printf("\t\tSet max skip length between words; default is 5\n");
printf("\t-sample <float>\n");
printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency");
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");
printf("\t\tUse Hierarchical Softmax; default is 1 (0 = not used)\n");
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");
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");
printf("\t-debug <int>\n");
printf("\t\tSet the debug mode (default = 2 = more info during training)\n");
printf("\t-binary <int>\n");
printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n");
printf("\t-save-vocab <file>\n");
printf("\t\tThe vocabulary will be saved to <file>\n");
printf("\t-read-vocab <file>\n");
printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n");
printf("\t-cbow <int>\n");
printf("\t\tUse the continuous bag of words model; default is 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;
}
//这三个文件名称的第一个字符设置为数字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]);//词向量维度保存为layer1_size
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]);//设置debug_mode参数,默认为2
if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]);//设置二进制参数,默认为0
if ((i = ArgPos((char *)"-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]);//是否使用CBOW算法
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]);//高频词亚采样的阈值,默认是0
if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]);//是否采用层次softmax,默认是1
if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]);//负例数目,默认是0,常见数目5-10
if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);//多线程数目,默认是1
if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]);//出现次数少于min_count的词语被忽略,默认是5,训完整时应设为0
if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]);//输出词聚类结果而非词向量,默认0(输出词向量)
//calloc分配vocab_max_size个长度为sizeof()的连续空间,成功返回起始地址指针,否则返回NULL
vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word));//vocab为起始地址指针
vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int));//哈希表起始地址指针为vocab_hash(int型)
//预先计算好指数表,使用时查表即可,算一个trick
expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real));//分配1001个浮点型内存空间,每个可存一个浮点数
//把expTable[]就当作一个浮点型数组
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)
}
//************my debug************
//训练模型时使用的一些小函数均可在下面测试功能,并把TrainModel注释掉即可
TrainModel();// 主要函数,训练模型
return 0;
}
原文地址:http://blog.csdn.net/messiandzcy/article/details/44100391