之前也写过word2vec词向量文本分类实现,不过那是基于Keras。
今天来写下tensoflow版的代码。
再来感受下它的魅力。
tensorflow比Keras更接近底层,可以更方便让我们理解Word2vector如何应用在文本分类中
简化版例子。
算例
第一步:导入包
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: yudengwu
# @Date : 2020/9/6
import tensorflow as tf
import numpy as np
第二步:数据
为了方便,我只列出啦其个样本,且样本为英文。如果是中文,那么代码里的sentences应该为分词并去除停用词后的数据。
本例子中样本有的长度为3,有的为2。对应现实生活中不同长度的文本。
如果是中文例子,则长度指的是(分词并去除停用词后)样本包含词语的个数。
labels为标签,简单2分类操作。
sentences = ["i love you","love you","he loves me", "she likes baseball", "i hate you","hate you","sorry for that", "this is awful"]
labels = [1,1,1,1,0,0,0,0] # 1 is good, 0 is not good.
第三步:获取词典
word_dict = {w: i+1 for i, w in enumerate(word_list)}
字典中i来说一般不加1,默认从0 开始 ,我这里加1。是因为我后面要为断文本填0操作,使各个文本长度一致,是填充的0和原始字典0区别开来,所有字典中的i+1。
word_list = " ".join(sentences).split()
word_list = list(set(word_list))
word_dict = {w: i+1 for i, w in enumerate(word_list)}#词典
print(word_dict)
vocab_size = len(word_dict)+1#词语个数
print(vocab_size)
word_dict:
{‘she’: 1, ‘for’: 2, ‘baseball’: 3, ‘that’: 4, ‘me’: 5, ‘loves’: 6, ‘likes’: 7, ‘hate’: 8, ‘this’: 9, ‘you’: 10, ‘i’: 11, ‘awful’: 12, ‘is’: 13, ‘sorry’: 14, ‘love’: 15, ‘he’: 16}
vocab_size:
16
vocab_size&