word2vec理解:
自 然语言不能直接处理,因此我们要把它们转换成可以处理的数字或者向量。传统的方法是one-hot-encoder,就是把所有的单词重新篇成一个很长的向量,但是他有一个不好的地方,一是编码是随机的,没有提供任何关联信息,而是,编码的向量就有一个是1,其他都为零,整个矩阵很稀疏,稀疏矩阵的训练效率很低,
这里使用向量表达可以有效的解决这些问题,一类是计数模型,他就是用一个滑动窗口,就算一个字周围出现其他字的次数,然后转换成矩阵。而是预测模型,他主要是用到非监督学习,用到深度学习去预测,然后把隐藏层的系数矩阵作为他的向量。
Word2Vec即是一种计算非常高效的, 可以 从原始语料中学习字词空间向量的预测模型。它主要分为CBOW ( Continuous Bag of Words )和Skip-Gram 两种模式,其中CBOW是从原始语句(比如:中国的首都是————) 推测目标字词(比如:北京);而Skip-Gram则正好相反,它是从目标字词推测出原始语句, 其中 CBOW 对小 型数据 比较合适, 而Skip-Gram 在大型语料中表现得更好。
import collections
import math
import os
import random
import zipfile
import numpy as np
import urllib
import tensorflow as tf
# Step 1: Download the data.
# 步骤一: 下载数据
url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes):
"""Download a file if not present, and make sure it's the right size."""
# 如果不存在该文件的话就下载该文件,并确保它的大小正确
if not os.path.exists(filename):
filename, _ = urllib.request.urlretrieve(url + filename, filename)
statinfo = os.stat(filename)
if statinfo.st_size == expected_bytes:
print('Found and verified', filename)
else:
print(statinfo.st_size)
raise Exception(
'Failed to verify ' + filename + '. Can you get to it with a browser?')
return filename
filename = maybe_download('text8.zip', 31344016)
# Read the data into a list of strings.
# 把数据读取进一个字符串的列表
def read_data(filename):
"""Extract the first file enclosed in a zip file as a list of words"""
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
words = read_data(filename)
print('Data size', len(words))
# Step 2: Build the dictionary and replace rare words with UNK token.
# 步骤二: 构建一个词典,并把稀有词语用'UNK'代替
vocabulary_size = 50000
def build_dataset(words):
# 得到一个单词->词频的列表,取词频最高的49999个
count = [['UNK', -1]]
count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
#print(count[0])
#print(count[1])
#print(count[49999])
'''
i = 0
for word,_ in count:
if word == 'UNK':
i = i + 1
print('UNK', i, '个')
'''
# 得到一个单词->编号的词典
dictionary = dict()
#print(len(dictionary))
for word, _ in count:
dictionary[word] = len(dictionary)
#print(len(dictionary))
# 将全部单词转为编号,并统计UNK的词频
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)
# 将UNK的词频赋值
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)
#print(len(count))
#print(len(dictionary))
del words # Hint to reduce memory. 删除原始单词列表以节约内存
# 输出最常见的5个单词及频数(包括UNK)
print('Most common words (+UNK)', count[:5])
# 输出前十个单词
print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])
data_index = 0
# Step 3: Function to generate a training batch for the skip-gram model.
'''
用来生成训练用的batch数据
batch_size为批量大小
skip_window为单词最远可以联系的距离
num_skips为对每个单词生成多少个样本,它不能大于skip_window值的两倍
并且batch_size必须是它的整数倍(确保每个batch包含了一个词汇对应的所有样本)
'''
def generate_batch(batch_size, num_skips, skip_window):
global data_index
#print(data_index)
# 确保num_skips和batch_size满足前面提到的条件
assert batch_size % num_skips == 0
assert num_skips <= 2 * skip_window
# 用np.ndarray将batch和labels初始化为数组
batch = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
# span为对某个单词创建相关样本时会使用到的单词数量
span = 2 * skip_window + 1 # [ skip_window target skip_window ]
# 创建一个最大容量为span的deque,即双向队列,在对deque使用append方法添加变量时,只会保留最后插入的span个变量
buffer = collections.deque(maxlen=span)
# 从data_index开始,把span个单词顺序读入buffer作为初始值
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中过滤
targets_to_avoid.append(target)
batch[i * num_skips + j] = buffer[skip_window]
labels[i * num_skips + j, 0] = buffer[target]
# 在对一个目标单词生成完所有样本后(num_skips个样本),我们再读入下一个单词(同时会抛弃掉buffer中第一个单词),即把滑窗向后移动一位
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
# 返回batch和labels
return batch, labels
batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)
for i in range(8):
print(batch[i], reverse_dictionary[batch[i]],
'->', labels[i, 0], reverse_dictionary[labels[i, 0]])
# Step 4: Build and train a skip-gram model.
# 构建并训练一个skip-gram模型
batch_size = 128
# embedding_size即将单词转为稠密向量的维度,一般是50~1000这个范围内的值
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.
# 指验证单词只从频数最高的100个单词中抽取
valid_window = 100 # Only pick dev samples in the head of the distribution.
# 随机抽取valid_size个验证单词
valid_examples = np.random.choice(valid_window, valid_size, replace=False)
# 训练时用来做负样本的噪声单词的数量
num_sampled = 64 # Number of negative examples to sample.
# 创建一个tf.Graph并设置为默认的graph
graph = tf.Graph()
with graph.as_default():
# Input data.
# 创建训练数据中的placeholder
train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
# 将valid_examples转为TensorFlow中的constant
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
# Ops and variables pinned to the CPU because of missing GPU implementation
# 限定所有计算在CPU上执行,因为可能在GPU上还没有实现
with tf.device('/cpu:0'):
# Look up embeddings for inputs.
# 使用tf.random_uniform随机生成所有单词的词向量
embeddings = tf.Variable(
tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
# 使用tf.nn.embedding_lookup查找输入train_inputs对应的向量embed
embed = tf.nn.embedding_lookup(embeddings, train_inputs)
# Construct the variables for the NCE loss
# 使用tf.truncated_normal初始化NCE Loss中的权重参数nce_weights
nce_weights = tf.Variable(
tf.truncated_normal([vocabulary_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
# 将nce_biases初始化为0
nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
# Compute the average NCE loss for the batch.
# tf.nce_loss automatically draws a new sample of the negative labels each
# time we evaluate the loss.
# 使用tf.nn.nce_loss计算学习出的词向量embedding在训练数据上的loss,并使用tf.reduce_mean进行汇总
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))
# Construct the SGD optimizer using a learning rate of 1.0.
# 定义优化器为SGD,且学习速率为1.0
optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
# Compute the cosine similarity between minibatch examples and all embeddings.
# 计算嵌入向量embeddings的L2范数norm
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
# 将embeddings除以其L2范数得到标准化后的normalized_embeddings
normalized_embeddings = embeddings / norm
# 使用tf.nn.embedding_lookup查询验证单词的词向量
valid_embeddings = tf.nn.embedding_lookup(normalized_embeddings, valid_dataset)
# 计算验证单词的词向量与词汇表中所有单词的相似性
similarity = tf.matmul(valid_embeddings, normalized_embeddings, transpose_b=True)
# Add variable initializer.
init = tf.global_variables_initializer()
# Step 5: Begin training.
# 步骤5: 开始训练
# 定义最大的迭代次数为10万次
num_steps = 100001
with tf.Session(graph=graph) as session:
# We must initialize all variables before we use them.
# 执行参数初始化
init.run()
print("Initialized")
average_loss = 0
for step in range(num_steps):
# 先使用generate_batch生成一个batch的inputs和labels数据,并用它们创建feed_dict
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()
# 使用session.run()执行一次优化器运算(即一次参数更新)和损失计算,并将这一步训练的loss累积到average_loss
_, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)
average_loss += loss_val
if step % 2000 == 0:
if step > 0:
average_loss /= 2000
# The average loss is an estimate of the loss over the last 2000 batches.
# 之后每2000次循环,计算一下平均loss并显示出来
print("Average loss at step ", step, ": ", average_loss)
average_loss = 0
# Note that this is expensive (~20% slowdown if computed every 500 steps)
# 每10000次循环,计算一次验证单词与全部单词的相似度,并将与每个验证单词最相似的8个单词展示出来
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_str = "Nearest to %s:" % valid_word
for k in range(top_k):
close_word = reverse_dictionary[nearest[k]]
log_str = "%s %s," % (log_str, close_word)
print(log_str)
final_embeddings = normalized_embeddings.eval()
# Step 6: Visualize the embeddings.
def plot_with_labels(low_dim_embs, labels, filename='tsne.png'):
assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
plt.figure(figsize=(18, 18)) #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',
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)
plot_only = 200
low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only,:])
labels = [reverse_dictionary[i] for i in range(plot_only)]
plot_with_labels(low_dim_embs, labels)
except ImportError:
print("Please install sklearn, matplotlib, and scipy to visualize embeddings.")