NLP——Word2Vec

2022年5月25日00:36:03 发表评论 488 views

看完了,感觉挺有意思,基本分析如下:
先读取,分词,去掉停用词,形成二维列表,交给Word2Vec去计算
最后调用相关函数,虽然不甚理想,但是比起之前的测试准确度提高到了70%左右
先上代码:

#-*- coding:utf-8 -*-
import time
import pandas as pd
import jieba
from gensim.models import  Word2Vec
train_file = r'D:\win7远程\NLP 大数据人工智能自然语言处理\0725-基于FastText的中文分类\sohu_train.txt'
test_file= r'D:\win7远程\NLP 大数据人工智能自然语言处理\0725-基于FastText的中文分类\sohu_test.txt'
stopwords= r'D:\win7远程\NLP 大数据人工智能自然语言处理\0725-基于FastText的中文分类\stop_words.txt'
def processData():
    train_pd = pd.read_csv(train_file,sep='\t',header = None)
    test_pd= pd.read_csv(test_file,sep='\t',header = None)
    train_pd = train_pd.head(5000)
    test_pd= train_pd.head(5000)
    train_pd.columns = ['分类',"文章"]
    # 去除停用词:
    stopwords_list = [k.strip() for k in open(stopwords,encoding='utf-8').readlines()
                      if k.strip() !='']
    wordscuts_list = []  # 声明一个放停用词的list
    time0 = time.time()
    i  = 0
    for article in train_pd['文章']:
        wordsCut= [k for k in  jieba.cut(article) if k not in stopwords_list]
        wordscuts_list.append(wordsCut)
        i+=1
        if i%10==0:
            print('处理了%d篇文章,总共用时%.2f'%(i,time.time()-time0))
    return wordscuts_list


if __name__ == '__main__':
    # 数据预处理
    wordcutslist = processData()
    # 生成词向量
    print("开始执行Word2Vec")
    word2vec = Word2Vec(wordcutslist,sg=0,window=5,size=192,min_count=10,workers=5)
    # 相似度计算:
    print('相似度',word2vec.wv.most_similar('赤壁'))
    # 机器学习 LR做分类——特征工程

    pass




调试结果:

NLP——Word2VecNLP——Word2Vec其它:

 

word2vec

(1)word2vec:将 one-hot-vector 映射(embedding)低密度 连续的稠密向量。

神经网络(3层)

输入层:One-hot-vector

隐含层:线性单元(输入层计算)

输出层:softmax函数---(可以将数值归一化 0-1之间。每个分类被取到的概率。

0.1 0.3 0.4 0.05,0.15)

(2)CBOW(Continuous Bag of Words)& Skip-Gram

(3) a、安装 Gensim

pip install gensim(没有做 cextension扩展)

conda install -c conda-forge gensim(建议 -c 指channels)

b、直接调用

from gensim.models import Word2Vec

model=Word2Vec(sentences,sg=0,size=,window,min_count,workers)

sentences---预处理完之后的语料。(分句 分词)

sg--0:CBOW 1:SKip-gram

size:特征向量的维度,默认为100,推荐值为 几十-几百。(小坑,后来改成了vector-size)

window:当前词与预测词在一个句子中的最大距离。

alpha:学习速率 0-1之间。

min_count:词频的限制,最小出现次数。

workers:线程数

(4)搜狐新闻分类。

a\数据预处理

b\ word2vec模型声明--转为词向量

c、机器学习--特征工程、、、深度学习  不需要 声明网络的结构和参数

d\训练和测试(评价指标 准确度、召回值、精确度、F1-Score)

男人-女人+男人=男人

男人-女人+王=国君

5、doc2vec

(1)2014年提出的,word2vec扩展。---句子 段落和文章之间的相似性。

(2)DM:对应word2vec CBOW增加了文档的向量。主要是根据上下文预测上下文的其他单词。

DBOW:对应于 word2vec的 skip-gram,通过断乱的向量 预测其他单词。

Huffman树  可以提高计算速率。huffman编码。

(3)Doc2vec=(dm=0,size,window,min_count,workers)

dm=0 表示 DBOW dm=1表示DM算法。

 

 

 

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: