本文將從多個方面對GloVe詞向量進行詳細的闡述,包括其原理、優缺點、應用以及代碼實現。如果你對詞向量感興趣,那麼這篇文章將會是一次很好的學習體驗。
一、原理
GloVe(Global Vectors for Word Representation)是由斯坦福大學的研究者Jeffrey Pennington、Richard Socher和Christopher D. Manning提出的一種詞向量模型。
GloVe的主要思想是將詞向量表示為兩個詞的共現概率,通過優化共現概率的對數差異來學習詞向量。GloVe模型的假設是:如果兩個詞經常一起出現,則這兩個詞之間必定存在一種關係。這種關係可以建立在共現矩陣中,其中第(i,j)個元素Xij表示i詞和j詞在同一上下文中出現的次數。模型的核心思想是通過嘗試對點對之間的共現率進行建模來學習詞向量。對於J個不同的單詞,GloVe的目標是學習一個J x V的單詞-詞向量矩陣W,其中每個詞有一個V維的向量表示。GloVe使用了以下公式:
W(i,j) = exp(θ * f(Xij))
其中,f(Xij) = (Xij / Xmax) ^ α
其中,Xij是兩個詞在上下文中的共現次數,Xmax是所有共現頻率的上限,α是一個消除頻率影響的參數,θ是學習的權值。通過對數差異來優化目標函數:
J = ∑∑(W(i,j) * (wi · wj + bi + bj – logXij))^2
其中,wi是詞i的詞向量,bi是詞i的偏差項,同理wj和bj,logXij是所有共現概率的對數。
二、優缺點
相對於其他詞向量模型,GloVe有以下幾點優點:
1.對極端高頻和低頻詞語具有魯棒性。
2.一個單獨的全局共現矩陣可以用來生成不同大小的詞向量。
3.對於大規模語料庫,訓練速度相對較快。
與此同時,GloVe也有一些缺點:
1.缺乏層次結構,無法處理語義關係的複雜性。
2.對於一些意義相似但表述方式不同的辭彙,無法學習到它們之間的細微差異。
三、應用
GloVe詞向量在自然語言處理領域應用廣泛,包括語義相似度計算、命名實體識別、文本分類等。在此,我們以情感分類問題為例,簡單介紹GloVe的應用。
首先,我們需要將文本轉換成數值形式,例如詞袋模型。然後使用GloVe模型來學習每個詞的詞向量,最後可以使用一些分類器來對文本進行分類。下面我們給出Python代碼示例:
import os
import urllib.request
import numpy as np
from keras.layers import Conv1D, Dense, Input, LSTM, Embedding
from keras.layers import Dropout, Activation
from keras.layers.merge import concatenate
from keras.layers.normalization import BatchNormalization
from keras.models import Model
from keras.preprocessing import sequence
from keras.utils import np_utils
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 下載並解壓數據集
url = 'https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz'
filepath = './aclImdb_v1.tar.gz'
if not os.path.isfile(filepath):
result = urllib.request.urlretrieve(url, filepath)
print('downloaded:', result)
import tarfile
if not os.path.exists('./aclImdb'):
tfile = tarfile.open('./aclImdb_v1.tar.gz', 'r:gz')
result = tfile.extractall('./')
print('extracted to:', result)
# 載入數據集
def load_dataset(mode='train'):
"""
mode: 'train' or 'test'
"""
data_path = './aclImdb/{}/'.format(mode)
pos_files = os.listdir(data_path + 'pos/')
neg_files = os.listdir(data_path + 'neg/')
texts = []
labels = []
for filename in pos_files:
with open(data_path + 'pos/' + filename, encoding='utf-8') as f:
texts.append(f.read())
labels.append(1)
for filename in neg_files:
with open(data_path + 'neg/' + filename, encoding='utf-8') as f:
texts.append(f.read())
labels.append(0)
return texts, labels
train_texts, train_labels = load_dataset('train')
test_texts, test_labels = load_dataset('test')
# 構建詞典
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
tokenizer = Tokenizer()
tokenizer.fit_on_texts(train_texts)
word_index = tokenizer.word_index
MAX_SEQUENCE_LENGTH = 500
train_sequences = tokenizer.texts_to_sequences(train_texts)
train_sequences = pad_sequences(train_sequences, maxlen=MAX_SEQUENCE_LENGTH)
test_seqences = tokenizer.texts_to_sequences(test_texts)
test_seqences = pad_sequences(test_seqences, maxlen=MAX_SEQUENCE_LENGTH)
# 載入GloVe模型
GLOVE_DIR = './glove.6B/'
embeddings_index = {}
with open(os.path.join(GLOVE_DIR, 'glove.6B.100d.txt'), encoding='utf-8') as f:
for line in f:
values = line.split()
word = values[0]
coefs = np.array(values[1:], dtype='float32')
embeddings_index[word] = coefs
# 創建詞向量矩陣
EMBEDDING_DIM = 100
embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))
for word, i in word_index.items():
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix[i] = embedding_vector
# 構建模型
def build_model():
inputs = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
x = Embedding(len(word_index) + 1,
EMBEDDING_DIM,
weights=[embedding_matrix],
input_length=MAX_SEQUENCE_LENGTH,
trainable=True)(inputs)
x = Conv1D(filters=128, kernel_size=5, activation='relu')(x)
x = Dropout(0.5)(x)
x = LSTM(64)(x)
x = Dense(10, activation='relu')(x)
x = Dropout(0.5)(x)
predictions = Dense(1, activation='sigmoid')(x)
model = Model(inputs=inputs, outputs=predictions)
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
model = build_model()
model.fit(train_sequences, train_labels,
batch_size=32,
epochs=5,
validation_data=(test_seqences, test_labels))
y_pred = model.predict(test_seqences).flatten()
y_pred = np.round(y_pred).astype(int)
print('accuracy:', accuracy_score(test_labels, y_pred))
四、總結
本文從原理、優缺點、應用三個方面對GloVe詞向量進行了詳細的闡述,並且給出了一個簡單的情感分類問題實例,希望對讀者對詞向量的學習有幫助。GloVe詞向量模型在自然語言處理領域應用廣泛,其優越性的表現是基於全局統計的,這也是其相較於其他方法的優勢所在。
原創文章,作者:TYJSY,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/374378.html