源码目录:
tensorflow/examples/tutorials/word2vec/word2vec_basic.py
详细过程
1.下载并载入数据
url = 'http://mattmahoney.net/dc/'
def maybe_download(filename, expected_bytes):
# 判断下下载过的就不下了
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)
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(filename)
print('Data size', len(words))
2.建立词典
vocabulary_size = 50000
def build_dataset(words):
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) #data和words对应,把词转换为下标
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)
del words # Hint to reduce memory.
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])
3.根据skip-gram模型batch生成训练数据
data_index = 0
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是一维,labels是二维"""
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个词
buffer = collections.deque(maxlen=span)
for _ in range(span): # 依次取span个词
buffer.append(data[data_index])
data_index = (data_index + 1) % len(data)
for i in range(batch_size // num_skips):
target = skip_window # 目标词是中间那个
targets_to_avoid = [ skip_window ]
for j in range(num_skips): #从目标次左右取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]) #deque挤掉最前面的
data_index = (data_index + 1) % len(data)
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]])
4.构造神经网络
batch_size = 128
embedding_size = 128 # 词向量维度.
skip_window = 1 # 左右窗口大小.
num_skips = 2 #每个窗口取几个词
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.random.choice(valid_window, valid_size, replace=False)
num_sampled = 64 # Number of negative examples to sample.
graph = tf.Graph()
with graph.as_default():
"""placeholder用来放置网络使用过程的数据"""
train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
with tf.device('/cpu:0'):
"""词向量,二维,词典大小*词向量维数"""
embeddings = tf.Variable( tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
"""根据train_inputs查找embedding"""
embed = tf.nn.embedding_lookup(embeddings, train_inputs)
"""构造网络"""
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]))
"""定义lost function,"""
loss = tf.reduce_mean(
tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels, num_sampled, vocabulary_size))
"""定义优化方法"""
optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
"""norm化,每一行平方求和再开方. """
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, normalized_embeddings, transpose_b=True)
# Add variable initializer.
init = tf.initialize_all_variables()
5.开始训练
num_steps = 100001
with tf.Session(graph=graph) as session:
"""初始化所有变量"""
init.run()
print("Initialized")
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}
"""运行依次迭代,指定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.
print("Average loss at step ", step, ": ", average_loss)
average_loss = 0
# Note that this is expensive (~20% slowdown if computed every 500 steps)
if step % 10000 == 0:
"""计算similarity,结果是[评估个数*词数]"""
sim = similarity.eval()
for i in xrange(valid_size):
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()