【NLP实战】tensorflow词向量训练实战
实战是学习一门技术最好的方式,也是深入了解一门技术唯一的方式。因此,NLP专栏计划推出一个实战专栏,让有兴趣的同学在看文章之余也可以自己动手试一试。
本篇介绍自然语言处理中最基础的词向量的训练。
作者&编辑 | 小Dream哥
1 语料准备
用于词向量训练的语料应该是已经分好词的语料,如下所示:
2 词向量训练
(1) 读取语料数据
读取数据的过程很简单,就是从压缩文件中读取上面显示的语料,得到一个列表。
def read_data(filename):
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
(2) 根据语料,构建字典
构建字典几乎是所有NLP任务所必须的步骤。
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
data=[dictionary[word] if word in dictionary else 0 for word in words]
count[0][1] = unk_count
reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reverse_dictionary
(3) 根据语料,获取一个batch的数据
这里需要解释一下,此次词向量的训练,采用的是skip gram的方式,即通过一个词,预测该词附近的词。generate_batch函数中,skip_window表示取该词左边或右边多少个词,num_skips表示总共取多少个词。最后生成的batch数据,batch是num_skips*batch_size个词,label是中间的batch_size个词。
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)
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
(4) 用tensforslow训练词向量
首先,构造tensorflow运算图,主要包括以下几个步骤:
1.用palceholder先给训练数据占坑;
2.初始化词向量表,是一个|V|*embedding_size的矩阵,目标就是优化这个矩阵;
3.初始化权重;
4.构建损失函数,这里用NCE构建;
5.构建优化器;
6.构建变量初始化器
graph = tf.Graph()
with graph.as_default():
# input data
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)
# operations and variables
# look up embeddings for inputs
embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_inputs)
# construct the variables for the 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]))
ncs_loss_test=tf.nn.nce_loss(weights=nce_weights, biases=nce_biases,labels=train_labels, inputs=embed, num_sampled=num_sampled, num_classes=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))
# construct the SGD optimizer using a learning rate of 1.0
optimizer = tf.train.GradientDescentOptimizer(1.0).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
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()
然后,开始训练词向量:
num_steps = 1000
with tf.Session(graph=graph) as session:
# we must initialize all variables before using them
init.run()
print('initialized.')
# loop through all training steps and keep track of loss
average_loss = 0
for step in range(num_steps):
# generate a minibatch of training data
batch_inputs, batch_labels = generate_batch(batch_size, num_skips, skip_window)
feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}
# we perform a single update step by evaluating the optimizer operation (including it
# in the list of returned values of session.run())
_, loss_val,ncs_loss_ = session.run([optimizer, loss,ncs_loss_test], feed_dict=feed_dict)
average_loss += loss_val
final_embeddings = normalized_embeddings.eval()
print(final_embeddings)
(5) 保存词向量
将训练好的词向量写到文件中备用。
final_embeddings = normalized_embeddings.eval()
print(final_embeddings)
fp=open('vector.txt','w',encoding='utf8')
for k,v in reverse_dictionary.items():
t=tuple(final_embeddings[k])
s=''
for i in t:
i=str(i)
s+=i+" "
fp.write(v+" "+s+"\n")
fp.close()
最后,我们将词向量写到了vector.txt里面,得到了一份很大的词向量表,我们看看它长成什么样子:
可以看到,词向量就是将每个中文词用一个向量来表示,整个词表及其词向量构成了这份词向量表。
这里留一个作业,读者可以自己试一下,从表中读取出来几个词的向量,计算出来他们的相似度,看训练出来的词向量质量如何。
至此本文介绍了如何利用tensorflow平台自己写代码,训练一份自己想要的词向量,代码在我们有三AI的github可以
https://github.com/longpeng2008/yousan.ai/tree/master/natural_language_processing
找到word2vec文件夹,执行python3 w2v_skip_gram.py就可以运行,训练词向量了。
总结
这里讲述了词向量的具体训练过程,相关的原理在我之前的系列文章里有详细的讲述,感兴趣的同学可以好好看一下:
词向量是NLP开始迈进“现代化”的关键,是各种面试必问的基础,需重视。
我们也会在知识星球讨论代码的具体实现和优化,感兴趣扫描下面的二维码了解。