【问题标题】:How to find the correlation between two strings in pandas如何在熊猫中找到两个字符串之间的相关性
【发布时间】:2019-08-19 01:14:00
【问题描述】:

我有 df 的字符串值

   Keyword
    plant
    cell
    cat
    Pandas

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

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

【问题讨论】:

  • 您是要查找字母或单词同义词距离的相关性吗?
  • @NagaKiran 同义词距离。
  • @Georgy 不,我想查找同义词距离,但要查找植物与细胞、植物与猫、植物与熊猫等之间的同义词距离,而不是一个相关值,我想要单独的分数
  • 你可以参考链接Semantic feature generation

标签: python string pandas dataframe correlation


【解决方案1】:

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

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

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

接下来使用gzip使用这个命令解压文件:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    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']))
    

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

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

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 2018-10-23
      • 2018-11-16
      • 2017-09-07
      • 2020-04-23
      相关资源
      最近更新 更多