下面几篇是deeplearning4j在文本方面的例子,文本方面我还没有实战经验,只是大概看过spark-ml中word2vector等的源码,word2vector是比较传统的模型,本质上可以把它理解成词的降维,而gloVe是和word2vector功能相似的模型,把句子的信息和全局的信息结合,目的是在语义和语句上都获得更好的表达效果,下面我们仅从使用的角度上看gloVe模型的代码
public class GloVeExample { private static final Logger log = LoggerFactory.getLogger(GloVeExample.class);//获取日志 public static void main(String[] args) throws Exception { File inputFile = new ClassPathResource("raw_sentences.txt").getFile();//获取文件名称并打印绝对地址 System.out.println(inputFile.getAbsolutePath()); // creating SentenceIterator wrapping our training corpus SentenceIterator iter = new BasicLineIterator(inputFile.getAbsolutePath());//通过基础的行迭代器,构建句子迭代器 // Split on white spaces in the line to get words TokenizerFactory t = new DefaultTokenizerFactory();//创建切分实例,用空格切分单词 t.setTokenPreProcessor(new CommonPreprocessor());//预处理,把逗号都去掉并且转成小写字母 Glove glove = new Glove.Builder()//构建一个单机Glove模型,Glove继承了SequenceVectors,SequenceVectors继承结构也比较复杂public class SequenceVectors<T extends SequenceElement> extends WordVectorsImpl<T> implements WordVectors {.iterate(iter)//装入迭代的句子 .tokenizerFactory(t)//装入切分器 .alpha(0.75)//这个是权重函数的指数参数,默认0.75 .learningRate(0.1)//学习率 // number of epochs for training .epochs(25)//训练的步数 // cutoff for weighting function .xMax(100)//损失函数里有个概率函数,概率函数是个截断函数,防止高频词对模型的影响,这个100就是截断阈值 // training is done in batches taken from training corpus .batchSize(1000)//批大小 // if set to true, batches will be shuffled before training .shuffle(true)//如果设置成true,训练前批会随机排序 // if set to true word pairs will be built in both directions, LTR and RTL .symmetric(true)//symmetric是对称的意思,如果设置成true,会考虑从左到右,从右到左双向的共现频率 .build();//构建模型类 glove.fit();//模型定型 double simD = glove.similarity("day", "night");//然后可以计算词的相似度了 log.info("Day/night similarity: " + simD); Collection<String> words = glove.wordsNearest("day", 10);//计算和day最相似的10个词 log.info("Nearest words to 'day': " + words); System.exit(0); }}
版权声明:本文为chencheng12077原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。