[自然语言处理] word2vec自己训练词向量
word2vec代码(中文英文都可以训练)
import collections
import math
import random
import zipfile
import numpy as np
from six.moves import xrange
import tensorflow as tf
def read_data(filename):
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
words = read_data('word_embeddings/msr_unlabel.zip')
print('Data size', len(words))
vocabulary_size = 7000
def build_dataset(words, vocabulary_size):
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
if word in dictionary:
index = dictionary[word]
else:
index = 0 # dictionary['UNK']
unk_count += 1
data.append(index)
count[0][1] = unk_count
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reverse_dictionary
data, count, dictionary, reverse_dictionary = build_dataset(words, vocabulary_size)
# 删除words引用
del words
#****************************** 开始 ********************************************
data_index = 0
# Step 3: Function to generate a training batch for the skip-gram model.
def generate_batch(batch_size, num_skips, skip_window):
global data_index
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
buffer = collections.deque(maxlen=span)
for _ in range(span):
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
# 获取batch和labels
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [skip_window]
# 循环2次,一个目标单词对应两个上下文单词
for j in range(num_skips):
while target in targets_to_avoid:
# 可能先拿到前面的单词也可能先拿到后面的单词
target = random.randint(0, span - 1)
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
# Backtrack a little bit to avoid skipping words in the end of a batch
# 回溯3个词。因为执行完一个batch的操作之后,data_index会往右多偏移span个位置
data_index = (data_index + len(data) - span) % len(data)
return batch, labels
batch_size = 128
embedding_size = 128 # 词向量维度Dimension of the embedding vector.
skip_window = 1 # How many words to consider left and right.
num_skips = 2 # How many times to reuse an input to generate a label.
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
# 从0-100抽取16个整数,无放回抽样
valid_examples = np.random.choice(valid_window, valid_size, replace=False)
# 负采样样本数
num_sampled = 64 # Number of negative examples to sample.
# Step 4: Build and train a skip-gram model.
graph = tf.Graph()
with graph.as_default():
# Input data.
with tf.variable_scope('input'):
train_inputs = tf.placeholder(tf.int32, shape=[batch_size],name='train_inputs')
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1],name='train_labels')
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
# Ops and variables pinned to the CPU because of missing GPU implementation
# with tf.device('/cpu:0'):
# 词向量----------------------5万个词就是5万行,定义128维特征为128列************88
# Look up embeddings for inputs.
with tf.variable_scope('embedding'):
embeddings = tf.Variable(
tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0),name='embedding')
# embedding_lookup(params,ids)其实就是按照ids顺序返回params中的第ids行
# 比如说,ids=[1,7,4],就是返回params中第1,7,4行。返回结果为由params的1,7,4行组成的tensor
# 提取要训练的词-----------------------------------不是每次迭代5万个词,抽样迭代按批次就是按词的编号,把词的编号传进去
embed = tf.nn.embedding_lookup(embeddings, train_inputs)
with tf.variable_scope('net'):
# Construct the variables for the noise-contrastive estimation(NCE) loss
nce_weights = tf.Variable(
tf.truncated_normal([vocabulary_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
# Compute the average NCE loss for the batch.
with tf.variable_scope('loss'):
loss = tf.reduce_mean(
tf.nn.nce_loss(weights=nce_weights,
biases=nce_biases,
labels=train_labels,
inputs=embed,
num_sampled=num_sampled,
num_classes=vocabulary_size),name='loss')
tf.summary.scalar('ece_loss',loss)
# Construct the SGD optimizer using a learning rate of 1.0.
optimizer = tf.train.GradientDescentOptimizer(1).minimize(loss)
# Compute the cosine similarity between minibatch examples and all embeddings.
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
# 抽取一些常用词来测试余弦相似度
# 如果输入的是64,那么对应的embedding是normalized_embeddings第64行的vector
valid_embeddings = tf.nn.embedding_lookup(
normalized_embeddings, valid_dataset)
# valid_size == 16
# [16,1] * [1*50000] = [16,50000]
similarity = tf.matmul(
valid_embeddings, normalized_embeddings, transpose_b=True)
# Add variable initializer.
init = tf.global_variables_initializer()
num_steps = 20000
final_embeddings = []
# Step 5: 开始训练,启动session
with tf.Session(graph=graph) as session:
print("启动session")
merge = tf.summary.merge_all()
init.run()
train_writer = tf.summary.FileWriter('log')
average_loss = 0
for step in xrange(num_steps):
batch_inputs, batch_labels = generate_batch(
batch_size, num_skips, skip_window)
feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}
# We perform one update step by evaluating the optimizer op (including it
# in the list of returned values for session.run()
_, loss_val, summary_train = session.run([optimizer, loss, merge], feed_dict=feed_dict)
average_loss += loss_val
train_writer.add_summary(summary_train, step)
# print("batch_inputs:%s batch_labels:%s" % (batch_inputs,batch_labels))
# batch_inputs矩阵 成对的标号 batch_labels 换行的标号 ??
# 每2000次迭代,打印损失值
if step % 2000 == 0:
if step > 0:
average_loss /= 2000
# The average loss is an estimate of the loss over the last 2000 batches.
print("Average loss at step ", step, ": ", average_loss)
average_loss = 0
# 每2000次迭代,随机抽一个词,并打印周围相似词
if step % 2000 == 0:
sim = similarity.eval()
# 计算验证集的余弦相似度最高的词
for i in xrange(valid_size):
# 根据id拿到对应单词
valid_word = reverse_dictionary[valid_examples[i]]
top_k = 8 # number of nearest neighbors
# 从大到小排序,排除自己本身,取前top_k个值
nearest = (-sim[i, :]).argsort()[1:top_k + 1]
log_str = "Nearest to %s:" % valid_word
for k in xrange(top_k):
close_word = reverse_dictionary[nearest[k]]
log_str = "%s %s," % (log_str, close_word)
print(log_str)
# 训练结束得到的全部词的词向量矩阵
final_embeddings = normalized_embeddings.eval()
# 常规记录日志文件
writer = tf.summary.FileWriter("log", session.graph)
# 保存词对应词向量的文件
e = open('word_embeddings/msrp_embeddings','w', encoding='utf-8')
e.write(str(vocabulary_size)+" "+str(embedding_size)+'\n')
for index in range(len(final_embeddings)):
embedding_list = final_embeddings[index].tolist()
# print(embedding_list)
embedding_str = " ".join('%s' % id for id in embedding_list)
e.write(str(reverse_dictionary[index])+" "+str(embedding_str)+'\n')
e.close()
# Step 6: Visualize the embeddings.降维画图
def plot_with_labels(low_dim_embs, labels,filename='word_embeddings/msrp_embeddings.png'):
assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
# 设置图片大小
plt.figure(figsize=(15, 15)) # in inches
for i, label in enumerate(labels):
x, y = low_dim_embs[i, :]
plt.scatter(x, y)
plt.annotate(label,
xy=(x, y),
xytext=(5, 2),
textcoords='offset points',
fontproperties = 'SimHei',
fontsize = 14,
ha='right',
va='bottom')
plt.savefig(filename)
try:
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000, method='exact') # mac:method='exact'
# 画500个点
plot_only = 300
#每个词reverse_dictionary对应每个词向量final_embeddings
low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :])
labels = [reverse_dictionary[i] for i in xrange(plot_only)]
plot_with_labels(low_dim_embs, labels)
except ImportError:
print("Please install sklearn, matplotlib, and scipy to visualize embeddings.")
训练过程:
训练结果:
得到7000个词的128维的词向量表达(输出词的个数,维度,训练次数都可以自己根据需求设置)
词向量之间的多维空间距离,压平到二维平面。(达到距离近的词语义相近的效果)
训练次数增多效果会好些,但训练时间会长。
为了提升词嵌入的效果,也可使用预训练好的词向量,详见本篇博客:
预训练词向量中文维基百科,英文斯坦福glove预训练的词向量下载
https://blog.****.net/sinat_41144773/article/details/89875130
结束。