使用Tensorflow构建一个性能超差的word2vec
使用Tensorflow构建一个性能超差的word2vec
https://www.jianshu.com/p/25287d969a30
首先是对word2vec的原理(只针对:https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/examples/tutorials/word2vec/word2vec_basic.py的实现)的一个直觉层面的理解:
word2vec第一步随机生成每个单词的embedding,存到一个变量池里。如果你的词汇表长度是vocabulary_size(也就是你一共就研究这么几个单词,别的单词都归到unknown), 而对每个单词,你想用embedding_size维的向量来表示的话,那这个变量池自然是一个有vocabulary_size行,embedding_size列的矩阵啦。
然后就是给每个单词打标签,如果是Skip-gram Model的话,单词w的标签,就是出现在它前面的(紧挨着)单词(的词汇表id),或者是出现在他后面的单词。对,一个单词会有两个标签(参数不一样的话,label还会更多)。也就是一张图片既是猫,又是狗。似乎有点矛盾,但计算机会用数学的方法消化掉这种矛盾。
现在输入,输出,就明了了,输入是一个单词对应的embedding变量池中相应的一行,输出是它对应的label(label不止一个的话,就多次输入输出)。
如果你的embedding_size是128的话,那你的模型按理说应该是128进1出的一个模型。
但是,跟识别数字一样,对于输出,你不能用0表示0,用1表示1,
你得用【1,0,0,...】这个onehot的向量表示0,1的话类似
所以,你的输出不是1维的,而是你要分几类就是几维的。数字识别是分10类,所以y是10维的,word2vec要分的类和你的词汇表数量一样多,所以y是vocabulary_size维(以5000为例)的(onehot形式)。
恩,你就是要训练一个128进5000出的分类器。在不断训练的过程中,通过梯度下降,不仅更新分类器的参数,还要更新embedding变量池中的每一个数。训练结束后,我们反而并不太关心这个分类器,而是更希望得到性能更好的embedding变量池。
所以代码的话:
'''
Created on 2017-6-19
@author: Administrator
'''
import collections
import math
import os
import numpy as np
import tensorflow as tf
import random
path="E:\\NLPdata\\"
filename = "text8"
with open(path+filename) as f:
data=tf.compat.as_str(f.read()).split()
words=data
print("data size:"+str(len(words)))
vocabulary_size=5000
count=[['UNK',-1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
print(count[:5])
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
unk_count+=1
data.append(index)
count[0][1]=unk_count
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])
data_index = 0
def one_hot(index,ds):
oh=np.zeros(ds)
oh[index]=1
return oh
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, vocabulary_size), 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)
for i in range(batch_size // num_skips):
target = skip_window # target label at the center of the buffer
targets_to_avoid = [ skip_window ]
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] = one_hot(buffer[target],vocabulary_size)
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
return batch, labels
print('data:', [reverse_dictionary[di] for di in data[:8]])
for num_skips, skip_window in [(2, 1), (4, 2)]:
data_index = 0
batch, labels = generate_batch(batch_size=8, num_skips=num_skips, skip_window=skip_window)
print('\nwith num_skips = %d and skip_window = %d:' % (num_skips, skip_window))
print(' batch:', [reverse_dictionary[bi] for bi in batch])
print(' labels:',labels)
# batch_size = 128
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.
# We pick a random validation set to sample nearest neighbors. here we limit the
# validation samples to the words that have a low numeric ID, which by
# construction are also the most frequent.
valid_size = 16 # Random set of words to evaluate similarity on.
valid_window = 100 # Only pick dev samples in the head of the distribution.
valid_examples = np.array(random.sample(range(valid_window), valid_size))
# num_sampled = 64 # Number of negative examples to sample.
graph = tf.Graph()
with graph.as_default(), tf.device('/cpu:0'):
train_dataset = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.float32, shape=[batch_size, vocabulary_size])
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
#softmax_weights = tf.Variable(tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size)))
#softmax_biases = tf.Variable(tf.zeros([vocabulary_size]))
W = tf.Variable(tf.zeros([embedding_size, vocabulary_size]))
b = tf.Variable(tf.zeros([vocabulary_size]))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
y=tf.nn.softmax(tf.matmul(embed,W)+b)
loss = tf.reduce_mean(-tf.reduce_sum(train_labels * tf.log(y), reduction_indices=[1]))
optimizer = tf.train.AdagradOptimizer(1.0).minimize(loss)
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
valid_embeddings = tf.nn.embedding_lookup(normalized_embeddings, valid_dataset)
similarity = tf.matmul(valid_embeddings, tf.transpose(normalized_embeddings))
num_steps = 100001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().run()
print('Initialized')
average_loss = 0
for step in range(num_steps):
batch_data, batch_labels = generate_batch(
batch_size, num_skips, skip_window)
feed_dict = {train_dataset : batch_data, train_labels : batch_labels}
_, l = session.run([optimizer, loss], feed_dict=feed_dict)
average_loss += l
if step % 2000 == 0:
if step > 0:
average_loss = average_loss / 2000
# The average loss is an estimate of the loss over the last 2000 batches.
print('Average loss at step %d: %f' % (step, average_loss))
average_loss = 0
# note that this is expensive (~20% slowdown if computed every 500 steps)
if step % 10000 == 0:
sim = similarity.eval()
for i in range(valid_size):
valid_word = reverse_dictionary[valid_examples[i]]
top_k = 8 # number of nearest neighbors
nearest = (-sim[i, :]).argsort()[1:top_k+1]
log = 'Nearest to %s:' % valid_word
for k in range(top_k):
close_word = reverse_dictionary[nearest[k]]
log = '%s %s,' % (log, close_word)
print(log)
final_embeddings = normalized_embeddings.eval()
其实就是基于原来的代码改的,主要改动包括,
把词汇表降到5000,降低y的维度
label直接变成one-hot
把训练模型直接改成softmax分类器,更容易看懂,
loss函数就是之前的交叉熵,是不是很亲切,
这段代码训练慢,效果一般,但还是有一定效果。不过它说明了word2vec就是个分类器的本质,对理解原理有帮助。
事实上,这里实现的就是官方文档里,说的那个因为效果差被对比的方法(下图)。哈哈,就是这样。不过我们实现了这个的基础上,理解了原理,再去亲手实现NCE(而不是直接调函数),岂不是对NCE掌握的更好了?