word2vec源码解析之word2phrase.c

word2vec源码解析之word2phrase.c


最近研究了一下google的开源项目word2vector,http://code.google.com/p/word2vec/。

其实这玩意算是神经网络在文本挖掘的一项成功应用。

word2vec.c是核心代码,不过感觉先读word2phrase.c代码,再读前者比较好。

一来word2phrase.c算法简单点,容易理解,

二来word2phrase.c里面有些函数在word2vec.c会用到,读完word2phrase.c有助于读word2vec.c。


说白了,word2phrase就是将词语拼成短语。具体算法在论文《Distributed Representations of Words and Phrases and their Compositionality》讲到。

我也写过这篇论文的学习笔记http://blog.csdn.net/lingerlanlan/article/details/38048335


下面是源码注释,建议从main函数开始读。


//  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 60

const int vocab_hash_size = 500000000; // Maximum 500M entries in the vocabulary

typedef float real;                    // Precision of float numbers

struct vocab_word 
{
  long long cn;//词频
  char *word;//词语
};

char train_file[MAX_STRING], output_file[MAX_STRING];
struct vocab_word *vocab;
int debug_mode = 2, min_count = 5, *vocab_hash, min_reduce = 1;
long long vocab_max_size = 10000, vocab_size = 0;
long long train_words = 0;
real threshold = 100;

unsigned long long next_random = 1;

// Reads a single word from a file, assuming space + tab + EOL to be word boundaries
//从文件流中读取一个词语
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') 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
//算出一个词语的hash值
int GetWordHash(char *word) 
{
  unsigned long long a, hash = 1;
  for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a];
  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;
  vocab_size++;
  // Reallocate memory if needed
  if (vocab_size + 2 >= vocab_max_size) 
  {
    vocab_max_size += 10000;
    vocab=(struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word));
  }
  hash = GetWordHash(word);
  while (vocab_hash[hash] != -1) //知道hash值没有冲突
    hash = (hash + 1) % vocab_hash_size;
  vocab_hash[hash]=vocab_size - 1;//hash表的作用,由一个词的hash值映射到该词在词汇表中的位置
  return vocab_size - 1;
}

// Used later for sorting by word counts
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;
  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;
  for (a = 0; a < vocab_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
      hash = GetWordHash(vocab[a].word);
      while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size;
      vocab_hash[hash] = a;
    }
  }
  vocab = (struct vocab_word *)realloc(vocab, vocab_size * sizeof(struct vocab_word));
}

// 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;
  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 LearnVocabFromTrainFile() 
{
  char word[MAX_STRING], last_word[MAX_STRING], bigram_word[MAX_STRING * 2];
  FILE *fin;
  long long a, i, start = 1;
  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;
    if (!strcmp(word, "</s>")) 
    {
      start = 1;
      continue;
    } 
    else start = 0;
    train_words++;
    if ((debug_mode > 1) && (train_words % 100000 == 0)) 
    {
      printf("Words processed: %lldK     Vocab size: %lldK  %c", train_words / 1000, vocab_size / 1000, 13);
      fflush(stdout);
    }
    i = SearchVocab(word);//查找该词在词汇表的位置
    if (i == -1) //第一次遇到,则添加到词汇表中
    {
      a = AddWordToVocab(word);
      vocab[a].cn = 1;
    } 
    else vocab[i].cn++;//增加词汇
    if (start) continue;
    sprintf(bigram_word, "%s_%s", last_word, word);//两个词频拼在一起,生成“假短语”
    bigram_word[MAX_STRING - 1] = 0;
    strcpy(last_word, word);
    i = SearchVocab(bigram_word);//查找“短语”是否在词汇表中存在
    if (i == -1) //不存在,则添加进去
    {
      a = AddWordToVocab(bigram_word);
      vocab[a].cn = 1;
    } 
    else vocab[i].cn++;//存在则增加词频
    if (vocab_size > vocab_hash_size * 0.7) ReduceVocab();//如果词汇表太大了,则缩减
  }
  SortVocab();//根据词频排序
  if (debug_mode > 0) 
  {
    printf("\nVocab size (unigrams + bigrams): %lld\n", vocab_size);
    printf("Words in train file: %lld\n", train_words);
  }
  fclose(fin);
}

void TrainModel()
{
  long long pa = 0, pb = 0, pab = 0, oov, i, li = -1, cn = 0;
  char word[MAX_STRING], last_word[MAX_STRING], bigram_word[MAX_STRING * 2];
  real score;
  FILE *fo, *fin;
  printf("Starting training using file %s\n", train_file);
  LearnVocabFromTrainFile();//遍历训练文件,统计词频,生成词汇表
  fin = fopen(train_file, "rb");
  fo = fopen(output_file, "wb");
  word[0] = 0;
  while (1) 
  {
    strcpy(last_word, word);//上一个词语
    ReadWord(word, fin);//从文件流读进新的词语
    if (feof(fin)) break;
    if (!strcmp(word, "</s>")) 
    {
      fprintf(fo, "\n");
      continue;
    }
    cn++;
    if ((debug_mode > 1) && (cn % 100000 == 0)) 
    {
      printf("Words written: %lldK%c", cn / 1000, 13);
      fflush(stdout);
    }
    oov = 0;
    i = SearchVocab(word);//返回该词在词汇表的位置,-1表示
    if (i == -1) oov = 1; //如果第一次遇到该词
    else pb = vocab[i].cn;//该词的词频
    if (li == -1) oov = 1;//如果上一个词是第一次遇到
    li = i;
    sprintf(bigram_word, "%s_%s", last_word, word);//两个词语拼在一起,形成“短语”
    bigram_word[MAX_STRING - 1] = 0;
    i = SearchVocab(bigram_word);//“短语”是否在词汇表中存在
    if (i == -1) //不存在
      oov = 1; 
    else pab = vocab[i].cn;//存在,则找出该“短语”的词频
    if (pa < min_count) oov = 1;
    if (pb < min_count) oov = 1;
    if (oov) score = 0; //oov的值为1,则认为这两个词语不可能在一起,不能形成短语
    else score = (pab - min_count) / (real)pa / (real)pb * (real)train_words;//根据公式算出两个词语“在一起”的可能性
    if (score > threshold) //如果分数大于某个阈值,则认为他们能“在一起”,能形成短语
    {
      fprintf(fo, "_%s", word);//往文件输出,连在上一个词,注意这两个词用“_”连在一起,表示他们是短语。
      pb = 0;
    } 
    else fprintf(fo, " %s", word);//往文件输出,用空格隔开,表示这个两个词语不是短语。
    pa = pb;
  }
  fclose(fo);
  fclose(fin);
}

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("WORD2PHRASE tool v0.1a\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 / phrases\n");

    //最小词频,如果某个词语小于这个阈值,则丢弃;默认为5。
    printf("\t-min-count <int>\n");
    printf("\t\tThis will discard words that appear less than <int> times; default is 5\n");

    //阈值,两个词语通过一个函数计算得到一个分数,再跟这个阈值比较,衡量是否能形成短语;默认是100。
    printf("\t-threshold <float>\n");
    printf("\t\t The <float> value represents threshold for forming the phrases (higher means less phrases); default 100\n");

    //是否为debug模式
    printf("\t-debug <int>\n");
    printf("\t\tSet the debug mode (default = 2 = more info during training)\n");

    printf("\nExamples:\n");
    printf("./word2phrase -train text.txt -output phrases.txt -threshold 100 -debug 2\n\n");
    return 0;
  }
  if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]);
  if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);
  if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]);
  if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]);
  if ((i = ArgPos((char *)"-threshold", argc, argv)) > 0) threshold = atof(argv[i + 1]);
  vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word));//词汇表申请空间
  vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int));//hash表申请空间
  TrainModel();
  return 0;
}






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值