文章目录
Word2Vec应用案例以及Fasttext
一、文本情感分析(英文&&中文)
1.基本的文本预处理技术 (网页解析,文本抽取,正则表达式等)
#下载停用词
nltk.download('stopwords')
eng_stopwords = set(stopwords.words('english'))
# 清洗数据
def clean_text(text):
#去除标签
text = BeautifulSoup(text, 'html.parser').get_text()
#去除标点
text = re.sub(r'[^a-zA-Z]', ' ', text)
#分词,变成小写形式
words = text.lower().split()
#去除停用词
words = [w for w in words if w not in eng_stopwords]
return ' '.join(words)
2.word2vec词向量编码与机器学习建模情感分析
print('Training model...')
#初始化model
model =gensim.models.word2vec.Word2Vec(sentences,workers=num_workers,
size=num_features,min_count=min_word_count,
window=context,sample=downsampling)
# If you don't plan to train the model any further, calling
# init_sims will make the model much more memory-efficient.
model.init_sims(replace=True)
# It can be helpful to create a meaningful model name and
# save the model for later use. You can load it later using Word2Vec.load()
model.save(os.path.join('.', 'models', model_name))
print(model.doesnt_match("man woman child kitchen".split()))
print(model.doesnt_match('france england germany berlin'.split()))
def to_review_vector(review):
words = clean_text(review, remove_stopwords=True)
array = np.array([model[w] for w in words if w in model])
return pd.Series(array.mean(axis=0))
二、Fasttext
1.模型意义
Word2Vec:
I like dogs
输入是 I dogs 输出是like
由I dogs来看输出like的几率有多大
Fasttext:
如果有这样一个句子I like dogs,情感分类的(正面为1)
将这个1塞进这个句子里面,由I like dogs 来判断出现1的可能性
类似就是把label塞进去,看label输出是多少
随便塞进去在哪里都可以,但是整个数据集里面,要在同样的位置(前面或者后面)
因为在word2vec模型中,就认为语料的语境就这样,比如like 后面就是1
2.模型改进
(1)加入N-gram
N-gram:就是把n个token合在一起
Word2Vec用的bag of words,就是把出现的单词给它表上一个index,I 标记为1,you标 记为2,love标记为3,但是会出现一个问题,前后的位置变化,句子意思就变了
Bi-Gram:量级比词袋大,但是可以保证句子的前后关系
N-gram的tokens就特别特别多了
(2)kernel Trick与Hashing trick
但是hashing trick遇到高维的时候会有很多问题
用符号解决冲突问题
fasttext中,就是用hashing trick将tokens变为一个小维度
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kBrfSxA0-1642411827236)(/Users/duanyuqing/Library/Application Support/typora-user-images/image-20220117171506933.png)]
(3)哈夫曼树
简单的softmax变为层次的softmax
softmax就是一个one-hot编码:eg概率是[0.1,0.2,0.3,0.3,0.1],取出最高概率的那个词
层次softmax,就是将概率按照从大到小的顺序连接起来
输出结果不再针对每个单词,而是针对每个边,p(w1)=p1*p2*p3
时间复杂度O(K),如果用树形结构就是O(logK)
树怎么编:深度搜索,看应该用哪个单词
霍夫曼树
意义:重的东西放在上面,用的几率大
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FZD7hRZP-1642411827237)(/Users/duanyuqing/Library/Application Support/typora-user-images/image-20220117172450562.png)]
比如:有KNGIHE个节点,分别有自己的权值425137
从小到大进行排列:I是最小的,因为权值就是有1,N是次小的,权值是2,E是最大的,权值为7
只要算出第一个编码是0还是1就好
模型用途:专注文本分类
提速:应用了Hash trick、霍夫曼编码树