一、Work2Vec
(1)独热编码one-hot
假设有变量Word_size,可以理解为,我们初始设定可能有读诵好个词语在一篇文章中(一般通过统计得来)。
具体的形式如下:
重庆[1,0,0,0,0……0]
成都[0,1,0,0,0……0]
北京[0,0,1,0,0……0]
这里也可以将one-hot理解成一种为每个不同的词设定index的过程。
(2)Word2vec训练过程
假设语料信息为:今天天气真好。通过分词处理后得到结果:今天/天气/真好。
先对三个词进行one-hot编码。这里假设Word_size变量为1000。对于今天这个词,它的编码可以为[1,0,0,0……]它是一个1x1000维的向量。
Word2vec的主要的作用就是减少了词向量的维度,同时解决了one-hot情况下向量稀疏度过大的问题(0太多了)。所以将得到的1x1000的向量经过一个1000x50的未知参数矩阵w1后得到1x50维度大小的矩阵,这样就缩小了原本向量的大小。也可以看出,这里的操作实际上等于取出了未知向量中的第一行数据。对一篇语料中所有的词都做上述处理便得到了所有词的词向量。
然后将1x50的向量通过一个50x1000的矩阵w2重新得到1x1000的矩阵,再经过softmax后与目标词汇进行loss计算,通过loss更新w1,w2矩阵。(这里是根据Skip-grow模型介绍的,即已知一个词汇,去计算它上下文的词)
二、数据预处理
(1)载入,清洗,分词
eng_stopwords = 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)
df = pd.read_csv('data/unlabeledTrainData.tsv', sep='\t', escapechar='\\')
df['clean_review'] = df.review.apply(clean_text)
sentences = df['clean_review']
print(sentences[0])
(2)将数据变成list的形式
sentences_list = []
for line in sentences:
sentences_list.append(nltk.word_tokenize(line))
print(sentences_list)
将上述数据变成下面这样的list
三、测试
num_features = 300
min_word_count = 40
num_workes =4
context = 10
model_name = '{}features_{}minwords_{}context.model'.format(num_features,min_word_count,context)
from gensim.models.word2vec import Word2Vec
model = Word2Vec(sentences_list,workers=num_workes,vector_size=num_features,min_count=min_word_count,window=context)
model.init_sims(replace=True)
model.save(os.path.join('models',model_name))
print(model.wv.doesnt_match(['man','woman','child','kitchen']))
print(model.wv.most_similar("boy"))
对Word2Vec的参数进行分析:
sentences:语料(列表或者从文件读出)
vector_size:词向量的维度
window:词向量上下文最大距离,window越大,则和某一词较远的词也会产生上下文关系。默认值为5
sg:即我们的word2vec两个模型的选择了。如果是0, 则是CBOW模型;是1则是Skip-Gram模型;默认是0即CBOW模型。
min_count:需要计算词向量的最小词频。这个值可以去掉一些很生僻的低频词,默认是5。如果是小语料,可以调低这个值。
还有一些其他的设置,主要用这几个。
四、对影评数据进行测试
仅用词袋
使用W2V,在上述的代码中,我们仅仅是使用语料将每个词的词向量表示出来,而我们最终的目的是得到影评结果,也就是通过分析一句话,所以,我们需要获得一句话的向量,这里简单的将一句话所有词的词向量叠加后求均值,作为一句话的句向量处理。
def to_review_vector(review):
global word_vec
review = clean_text(review)
word_vec = np.zeros((1,300))
for word in review:
if word in list(model.wv.key_to_index):
word_vec += np.array([model.wv[word]])
return pd.Series(word_vec.mean(axis = 0))
train_data_features = df.review.apply(to_review_vector)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train,y_test = train_test_split(train_data_features,df.sentiment,test_size=0.2,random_state=0)
LR_model = LogisticRegression()
LR_model = LR_model.fit(X_train, y_train)
y_pred = LR_model.predict(X_test)
cnf_matrix = confusion_matrix(y_test, y_pred)
print("Recall metric in the testing dataset", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
print("accuracy metric in the testing dataset", (cnf_matrix[1,1]+cnf_matrix[0,0])/(cnf_matrix[0,0]+cnf_matrix[1,1]+cnf_matrix[1,0]+cnf_matrix[0,1]))