57

如何计算出文本数据的相似矩阵?

 4 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzI1MTE2ODg4MA%3D%3D&%3Bmid=2650072588&%3Bidx=1&%3Bsn=9dd071f914ec6f9baba679003167f052
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

今天要计算texts中两两文本计算相似性,生成texts对应的相似矩阵。我们需要先将text转为为向量,texts转化后就是文档-词频矩阵。

texts = ['吃着火锅唱着歌,突然失业了怎么办?',
        '北京今年高考外语口试取消!外语口试费用将全额退还',
        '北京取消外语口试到底怎么回事?',
        '最新:今年北京市统一高考外语口试不再举行',
        '北京市取消2020年高考外语口试',
        '先上岗、再考证!2020年上半年中小学教师资格考试推迟',
        '上万个公司都在用的机器学习服务SageMaker,AWS宣布要在中国推出了']


texts
['吃着火锅唱着歌,突然失业了怎么办?',
 '北京今年高考外语口试取消!外语口试费用将全额退还',
 '北京取消外语口试到底怎么回事?',
 '最新:今年北京市统一高考外语口试不再举行',
 '北京市取消2020年高考外语口试',
 '先上岗、再考证!2020年上半年中小学教师资格考试推迟',
 '上万个公司都在用的机器学习服务SageMaker,AWS宣布要在中国推出了']

中文语料准备

现在有texts,希望将其变成文档词频矩阵,已知有scikit-learn机器学习库可以将英文语料转化为文档词频矩阵。

但并不能直接使用scikit-learn,我们一定要先将中文转为成 类英文形态 ,即词语之间用空格间隔。

转化代码如下

import jieba

corpus = [' '.join(jieba.lcut(text)) 
          for text in texts]


corpus
Building prefix dict from the default dictionary ...
Dumping model to file cache /var/folders/sc/3mnt5tgs419_hk7s16gq61p80000gn/T/jieba.cache
Loading model cost 0.768 seconds.
Prefix dict has been built successfully.





['吃 着 火锅 唱着歌 , 突然 失业 了 怎么办 ?',
 '北京 今年 高考 外语 口试 取消 ! 外语 口试 费用 将 全额 退还',
 '北京 取消 外语 口试 到底 怎么回事 ?',
 '最新 :今年 北京市 统一 高考 外语 口试 不再 举行',
 '北京市 取消 2020 年 高考 外语 口试',
 '先 上岗 、 再 考证 !2020 年 上半年 中小学 教师资格 考试 推迟',
 '上万个 公司 都 在 用 的 机器 学习 服务 SageMaker , AWS 宣布 要 在 中国 推出 了']

生成文档词频矩阵

有了符合scikit-learn输入要求的数据格式,我们就可以很方便的将语料数据转化为中文文档词频矩阵(doc-term-matrix)。

有两种统计词频的方法

  • TfidfVectorizer

  • CountVectorizer

一般情况下用TfidfVectorizer,关于两者区别大家有精力去看一下这篇

如何从文本中提取特征信息?

from sklearn.feature_extraction.text import TfidfVectorizer

tfidf = TfidfVectorizer()
#dtm(doc-term-matrix)
dtm = tfidf.fit_transform(corpus)
dtm
<7x39 sparse matrix of type '<class 'numpy.float64'>'
	with 53 stored elements in Compressed Sparse Row format>

dtm是一个形状为 7*39 矩阵

  • 7  文档数(文本数)

  • 39 词语数(语料中涉及到的词语数)

这里我们看一下tfidf一共发现了39个词,分别是

feature_words = tfidf.get_feature_names()
print(feature_words)
['2020', 'aws', 'sagemaker', '上万个', '上半年', '上岗', '不再', '中国', '中小学', '举行', '今年', '全额', '公司', '到底', '北京', '北京市', '取消', '口试', '唱着歌', '外语', '失业', '学习', '宣布', '怎么办', '怎么回事', '推出', '推迟', '教师资格', '最新', '服务', '机器', '火锅', '突然', '统一', '考证', '考试', '费用', '退还', '高考']

计算文本相似矩阵

现在已经可以确定,我们已经拥有了文档-词频矩阵,

from sklearn.metrics.pairwise import cosine_similarity, pairwise_distances

接下来我们要计算出 7*7 文档相似矩阵(这里我们的测试文本有7条)。

from sklearn.metrics.pairwise import cosine_similarity, pairwise_distances

cos_sim_matrix = cosine_similarity(dtm)

#相似矩阵形状
print(cos_sim_matrix.shape)
print()
print(cos_sim_matrix)
(7, 7)

[[1.         0.         0.         0.         0.         0.
  0.        ]
 [0.         1.         0.4698711  0.362457   0.49069644 0.
  0.        ]
 [0.         0.4698711  1.         0.14816366 0.35816398 0.
  0.        ]
 [0.         0.362457   0.14816366 1.         0.42708997 0.
  0.        ]
 [0.         0.49069644 0.35816398 0.42708997 1.         0.14014411
  0.        ]
 [0.         0.         0.         0.         0.14014411 1.
  0.        ]
 [0.         0.         0.         0.         0.         0.
  1.        ]]
pairwise_sim_matrix = pairwise_distances(dtm)

print(pairwise_sim_matrix.shape)
print()
print(pairwise_sim_matrix)
(7, 7)

[[0.         1.41421356 1.41421356 1.41421356 1.41421356 1.41421356
  1.41421356]
 [1.41421356 0.         1.02968821 1.12919706 1.00926068 1.41421356
  1.41421356]
 [1.41421356 1.02968821 0.         1.30524813 1.13299252 1.41421356
  1.41421356]
 [1.41421356 1.12919706 1.30524813 0.         1.07042985 1.41421356
  1.41421356]
 [1.41421356 1.00926068 1.13299252 1.07042985 0.         1.31137782
  1.41421356]
 [1.41421356 1.41421356 1.41421356 1.41421356 1.31137782 0.
  1.41421356]
 [1.41421356 1.41421356 1.41421356 1.41421356 1.41421356 1.41421356
  0.        ]]

pairwise_distances方法是 cosine_similarity减1后取绝对值得到的。

将相似矩阵存到txt中

计算得到的cos_sim_matrix和pairwise_sim_matrix是numpy中的array数据类型,可以使用numpy.savetxt函数将矩阵信息存储到txt中。

当然到这一步,也可以想办法存到别的文件格式中

import numpy as np

np.savetxt('cos_sim_matrix.txt', cos_sim_matrix)
np.savetxt('pairwise_sim_matrix.txt', pairwise_sim_matrix)

读取txt中的相似矩阵

如果后续需要在python中分析,可能需要用到数据读取。

import numpy as np

matrix = np.loadtxt('cos_sim_matrix.txt')
matrix
array([[1.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        ],
       [0.        , 1.        , 0.4698711 , 0.362457  , 0.49069644,
        0.        , 0.        ],
       [0.        , 0.4698711 , 1.        , 0.14816366, 0.35816398,
        0.        , 0.        ],
       [0.        , 0.362457  , 0.14816366, 1.        , 0.42708997,
        0.        , 0.        ],
       [0.        , 0.49069644, 0.35816398, 0.42708997, 1.        ,
        0.14014411, 0.        ],
       [0.        , 0.        , 0.        , 0.        , 0.14014411,
        1.        , 0.        ],
       [0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 1.        ]])

公众号后台回复关键词 相似矩阵 , 可 获得该数据集

往期文章

中文文本分析相关资源汇总

cnsenti中文情绪情感分析库

70G上市公司定期报告数据集

两行代码读取pdf、docx文件

三行代码计算文本相似性

5个小问题带你理解列表推导式

文本数据清洗之正则表达式

Python网络爬虫与文本数据分析

综述:文本分析在市场营销研究中的应用

LabelStudio多媒体数据标注工具[5星推荐]

如何批量下载上海证券交易所上市公司年报

Loughran&McDonald金融文本情感分析库

如何使用Python快速构建领域内情感词典

Python数据分析相关学习资源汇总帖

漂亮~pandas可以无缝衔接Bokeh

YelpDaset: 酒店管理类数据集10+G

看在这么多数据面子上,给我点好看可好❤


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK