# Tensorflow实现word2vec

## 数据集

```'''Step1: download dataset'''
url = 'http://mattmahoney.net/dc/'

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)
return filename

## 读取数据

```'''Step2: read dataset'''
with zipfile.ZipFile(filename) as f:
return data

print('Datas size', len(words))```

words中包含17005207个word

```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
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)
del words```

data是单词的index，dictionary是正向的word–>index的字典，reverse_dictionary是反向的index–>word的字典.

## 生成batch数据

```'''Step3: batch generator'''
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 = np.ndarray(shape=(batch_size), dtype=np.int32)
labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
span = 2 * skip_window + 1
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 //单词之间联系的距离
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, 0] = buffer[target]
buffer.append(data[data_index])
data_index = ( data_index + 1) % len(data)

return batch, labels```

## 训练

• The basic idea is to convert a multinomial classification problem (as it is the problem of predicting the next word) to a binary classification problem. That is, instead of using softmax to estimate a true probability distribution of the output word, a binary logistic regression (binary classification) is used instead.
• For each training sample, the enhanced (optimized) classifier is fed a true pair (a center word and another word that appears in its context) and a number of kk randomly corrupted pairs (consisting of the center word and a randomly chosen word from the vocabulary). By learning to distinguish the true pairs from corrupted ones, the classifier will ultimately learn the word vectors.
• This is important: instead of predicting the next word (the “standard” training technique), the optimized classifier simply predicts whether a pair of words is good or bad.

```'''Step 4: training'''
batch_size = 128
embedding_size = 128
skip_window = 128
num_skips = 2
valid_size = 16
valid_window = 100 //进行validation的单词数量
valid_examples = np.random.choice(valid_window, valid_size, replace=False)
num_sampled = 64 //负样本的单词数量

graph = tf.Graph()
with graph.as_default():
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)) //随机生成词向量
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]))

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)) //使用NCE 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, normalized_embeddings, transpose_b=True)
init = tf.global_variables_initializer()

num_steps = 1000000
with tf.Session(graph=graph) as session:
init.run()
print('Initialized')

average_loss = 0
for step in range(num_steps+1):
batch_inputs, batch_labels = generate_batch(batch_size, num_skips, skip_window)
feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}
_, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)
average_loss += loss_val

if step % 2000 == 0:
if  step > 0:
average_loss /= 2000
print('Average loss at step %d : %.4f' % (step, average_loss))
average_loss = 0

if step % 10000 == 0:
sim = similarity.eval()
for i in range(valid_size):
valid_word = reverse_dictionary[valid_examples[i]]
top_k = 5
nearst = (-sim[i, :]).argsort()[1:top_k+1]
log_str = 'Nearst to %s:' % valid_word
for k in range(top_k):
close_word = reverse_dictionary[nearst[k]]
log_str = '%s %s,' % (log_str, close_word)
print(log_str)
final_embeddings = normalized_embeddings.eval()```

## 可视化

```'''Step 5: visualization'''
from sklearn.manifold import TSNE
import  matplotlib.pyplot as plt
def plot_with_label(low_dim_embs, labels, filename='tsne.png'):
assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings'
plt.figure(figsize=(18,18))
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)

tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
plot_only = 3000
low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :])
labels = [reverse_dictionary[i] for i in range(plot_only)]
plot_with_label(low_dim_embs, labels)```

114 篇文章54 人订阅

0 条评论

## 相关文章

376100

15110

### tensorflow学习笔记(三十四)：Saver(保存与加载模型)

Saver tensorflow 中的 Saver 对象是用于 参数保存和恢复的。如何使用呢？ 这里介绍了一些基本的用法。 官网中给出了这么一个例子： ...

44080

### [C++]:A*——A Star算法简介

A*算法 求最优解 算法一直维护两个表: Open和Close 将起点S加入Open中 将所有S可到达的点（障碍物以及位于Close表中的点均看成不可达...

50060

36950

### 一致性hash算法清晰详解！

consistent hashing 算法早在 1997 年就在论文 Consistent hashing and random trees 中被提出，目前在 ...

11120

32370

### 详解 Python qrcode 二维码模块

1、version：控制二维码的大小，取值范围从1到40。取最小值1时，二维码大小为21*21。取值为 None （默认）或者使用fit=true参数（默认）时...

16200

19630

7420