当前位置: 首页 > 工具软件 > Word2VEC_Java > 使用案例 >

java调用word2vec模型_word2vec使用過程(Java版)

谭曦
2023-12-01

這里只介紹如何使用,不介紹原理(想要了解原理的看這里)

1.下載Word2Vec(Java版地址)

2.根據自己情況准備語料庫(搜狗2012全網新聞數據)

3.處理語料庫。

以搜狗2012全網新聞數據為例:

(1)首先處理掉HTML標簽並轉為utf8編碼格式:cat news_tensite_xml.dat | iconv -f gb18030 -t utf-8 -c | grep "" > corpus.txt

(2)進行分詞處理,這里使用的ANSJ(jar包下載地址):public class Test {

public static final String TAG_START_CONTENT = "";

public static final String TAG_END_CONTENT = "";

public static void main(String[] args) {

String temp = null ;

BufferedReader reader = null;

PrintWriter pw = null;

System.out.println("開始分詞...");

try {

//分詞之前的文件路徑

File file = new File("C:/users/xxx/Desktop/xxx");

InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");

reader = new BufferedReader(read);

//分詞之后的文件路徑

pw = new PrintWriter("C:/users/xxx/Desktop/xxx");

long start = System.currentTimeMillis() ;

int allCount =0 ;

int termcnt = 0;

Set set = new HashSet();

while((temp=reader.readLine())!=null){

temp = temp.trim();

if (temp.startsWith(TAG_START_CONTENT)) {

int end = temp.indexOf(TAG_END_CONTENT);

String content = temp.substring(TAG_START_CONTENT.length(), end);

if (content.length() > 0) {

allCount += content.length() ;

List result = ToAnalysis.parse(content);

for (Term term: result) {

String item = term.getName().trim();

if (item.length() > 0) {

termcnt++;

pw.print(item.trim() + " ");

set.add(item);

}

}

pw.println();

}

}

}

long end = System.currentTimeMillis() ;

System.out.println("已完成!");

System.out.println("共" + termcnt + "個term," + set.size() + "個不同的詞,共 "

+allCount+" 個字符,每秒處理了:"+(allCount*1000.0/(end-start)));

} catch (IOException e) {

e.printStackTrace();

} finally {

if (null != reader) {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != pw) {

pw.close();

}

}

}

}

4.開始訓練

使用剛剛下載的Word2Vec,其中有一個Learn類,改一下里面的路徑,開始訓練就好。

時間可能比較長,另外,需要改一下分配給jvm的最大內存大小,不然會out of memory。

eclipse這樣修改:Run->Run Configurations->Arguments,在VM arguments里面添加-Xmx3072m。這里的3072m是分配給jvm的內存的大小,根據自己需要填寫數值就好。

這里有一份我訓練好的模型(使用搜狗2012全網新聞數據):

鏈接:http://pan.baidu.com/s/1geEyJnH 密碼:wbu7

5.最后就可以直接使用訓練出來的模型了:Word2VEC vec = new Word2VEC();

//訓練出來的模型的路徑

vec.loadJavaModel("C:/xxx/xxx");

String str = "哈哈";

System.out.println(vec.distance(str));

 类似资料: