實(shí)戰(zhàn)是學(xué)習(xí)一門(mén)技術(shù)最好的方式,也是深入了解一門(mén)技術(shù)唯一的方式。因此,NLP專欄計(jì)劃推出一個(gè)實(shí)戰(zhàn)專欄,讓有興趣的同學(xué)在看文章之余也可以自己動(dòng)手試一試。
本篇介紹自然語(yǔ)言處理中最基礎(chǔ)的詞向量的訓(xùn)練。
作者&編輯 | 小Dream哥
1 語(yǔ)料準(zhǔn)備
用于詞向量訓(xùn)練的語(yǔ)料應(yīng)該是已經(jīng)分好詞的語(yǔ)料,如下所示:
2 詞向量訓(xùn)練
(1) 讀取語(yǔ)料數(shù)據(jù)
讀取數(shù)據(jù)的過(guò)程很簡(jiǎn)單,就是從壓縮文件中讀取上面顯示的語(yǔ)料,得到一個(gè)列表。
def read_data(filename):
with zipfile.ZipFile(filename) as f:
data = tf.compat.as_str(f.read(f.namelist()[0])).split()
return data
(2) 根據(jù)語(yǔ)料,構(gòu)建字典
構(gòu)建字典幾乎是所有NLP任務(wù)所必須的步驟。
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) 根據(jù)語(yǔ)料,獲取一個(gè)batch的數(shù)據(jù)
這里需要解釋一下,此次詞向量的訓(xùn)練,采用的是skip gram的方式,即通過(guò)一個(gè)詞,預(yù)測(cè)該詞附近的詞。generate_batch函數(shù)中,skip_window表示取該詞左邊或右邊多少個(gè)詞,num_skips表示總共取多少個(gè)詞。最后生成的batch數(shù)據(jù),batch是num_skips*batch_size個(gè)詞,label是中間的batch_size個(gè)詞。
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訓(xùn)練詞向量
首先,構(gòu)造tensorflow運(yùn)算圖,主要包括以下幾個(gè)步驟:
1.用palceholder先給訓(xùn)練數(shù)據(jù)占坑;
2.初始化詞向量表,是一個(gè)|V|*embedding_size的矩陣,目標(biāo)就是優(yōu)化這個(gè)矩陣;
3.初始化權(quán)重;
4.構(gòu)建損失函數(shù),這里用NCE構(gòu)建;
5.構(gòu)建優(yōu)化器;
6.構(gòu)建變量初始化器
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()
然后,開(kāi)始訓(xùn)練詞向量:
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) 保存詞向量
將訓(xùn)練好的詞向量寫(xiě)到文件中備用。
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()
最后,我們將詞向量寫(xiě)到了vector.txt里面,得到了一份很大的詞向量表,我們看看它長(zhǎng)成什么樣子:
可以看到,詞向量就是將每個(gè)中文詞用一個(gè)向量來(lái)表示,整個(gè)詞表及其詞向量構(gòu)成了這份詞向量表。
這里留一個(gè)作業(yè),讀者可以自己試一下,從表中讀取出來(lái)幾個(gè)詞的向量,計(jì)算出來(lái)他們的相似度,看訓(xùn)練出來(lái)的詞向量質(zhì)量如何。
至此本文介紹了如何利用tensorflow平臺(tái)自己寫(xiě)代碼,訓(xùn)練一份自己想要的詞向量,代碼在我們有三AI的github可以
https://github.com/longpeng2008/yousan.ai/tree/master/natural_language_processing
找到word2vec文件夾,執(zhí)行python3 w2v_skip_gram.py就可以運(yùn)行,訓(xùn)練詞向量了。
這里講述了詞向量的具體訓(xùn)練過(guò)程,相關(guān)的原理在我之前的系列文章里有詳細(xì)的講述,感興趣的同學(xué)可以好好看一下:
【NLP-詞向量】從模型結(jié)構(gòu)到損失函數(shù)詳解word2vec
詞向量是NLP開(kāi)始邁進(jìn)“現(xiàn)代化”的關(guān)鍵,是各種面試必問(wèn)的基礎(chǔ),需重視。
我們也會(huì)在知識(shí)星球討論代碼的具體實(shí)現(xiàn)和優(yōu)化,感興趣掃描下面的二維碼了解。
聯(lián)系客服