参考链接
https://www.jianshu.com/p/8c04344f2144
基本含义
词向量:单词的数字化表示。
例如:我们 = [1,2,3,4,2,1]
为什么要生成词向量?
文本计算机是无法构建函数的,文本转换的词向量可以。
生成方法
gensim库
分词->训练->调用模型
# 数据集是我随便找的一篇小说
import jieba
from gensim.models import word2vec
# 数据预处理
def load_train_data(filename):
# 数据预处理
sentences=[]
with open(filename, 'r', encoding='utf-8') as reader:
for line in reader:
line = line.strip()
if len(line) >= 10:
sentences.append(line)
return sentences
# 使用结巴分词
def segment(sentences):
words=[]
for sentence in sentences:
# word=pseg.cut(sentence) # 带分词的词性
word=jieba.cut(sentence) # 只是分词,不带词性,分完词之后,使用一个list装起来
result=''
for w in word:
result+=' '+w
words.append(result)
# 读取每一行文本,将所有的文本写
with open('F:\\python\\NLPBase\\data\\test.txt','a',encoding='utf-8') as fw:
for result in words:
fw.write(result)
pass
fw.close()
return words
# 生成word2vec模型,生成词向量
def word2vect(filepath):
sentences = word2vec.LineSentence(filepath)
model = word2vec.Word2Vec(sentences, hs=1, min_count=1, window=3, vector_size=10)
model.save('model') # 保存模型
#======================================
# 加载数据集
sentences=load_train_data('F:\\python\\NLPBase\\data\\dataset.txt')
# 分词
words=segment(sentences)
#训练
word2vect('F:\\python\\NLPBase\\data\\test.txt')
model = word2vec.Word2Vec.load('model') # 加载模型
# 找出一个词向量最近的词集合
for val in model.wv.similar_by_word("南方", topn=10):
print(val[0], val[1])
pass
Bert
加载bert分词器->加载bert模型->分词->将token转为vocabulary索引->训练->生成词向量
import torch
from pytorch_pretrained_bert import BertModel, BertTokenizer
# 注意这个bert的配置文件可以从网上下载,也可以直接加载网上的,我这里是直接加载网上的,如果你下载了这些配置文件到本地,则就直接填写路径就可以了
# 加载bert的分词器
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# 加载bert模型,这个路径文件夹下有bert_config.json配置文件和model.bin模型权重文件
bert = BertModel.from_pretrained('bert-base-uncased')
# 分词
s = "I'm not sure, this can work, lol -.-"
tokens = tokenizer.tokenize(s)
# "i\\'\\m\\not\\sure\\,\\this\\can\\work\\,\\lo\\##l\\-\\.\\-"
# 将token转为vocabulary索引
ids = torch.tensor([tokenizer.convert_tokens_to_ids(tokens)])
# 放到bert模型中训练
result = bert(ids, output_all_encoded_layers=True)
print(result)