让DeepLearning4j阅读小说并给出关联度最高的词

2024-04-06 12:38

本文主要是介绍让DeepLearning4j阅读小说并给出关联度最高的词,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

DeepLearning4j是一个java的神经网络框架,便于java程序员使用神经网络来完成一些机器学习工程。

不管什么机器学习框架,NLP是一个不能不谈的领域,DL4J也提供了nlp的相关实现。其中入门的例子就是从一大堆文字中找到最相关的词。

我们先来看看官方的demo,然后再模仿一个类似的程序,只不过是阅读中文的小说。

官方的demo叫Word2VecRawTextExample,我们直接新建一个java的maven项目,pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.tianyalei</groupId><artifactId>wolf_ml_mnist</artifactId><version>1.0-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><nd4j.version>1.0.0-beta</nd4j.version><dl4j.version>1.0.0-beta</dl4j.version><datavec.version>1.0.0-beta</datavec.version><logback.version>1.1.7</logback.version><scala.binary.version>2.10</scala.binary.version></properties><dependencies><!--神经网络的实现方法--><dependency><groupId>org.deeplearning4j</groupId><artifactId>deeplearning4j-core</artifactId><version>${dl4j.version}</version></dependency><!--ND4J库的CPU版本,驱动DL4J--><!--nd4j-cuda-9.1-platform,写成这个就是GPU--><dependency><groupId>org.nd4j</groupId><artifactId>nd4j-native-platform</artifactId><!--<artifactId>nd4j-cuda-9.1-platform</artifactId>--><version>${nd4j.version}</version></dependency><dependency><groupId>org.deeplearning4j</groupId><artifactId>deeplearning4j-nlp</artifactId><version>${dl4j.version}</version></dependency><dependency><groupId>org.deeplearning4j</groupId><artifactId>deeplearning4j-ui_2.11</artifactId><version>${dl4j.version}</version></dependency><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>${logback.version}</version></dependency><!--中文分词start--><!--<dependency><groupId>org.fnlp</groupId><artifactId>fnlp-core</artifactId><version>2.1-SNAPSHOT</version></dependency>--><dependency><groupId>net.sf.trove4j</groupId><artifactId>trove4j</artifactId><version>3.0.3</version></dependency><dependency><groupId>commons-cli</groupId><artifactId>commons-cli</artifactId><version>1.2</version></dependency><!--中文分词end--></dependencies>
</project>
package com.tianyalei.nlp;import org.deeplearning4j.models.word2vec.Word2Vec;
import org.deeplearning4j.text.sentenceiterator.BasicLineIterator;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.tokenization.tokenizer.preprocessor.CommonPreprocessor;
import org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;
import org.nd4j.linalg.io.ClassPathResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.Collection;/*** Created by agibsonccc on 10/9/14.** Neural net that processes text into wordvectors. See below url for an in-depth explanation.* https://deeplearning4j.org/word2vec.html*/
public class Word2VecRawTextExample {private static Logger log = LoggerFactory.getLogger(Word2VecRawTextExample.class);public static void main(String[] args) throws Exception {// Gets Path to Text fileString filePath = new ClassPathResource("raw_sentences.txt").getFile().getAbsolutePath();log.info("Load & Vectorize Sentences....");// Strip white space before and after for each lineSentenceIterator iter = new BasicLineIterator(filePath);// Split on white spaces in the line to get wordsTokenizerFactory t = new DefaultTokenizerFactory();/*CommonPreprocessor will apply the following regex to each token: [\d\.:,"'\(\)\[\]|/?!;]+So, effectively all numbers, punctuation symbols and some special symbols are stripped off.Additionally it forces lower case for all tokens.*/t.setTokenPreProcessor(new CommonPreprocessor());log.info("Building model....");Word2Vec vec = new Word2Vec.Builder()//是一个词在语料中必须出现的最少次数。本例中出现不到五次的词都不予学习。.minWordFrequency(5)//是网络在处理一批数据时允许更新系数的次数。迭代次数太少,网络可能来不及学习所有能学到的信息;迭代次数太多则会导致网络定型时间变长。.iterations(1)//指定词向量中的特征数量,与特征空间的维度数量相等。以500个特征值表示的词会成为一个500维空间中的点。.layerSize(100).seed(42).windowSize(5)//告知网络当前定型的是哪一批数据集.iterate(iter)//将当前一批的词输入网络.tokenizerFactory(t).build();log.info("Fitting Word2Vec model....");vec.fit();log.info("Writing word vectors to text file....");// Prints out the closest 10 words to "day". An example on what to do with these Word Vectors.log.info("Closest Words:");Collection<String> lst = vec.wordsNearestSum("day", 10);//Collection<String> lst = vec.wordsNearest(Arrays.asList("king", "woman"), Arrays.asList("queen"), 10);log.info("10 Words closest to 'day': {}", lst);}
}

这就是NLP的helloworld级的入门项目,目标是从给定的raw_sentences.txt中找到与day最相近的词,将资源放到resource中,运行该程序即可。

运行结果:

可以看到,day的最相近的词有week、night、year等,还算非常靠谱。至于原理呢,大家可以在文档里去搜索day这个词,看看它的附近的词和用法,然后再去搜索week、night等词的旁边的词和用法,就大概知道怎么回事了。

该文用的相关资源去我项目里找https://github.com/tianyaleixiaowu/wolf_ml_mnist

从代码的注释中可以看看基本的概念,下面我们来让它学习一下中文的小说,并给出最接近的词。

和英文自带空格分词不同,中文是额外需要一个中文分词器的,不然中文全是一句一句的,根本分不开。所以我们在让机器学习读中文前,需要先将中文句子分成一个个的词语。

中文分词器很多,论使用的简易程度和效果,还是复旦的NLP比较靠谱,https://github.com/FudanNLP/fnlp。

GitHub上面有文档,讲怎么使用的,这里我直接简单说一下,下载models里的三个.m文件,和libs里的fnlp-code.jar,将jar添加为工程的依赖lib即可。至于复旦nlp额外需要的两个jar,我已经放在pom.xml里了。

然后就可以使用fnlp来对文档进行分词了。我们选择的文档是天龙八部tlbb.txt,这是没分词时的样子。

分词的代码

package com.tianyalei.nlp.tlbb;import java.io.*;/*** 运行后将得到一个分词后的文档* @author wuweifeng wrote on 2018/6/29.*/
public class FenCi {private FudanTokenizer tokenizer = new FudanTokenizer();public void processFile() throws Exception {String filePath = this.getClass().getClassLoader().getResource("text/tlbb.txt").getPath();BufferedReader in = new BufferedReader(new FileReader(filePath));File outfile = new File("/Users/wuwf/project/tlbb_t.txt");if (outfile.exists()) {outfile.delete();}FileOutputStream fop = new FileOutputStream(outfile);// 构建FileOutputStream对象,文件不存在会自动新建String line = in.readLine();OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");while (line != null) {line = tokenizer.processSentence(line);writer.append(line);line = in.readLine();}in.close();writer.close(); // 关闭写入流,同时会把缓冲区内容写入文件fop.close(); // 关闭输出流,释放系统资源}public static void main(String[] args) throws Exception {new FenCi().processFile();}
}
package com.tianyalei.nlp.tlbb;import org.fnlp.ml.types.Dictionary;
import org.fnlp.nlp.cn.tag.CWSTagger;
import org.fnlp.nlp.corpus.StopWords;
import org.fnlp.util.exception.LoadModelException;import java.io.IOException;
import java.util.List;/*** @author wuweifeng wrote on 2018/6/29.*/
public class FudanTokenizer {private CWSTagger tag;private StopWords stopWords;public FudanTokenizer() {String path = this.getClass().getClassLoader().getResource("").getPath();System.out.println(path);try {tag = new CWSTagger(path + "models/seg.m");} catch (LoadModelException e) {e.printStackTrace();}}public String processSentence(String context) {return tag.tag(context);}public String processSentence(String sentence, boolean english) {if (english) {tag.setEnFilter(true);}return tag.tag(sentence);}public String processFile(String filename) {return tag.tagFile(filename);}/*** 设置分词词典*/public boolean setDictionary() {String dictPath = this.getClass().getClassLoader().getResource("models/dict.txt").getPath();Dictionary dict;try {dict = new Dictionary(dictPath);} catch (IOException e) {return false;}tag.setDictionary(dict);return true;}/*** 去除停用词*/public List<String> flitStopWords(String[] words) {try {return stopWords.phraseDel(words);} catch (Exception e) {e.printStackTrace();return null;}}}    

然后运行一下,过一会就得到了分词后的文档tlbb_t.txt,将分词后的拷贝到resource下,将来机器学的就是分词后的文档。

package com.tianyalei.nlp.tlbb;import org.deeplearning4j.models.embeddings.loader.WordVectorSerializer;
import org.deeplearning4j.models.word2vec.Word2Vec;
import org.deeplearning4j.text.sentenceiterator.BasicLineIterator;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.tokenization.tokenizer.preprocessor.CommonPreprocessor;
import org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;
import org.nd4j.linalg.io.ClassPathResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.File;
import java.io.IOException;
import java.util.Collection;/*** @author wuweifeng wrote on 2018/6/29.*/
public class Tlbb {private static Logger log = LoggerFactory.getLogger(Tlbb.class);public static void main(String[] args) throws IOException {String filePath = new ClassPathResource("text/tlbb_t.txt").getFile().getAbsolutePath();log.info("Load & Vectorize Sentences....");SentenceIterator iter = new BasicLineIterator(new File(filePath));TokenizerFactory t = new DefaultTokenizerFactory();t.setTokenPreProcessor(new CommonPreprocessor());log.info("Building model....");Word2Vec vec = new Word2Vec.Builder().minWordFrequency(5).iterations(1).layerSize(100).seed(42).windowSize(5).iterate(iter).tokenizerFactory(t).build();log.info("Fitting Word2Vec model....");vec.fit();log.info("Writing word vectors to text file....");// Write word vectors to filelog.info("Writing word vectors to text file....");WordVectorSerializer.writeWordVectors(vec, "tlbb_vectors.txt");WordVectorSerializer.writeFullModel(vec, "tlbb_model.txt");String[] names = {"萧峰", "乔峰", "段誉", "虚竹", "王语嫣", "阿紫", "阿朱", "木婉清"};log.info("Closest Words:");for (String name : names) {System.out.println(name + ">>>>>>");Collection<String> lst = vec.wordsNearest(name, 10);System.out.println(lst);}}}

代码和之前的demo区别不大,运行后,就能看到这几个人的关联度最高的词了。



参考篇:https://blog.csdn.net/a398942089/article/details/51970691

这篇关于让DeepLearning4j阅读小说并给出关联度最高的词的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/879907

相关文章

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

论文阅读笔记: Segment Anything

文章目录 Segment Anything摘要引言任务模型数据引擎数据集负责任的人工智能 Segment Anything Model图像编码器提示编码器mask解码器解决歧义损失和训练 Segment Anything 论文地址: https://arxiv.org/abs/2304.02643 代码地址:https://github.com/facebookresear

软件架构模式:5 分钟阅读

原文: https://orkhanscience.medium.com/software-architecture-patterns-5-mins-read-e9e3c8eb47d2 软件架构模式:5 分钟阅读 当有人潜入软件工程世界时,有一天他需要学习软件架构模式的基础知识。当我刚接触编码时,我不知道从哪里获得简要介绍现有架构模式的资源,这样它就不会太详细和混乱,而是非常抽象和易

【阅读文献】一个使用大语言模型的端到端语音概要

摘要 ssum框架(Speech Summarization)为了 从说话人的语音提出对应的文本二题出。 ssum面临的挑战: 控制长语音的输入捕捉 the intricate cross-mdoel mapping 在长语音输入和短文本之间。 ssum端到端模型框架 使用 Q-Former 作为 语音和文本的中介连接 ,并且使用LLMs去从语音特征正确地产生文本。 采取 multi-st

Tensorflow lstm实现的小说撰写预测

最近,在研究深度学习方面的知识,结合Tensorflow,完成了基于lstm的小说预测程序demo。 lstm是改进的RNN,具有长期记忆功能,相对于RNN,增加了多个门来控制输入与输出。原理方面的知识网上很多,在此,我只是将我短暂学习的tensorflow写一个预测小说的demo,如果有错误,还望大家指出。 1、将小说进行分词,去除空格,建立词汇表与id的字典,生成初始输入模型的x与y d

你读文献的方式可能错了!掌握这些技巧,让阅读事半功倍!

我是娜姐 @迪娜学姐 ,一个SCI医学期刊编辑,探索用AI工具提效论文写作和发表。 科研新手如何精读一篇论文? 很多科研新手,一上来就疯狂下载几十上百篇文献。囫囵吞枣看完了,还是什么都不知道,大脑一片空白。究竟该如何读文献收获最大? 大佬说,要积极阅读、频繁阅读。 什么是积极阅读? 相比被动阅读,积极阅读是指在阅读之前准备好问题、设置阅读目标、保持批判性,收获更多、进步更大的一种阅读

FPGA随记——小说 可综合和不可综合

当然我在网络上找到了些可综合和不可综合的解释 感觉也很有参考价值: https://wenda.so.com/q/1378362174074040 综合就是把你写的rtl代码转换成对应的实际电路。 比如你写代码assign a=b&c; EDA综合工具就会去元件库里拿一个二输入与门出来,然后输入端分别接上b和c,输出端接上a 假如你写了很多这样的语句 assign a=b&c; assig

爬取豪ru老师刘艳小说

网址准备 可自行搜索,发现在电脑端无法获取内容,用浏览器仿手机的功能实现 抓包分析,发现网址非常简单,没有任何的反爬措施 可以得到返回的页面,而且字体也没用常见的反爬措施 接下来就分析各个章节的属性就大功告成了 爬取到了 警告,技术不可用于传播黄色

一键部署Phi 3.5 mini+vision!多模态阅读基准数据集MRR-Benchmark上线,含550个问答对

小模型又又又卷起来了!微软开源三连发!一口气发布了 Phi 3.5 针对不同任务的 3 个模型,并在多个基准上超越了其他同类模型。 其中 Phi-3.5-mini-instruct 专为内存或算力受限的设备推出,小参数也能展现出强大的推理能力,代码生成、多语言理解等任务信手拈来。而 Phi-3.5-vision-instruct 则是多模态领域的翘楚,能同时处理文本和视觉信息,图像理解、视频摘要

深入理解计算机系统阅读笔记-第四章

第四章 处理器体系结构 一个处理器支持的指令和指令的字节级编码称为它的ISA(instruction-set architecture,指令集体系结构)。不同家族处理器有不同的ISA。ISA在编译器编写者和处理器设计人员之间提供了一个概念抽象层,编译器编写者只需要知道允许哪些指令,以及他们是如何编码的;而处理器设计者,必须建造出执行这些指令的处理器。 ISA模型看上去是顺序执行的,实际上同时处