繁体   English   中英

如何在熊猫中找到两个字符串之间的相关性

[英]How to find the correlation between two strings in pandas

我有 df 的字符串值

   Keyword
    plant
    cell
    cat
    Pandas

我想找到这两个字符串值之间的关系或相关性。

我用过熊猫corr = df1.corrwith(df2,axis=0) 但这对于查找数值之间的相关性很有用,但我想通过查找相关距离来查看两个字符串是否相关。 我怎样才能做到这一点?

这里有几个步骤,你需要做的第一件事是为每个单词提取某种向量。

一个好方法是使用gensim word2vec(你需要从这里下载文件):

from gensim.models import KeyedVectors

model = KeyedVectors.load_word2vec_format('data/GoogleGoogleNews-vectors-negative300.bin', binary=True)

获得预训练后的矢量后,您需要为每个单词提取矢量:

vector = model['plant']

或者在pandas列示例中:

df['Vectors'] = df['Keyword'].apply(lambda x: model[x])

完成此操作后,您可以使用多种方法计算两个向量之间的距离,例如欧几里德距离:

from sklearn.metrics.pairwise import euclidean_distances
distances = euclidean_distances(list(df['Vectors']))

距离将是一个矩阵,对角线上的0和所有单词之间的距离。 距离越接近0,单词越相似。

您可以使用不同的模型和不同的距离指标,但您可以将其作为起点。

通常情况下,上述加载模型的方法可能不起作用,因此我将与您分享对我有用的方法。 我正在使用 Google Colab,因此使用了“!” 在每个命令之前。

使用wget下载文件(即模型),如下所示:

!wget -c "https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz"

接下来使用gzip使用以下命令解压缩文件:

!gzip -d GoogleNews-vectors-negative300.bin.gz

接下来使用gensimmodels库使用此代码加载下载的文件。 这将为您提供wordVector模型以供进一步使用。 我正在使用 Google Colab,因此如果您在本地执行此过程,文件路径可能会更改:

from gensim import models
model = models.KeyedVectors.load_word2vec_format(
    '/content/GoogleNews-vectors-negative300.bin', binary=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM