(1)首先準備好數據,這是未標記的數據形式。
(2)stopword 的數據
然後根據數據,設計代碼。
word2vec訓練詞向量
import os
import re
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import nltk.data
#nltk.download()
#from nltk.corpus import stopwords
from gensim.models.word2vec import Word2Vec
#加載數據
def load_dataset(name, nrows=None):
datasets = {
'unlabeled_train': 'unlabeledTrainData.tsv',
'labeled_train': 'labeledTrainData.tsv',
'test': 'testData.tsv'
}
if name not in datasets:
raise ValueError(name)
data_file = os.path.join('..', 'data', datasets[name])
df = pd.read_csv(data_file, sep='\t', escapechar='\\', nrows=nrows)
print('Number of reviews: {}'.format(len(df)))
return df
df = load_dataset('unlabeled_train')
df.head()
數據的預處理
#留了個候選,可以去除停用詞,也可以不去除停用詞。
#eng_stopwords = set(stopwords.words('english'))
eng_stopwords = {}.fromkeys([ line.rstrip() for line in open('../stopwords.txt')])
#定義清理數據的信息。
def clean_text(text, remove_stopwords=False):
text = BeautifulSoup(text, 'html.parser').get_text()
text = re.sub(r'[^a-zA-Z]', ' ', text)
words = text.lower().split()
if remove_stopwords:
words = [w for w in words if w not in eng_stopwords]
return words
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
#每去調用一次split——sentences就輸出一下。
def print_call_counts(f):
n = 0
def wrapped(*args, **kwargs):
nonlocal n
n += 1
if n % 1000 == 1:
print('method {} called {} times'.format(f.__name__, n))
return f(*args, **kwargs)
return wrapped
@print_call_counts
def split_sentences(review):
raw_sentences = tokenizer.tokenize(review.strip())
sentences = [clean_text(s) for s in raw_sentences if s]
return sentences
time sentences = sum(df.review.apply(split_sentences), [])
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# 設定詞向量訓練的參數
num_features = 300 # Word vector dimensionality,建議300,或者500
min_word_count = 40 # Minimum word count 至少出現40ci
num_workers = 4 # Number of threads to run in parallel,線程
context = 10 # Context window size 上下文,窗口大小
downsampling = 1e-3 # Downsample setting for frequent words gensuim,要用的,下采樣的。
# nnlm 有投射層,4個窗口,用前3個預測第四個,有10W個詞庫,,三個 one-hot, 就是 1*10w
# 下一次,投影層。初始化權重,稠密向量。
# C=300*10W,C與one-hot,相乘。變成300*1,三個加起來,就變成了 900*1
# Hidden layer :900*500。900*1,變成了500*1,也有Wx+b 最後10W的維度。
#
# Cbow(連續詞庫)
# 用 我喜歡 機器學習
# 預測 學習
# 我喜歡機器學習,就是四個詞向量。
# 直接求和,來預測詞的概率。
# Window就是 滑動窗口。。滑動窗口開着,把所有爲4 的窗口 掃描出來。
# Min_word=40: 出現次數至少 40次。
#
# Toma模型:
# 學習,來預測: 我喜歡 機器學習。
model_name = '{}features_{}minwords_{}context.model'.format(num_features, min_word_count, context)
print('Training model...')
#初始化
model = 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()))
print(model.most_similar("man"))#關聯度最高的。
最後生成了一個 40多兆的數據模型
數據輸出的結果: