word2vec 是一种广泛用于自然语言处理的技术,主要目的是将单词转换为词向量(将单词表示为数字向量)。这些词向量能够反映不同词语的相似性,使得语义上或语法上相近的词语在向量空间中也相互接近。
word2vec 是自然语言处理领域的一种基础技术,广泛应用于文本分析、机器翻译、情感分析等多种场景。
如下图所示,其中 N 为 2,对于单词 word,它的上下文词为 machine、learning、 a 和 method。
CBOW(连续词袋模型),一种根据上下文词预测当前词的模型。
下面,我们来看一下具体的模型架构。
输入层
隐藏层
输出层
CBOW 和 Skip-Gram 模型的区别在于输入词的数量。CBOW 模型采用多个词,每个词经过相同的嵌入层,然后对词嵌入向量进行平均,然后进入线性层。而 Skip-Gram 模型则采用单个词。
对中心词和外部词进行编码
此中心词和相应外部词将用于训练模型。
importre
importnumpyasnp
WINDOW_SIZE=2
defcreate_vocabulary(training_data):
"""通过标记训练数据返回排序后的单词列表。"""
all_words=''.join(training_data).lower()
all_words=all_words.replace('.','')
all_words=all_words.split('')
vocab=list(set(all_words))
vocab.sort()
returnvocab
defone_hot(word,vocab,vocab_size):
"""返回单词的独热编码向量。"""
one_hot=[0]*vocab_size
pos=vocab.index(word)
one_hot[pos]=1
one_hot=np.array(one_hot)
returnone_hot
defcreate_vector_word_map(vocab,vocab_size):
"""返回一个词典映射,将独热向量转换回单词。"""
vec_to_word={str(one_hot(word,vocab,vocab_size)):wordforwordinvocab}
returnvec_to_word
defencode_training_data(training_data,vocab_size,window_size):
"""Encodethecenterandoutsidewordsasone-hotvectors."""
encoded_training_data=[]
forsentenceintraining_data:
#Tokenizethesentence
tokens=re.sub(r'[^\w\s]','',sentence).lower().split('')
#Encodeeachcenterwordanditssurroundingcontextwords
forword_pos,wordinenumerate(tokens):
center_word=one_hot(word,vocab,vocab_size)
foroutside_posinrange(word_pos-window_size,
word_pos+window_size+1):
if(outside_pos>=0)and(outside_pos<len(tokens))\
and(outside_pos!=word_pos):
outside_word=one_hot(tokens[outside_pos],
vocab,
vocab_size)
encoded_training_data.append([center_word,outside_word])
returnencoded_training_data
defprint_training_encodings(encoded_training_data,vocab,vec_to_word):
"""rinttheencodingsforeach(centerword-outsidewords)set."""
max_len=len(max(vocab,key=len))
fornum,(cw_vector,ow_vectors)inenumerate(encoded_training_data):
cw=vec_to_word[str(cw_vector)]
ow=vec_to_word[str(ow_vectors)]
print(f'CenterWord#{num}:{cw}{cw_vector}')
print(f'OutsideWords:{ow}{ow_vectors}')
#Createtrainingdata
training_data=['Thedogchasedthecataroundthegarden.']
#Encodetrainingdata
vocab=create_vocabulary(training_data)
vocab_size=len(vocab)
vec_to_word=create_vector_word_map(vocab,vocab_size)
encoded_training_data=encode_training_data(training_data,
vocab_size,
window_size=WINDOW_SIZE)
##Printoutresults
print_training_encodings(encoded_training_data,vocab,vec_to_word)
EMBEDDING_DIM=3
#Calculatethehiddenlayervector
x=encoded_training_data[0][0]
w_center=np.random.rand(vocab_size,EMBEDDING_DIM)
h=np.dot(x,w_center)
#Printtheresults
print(f'Centerword,w(t):{vec_to_word[str(x)]}\n')
print(f'Inputvector,x:{x}\n')
print(f'W_center:\n\n{w_center}\n')
print(f'Hiddenlayer,h:{h}\n')#Calculatetherawnetworkoutputs
w_outside=np.random.rand(EMBEDDING_DIM,vocab_size)
u=np.dot(h,w_outside)
#Printtheresults
print(f'Hiddenlayer,h:{h}\n')
print(f'W_outside:\n\n{w_outside}\n')
print(f'Rawnetworkoutputs(logits),u:{u}\n')每个元素的值对应于一个单词属于给定中心词 x 的集合外部单词的“概率” 。
defsoftmax(u):
"""Returnthesoftmaxvaluesforavectoru."""
values=np.exp(u)/np.sum(np.exp(u))
returnvalues
deffind_outside_words(y_pred,vocab):
#Getasortedlistofsoftmaxscores
sorted_y_pred=y_pred.copy()
sorted_y_pred=sorted_y_pred[::-1]
top_score=sorted_y_pred[:1]
index=np.where(y_pred==top_score)[0][0]
print(index)
word=vocab[index]
returnword
#Calculatethesoftmaxoutputs
y_pred=softmax(u)
outside_word=find_outside_words(y_pred,vocab)
#Printtheresults
print(f'Rawnetworkoutputs(logits),u:{u}\n')
print(f'Softmaxoutputs,y_pred:{y_pred}\n')
print(f'Outsidewords:{outside_word}')
适用场景
性能
资源消耗
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |