为什么我在word2vec和TFIDF中有不同数量的术语?我该如何解决?

问题描述 投票:-4回答:1

我需要将TFIDF矩阵中的项的宽度乘以word2vec矩阵的词嵌入,但我不能这样做,因为每个矩阵具有不同数量的项。 我正在使用相同的语料库来获取两个矩阵,我不知道为什么每个矩阵都有不同数量的项。

[我的问题是,我有一个矩阵TFIDF,其形状为(56096, 15500)(对应于:项数,文档数)和矩阵Word2vec,其形状为(300, 56184)(对应于:字嵌入数,条款)。我在两个矩阵中都需要相同数量的项。

我使用此代码来获取单词嵌入Word2vec的矩阵:

def w2vec_gensim(norm_corpus):
    wpt = nltk.WordPunctTokenizer()
    tokenized_corpus = [wpt.tokenize(document) for document in norm_corpus]
    # Set values for various parameters
    feature_size = 300
    # Word vector dimensionality
    window_context = 10
    # Context window size
    min_word_count = 1
    # Minimum word count
    sample = 1e-3
    # Downsample setting for frequent words
    w2v_model = word2vec.Word2Vec(tokenized_corpus, size=feature_size, window=window_context, min_count =  min_word_count, sample=sample, iter=100)
    words = list(w2v_model.wv.vocab)
    vectors=[]
    for w in words:
        vectors.append(w2v_model[w].tolist())
    embedding_matrix= np.array(vectors)
    embedding_matrix= embedding_matrix.T
    print(embedding_matrix.shape)

    return embedding_matrix

以及用于获取TFIDF矩阵的代码:

tv = TfidfVectorizer(min_df=0., max_df=1., norm='l2', use_idf=True, smooth_idf=True)


def matriz_tf_idf(datos, tv):
    tv_matrix = tv.fit_transform(datos)
    tv_matrix = tv_matrix.toarray()
    tv_matrix = tv_matrix.T
    return tv_matrix

而且我在每个矩阵中需要相同数量的术语。例如,如果我在TFIDF中有56096个词,则在嵌入矩阵中需要相同的数字,我的意思是形状为(56096, 1550)的矩阵TFIDF和形状为(300, 56096)的嵌入Word2vec矩阵。如何在两个矩阵中获得相同数量的项?因为没有更多的数据我无法删除,由于我需要乘法才有意义,因为我的目标是从文档中获取嵌入内容。

非常感谢。

python matrix word2vec embedding
1个回答
0
投票

问题是,TFIDF削减了大约90个术语。这是因为标记化是必要的。这是解决方案:

wpt = nltk.WordPunctTokenizer()
tv = TfidfVectorizer(min_df=0., max_df=1., norm='l2', use_idf=True, smooth_idf=True,
                     tokenizer=wpt.tokenize)
© www.soinside.com 2019 - 2024. All rights reserved.