Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vector 二维单词嵌入中的单词映射_Vector_Sentiment Analysis_Word_Natural Language Processing - Fatal编程技术网

Vector 二维单词嵌入中的单词映射

Vector 二维单词嵌入中的单词映射,vector,sentiment-analysis,word,natural-language-processing,Vector,Sentiment Analysis,Word,Natural Language Processing,在我的硕士论文中,我创建了Word2Vec模型。我想展示这张图片来澄清结果。但是映射是如何在这个2D空间中显示单词的呢 所有单词都由300 dim的向量表示。它们是如何映射到这个2D图像的?x轴和y轴是什么 代码: 有几种方法 第一种方法是使用PCA(主成分分析),在x轴上绘制第一个成分,在y轴上绘制第二个成分(并丢弃其他成分) 你不用说你用哪个库来生成你的词向量,它可能有自己的PCA函数。但sklearn有一个: (有一些现成的代码显示如何使用gensim生成向量,然后使用该函数绘制向量。)

在我的硕士论文中,我创建了Word2Vec模型。我想展示这张图片来澄清结果。但是映射是如何在这个2D空间中显示单词的呢

所有单词都由300 dim的向量表示。它们是如何映射到这个2D图像的?x轴和y轴是什么

代码:


有几种方法

第一种方法是使用PCA(主成分分析),在x轴上绘制第一个成分,在y轴上绘制第二个成分(并丢弃其他成分)

你不用说你用哪个库来生成你的词向量,它可能有自己的PCA函数。但sklearn有一个: (有一些现成的代码显示如何使用gensim生成向量,然后使用该函数绘制向量。)

您可以尝试的另一种方法是绘制单词向量的前两个维度。这是合理的,因为字向量中的所有维度都应该具有相等的权重。也就是说,从300个维度中选取任何两个维度,都会得到与其他两个维度相同的信息量

但是使用PCA是更为正常的可视化方法

w2v_model.build_vocab(documents)

words = w2v_model.wv.vocab.keys()
vocab_size = len(words)
print("Vocab size", vocab_size)

w2v_model.train(documents, total_examples=len(documents), 

epochs=W2V_EPOCH)
tokenizer = Tokenizer()
tokenizer.fit_on_texts(df_train.text)

vocab_size = len(tokenizer.word_index) + 1
print("Total words", vocab_size)

x_train = pad_sequences(tokenizer.texts_to_sequences(df_train.text), maxlen=SEQUENCE_LENGTH)
x_test = pad_sequences(tokenizer.texts_to_sequences(df_test.text), maxlen=SEQUENCE_LENGTH)

labels = df_train.target.unique().tolist()
labels.append(NEUTRAL)

encoder = LabelEncoder()
encoder.fit(df_train.target.tolist())

y_train = encoder.transform(df_train.target.tolist())
y_test = encoder.transform(df_test.target.tolist())

y_train = y_train.reshape(-1,1)
y_test = y_test.reshape(-1,1)

embedding_matrix = np.zeros((vocab_size, W2V_SIZE))
for word, i in tokenizer.word_index.items():
  if word in w2v_model.wv:
    embedding_matrix[i] = w2v_model.wv[word]
print(embedding_matrix.shape)
embedding_layer = Embedding(vocab_size, W2V_SIZE, weights=[embedding_matrix], input_length=SEQUENCE_LENGTH, trainable=False)