基于sklearn.decomposition.TruncatedSVD的潜在语义分析实践

文章目录

    • 1. sklearn.decomposition.TruncatedSVD
    • 2. sklearn.feature_extraction.text.TfidfVectorizer
    • 3. 代码实践
    • 4. 参考文献

《统计学习方法》潜在语义分析(Latent Semantic Analysis,LSA) 笔记

1. sklearn.decomposition.TruncatedSVD

sklearn.decomposition.TruncatedSVD 官网介绍

class sklearn.decomposition.TruncatedSVD(n_components=2,
algorithm='randomized', n_iter=5, random_state=None, tol=0.0)

主要参数:

  • n_components: default = 2,话题数量

  • algorithm: default = “randomized”,算法选择

  • n_iter: optional (default 5),迭代次数
    Number of iterations for randomized SVD solver. Not used by ARPACK.

属性:

  • components_, shape (n_components, n_features)

  • explained_variance_, shape (n_components,)
    The variance of the training samples transformed by a projection to each component.

  • explained_variance_ratio_, shape (n_components,)
    Percentage of variance explained by each of the selected components.

  • singular_values_, shape (n_components,)
    The singular values corresponding to each of the selected components.

2. sklearn.feature_extraction.text.TfidfVectorizer

sklearn.feature_extraction.text.TfidfVectorizer 官网介绍
将原始文档集合转换为TF-IDF矩阵

class sklearn.feature_extraction.text.TfidfVectorizer(input='content',
encoding='utf-8', decode_error='strict', strip_accents=None,
lowercase=True, preprocessor=None, tokenizer=None, analyzer='word', 
stop_words=None, token_pattern='(?u)\b\w\w+\b', ngram_range=(1, 1), 
max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False, 
dtype=<class 'numpy.float64'>, norm='l2', use_idf=True, smooth_idf=True, 
sublinear_tf=False)

参数介绍 这个博客 写的很清楚。

from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ['This is the first document.','This document is the second document.','And this is the third one.','Is this the first document?',
]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())
print(X.shape)
print(X)
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
(4, 9)(0, 8)	0.38408524091481483(0, 3)	0.38408524091481483(0, 6)	0.38408524091481483(0, 2)	0.5802858236844359(0, 1)	0.46979138557992045(1, 8)	0.281088674033753(1, 3)	0.281088674033753(1, 6)	0.281088674033753(1, 1)	0.6876235979836938(1, 5)	0.5386476208856763(2, 8)	0.267103787642168(2, 3)	0.267103787642168(2, 6)	0.267103787642168(2, 0)	0.511848512707169(2, 7)	0.511848512707169(2, 4)	0.511848512707169(3, 8)	0.38408524091481483(3, 3)	0.38408524091481483(3, 6)	0.38408524091481483(3, 2)	0.5802858236844359(3, 1)	0.46979138557992045

3. 代码实践

# -*- coding:utf-8 -*-
# @Python Version: 3.7
# @Time: 2020/5/1 10:27
# @Author: Michael Ming
# @Website: https://michael.blog.csdn.net/
# @File: 17.LSA.py
# @Reference: https://cloud.tencent.com/developer/article/1530432
import numpy as np
from sklearn.decomposition import TruncatedSVD  # LSA 潜在语义分析
from sklearn.feature_extraction.text import TfidfVectorizer  # 将文本集合转成权值矩阵# 5个文档
docs = ["Love is patient, love is kind. It does not envy, it does not boast, it is not proud.","It does not dishonor others, it is not self-seeking, it is not easily angered, it keeps no record of wrongs.","Love does not delight in evil but rejoices with the truth.","It always protects, always trusts, always hopes, always perseveres.","Love never fails. But where there are prophecies, they will cease; where there are tongues, \they will be stilled; where there is knowledge, it will pass away. (1 Corinthians 13:4-8 NIV)"]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(docs)  # 转成权重矩阵
print("--------转成权重---------")
print(X)
print("--------获取特征(单词)---------")
words = vectorizer.get_feature_names()
print(words)
print(len(words), "个特征(单词)")  # 52个单词topics = 4
lsa = TruncatedSVD(n_components=topics)  # 潜在语义分析,设置4个话题
X1 = lsa.fit_transform(X)  # 训练并进行转化
print("--------lsa奇异值---------")
print(lsa.singular_values_)
print("--------5个文本,在4个话题向量空间下的表示---------")
print(X1)  # 5个文本,在4个话题向量空间下的表示pick_docs = 2  # 每个话题挑出2个最具代表性的文档
topic_docid = [X1[:, t].argsort()[:-(pick_docs + 1):-1] for t in range(topics)]
# argsort,返回排序后的序号
print("--------每个话题挑出2个最具代表性的文档---------")
print(topic_docid)# print("--------lsa.components_---------")
# print(lsa.components_)  # 4话题*52单词,话题向量空间
pick_keywords = 3  # 每个话题挑出3个关键词
topic_keywdid = [lsa.components_[t].argsort()[:-(pick_keywords + 1):-1] for t in range(topics)]
print("--------每个话题挑出3个关键词---------")
print(topic_keywdid)print("--------打印LSA分析结果---------")
for t in range(topics):print("话题 {}".format(t))print("\t 关键词:{}".format(", ".join(words[topic_keywdid[t][j]] for j in range(pick_keywords))))for i in range(pick_docs):print("\t\t 文档{}".format(i))print("\t\t", docs[topic_docid[t][i]])

运行结果

--------转成权重---------(0, 24)	0.3031801002944161(0, 19)	0.4547701504416241(0, 32)	0.2263512201359201(0, 22)	0.2263512201359201(0, 20)	0.3825669873635752(0, 12)	0.3031801002944161(0, 28)	0.4547701504416241(0, 14)	0.2263512201359201(0, 6)	0.2263512201359201(0, 36)	0.2263512201359201(1, 19)	0.28327311337182914(1, 20)	0.4765965465346523(1, 12)	0.14163655668591457(1, 28)	0.42490967005774366(1, 11)	0.21148886348790247(1, 30)	0.21148886348790247(1, 40)	0.21148886348790247(1, 39)	0.21148886348790247(1, 13)	0.21148886348790247(1, 2)	0.21148886348790247(1, 21)	0.21148886348790247(1, 27)	0.21148886348790247(1, 37)	0.21148886348790247(1, 29)	0.21148886348790247(1, 51)	0.21148886348790247:	:(3, 46)	0.22185332169737518(3, 17)	0.22185332169737518(3, 33)	0.22185332169737518(4, 24)	0.09483932399667956(4, 19)	0.09483932399667956(4, 20)	0.0797818291938777(4, 7)	0.1142518110942895(4, 25)	0.14161217495916(4, 16)	0.14161217495916(4, 48)	0.42483652487747997(4, 43)	0.42483652487747997(4, 3)	0.28322434991832(4, 34)	0.14161217495916(4, 44)	0.28322434991832(4, 49)	0.42483652487747997(4, 8)	0.14161217495916(4, 45)	0.14161217495916(4, 5)	0.14161217495916(4, 41)	0.14161217495916(4, 23)	0.14161217495916(4, 31)	0.14161217495916(4, 4)	0.14161217495916(4, 9)	0.14161217495916(4, 0)	0.14161217495916(4, 26)	0.14161217495916
--------获取特征(单词)---------
['13', 'always', 'angered', 'are', 'away', 'be', 'boast', 'but', 'cease', 'corinthians', 'delight', 'dishonor', 'does', 'easily', 'envy', 'evil', 'fails', 'hopes', 'in', 'is', 'it', 'keeps', 'kind', 'knowledge', 'love', 'never', 'niv', 'no', 'not', 'of', 'others', 'pass', 'patient', 'perseveres', 'prophecies', 'protects', 'proud', 'record', 'rejoices', 'seeking', 'self', 'stilled', 'the', 'there', 'they', 'tongues', 'trusts', 'truth', 'where', 'will', 'with', 'wrongs']
52 个特征(单词)
--------lsa奇异值---------
[1.29695724 1.00165234 0.98752651 0.94862686]
--------5个文本,在4个话题向量空间下的表示---------
[[ 0.85667347 -0.00334881 -0.11274158 -0.14912237][ 0.80868148  0.09220662 -0.16057627 -0.33804609][ 0.46603522 -0.3005665  -0.06851382  0.82322097][ 0.13423034  0.92315127  0.22573307  0.2806665 ][ 0.24297388 -0.22857306  0.9386499  -0.08314939]]
--------每个话题挑出2个最具代表性的文档---------
[array([0, 1], dtype=int64), array([3, 1], dtype=int64), array([4, 3], dtype=int64), array([2, 3], dtype=int64)]
--------每个话题挑出3个关键词---------
[array([28, 20, 19], dtype=int64), array([ 1, 46, 33], dtype=int64), array([49, 48, 43], dtype=int64), array([10, 42, 18], dtype=int64)]
--------打印LSA分析结果---------
话题 0关键词:not, it, is文档0Love is patient, love is kind. It does not envy, it does not boast, it is not proud.文档1It does not dishonor others, it is not self-seeking, it is not easily angered, it keeps no record of wrongs.
话题 1关键词:always, trusts, perseveres文档0It always protects, always trusts, always hopes, always perseveres.文档1It does not dishonor others, it is not self-seeking, it is not easily angered, it keeps no record of wrongs.
话题 2关键词:will, where, there文档0Love never fails. But where there are prophecies, they will cease; where there are tongues,         they will be stilled; where there is knowledge, it will pass away. (1 Corinthians 13:4-8 NIV)文档1It always protects, always trusts, always hopes, always perseveres.
话题 3关键词:delight, the, in文档0Love does not delight in evil but rejoices with the truth.文档1It always protects, always trusts, always hopes, always perseveres.

4. 参考文献

主要参考了下面作者的文章,表示感谢!
sklearn: 利用TruncatedSVD做文本主题分析

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/475999.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一个简单又高效的日志系统

摘要&#xff1a;本文给出一个性能高&#xff0c;使用简单的日志解决方案。本模块实现日志信息的批量写入文件&#xff0c;定时自动flush到文件中&#xff0c;写入文件的日志级别可动态调整&#xff0c;单个日志文件大小可配置&#xff0c;循环对日志文件写入&#xff0c;这样不…

R语言chorolayer_R语言空间可视化:绘制英国脱欧投票地图

添加法国&#xff0c;它位于右下方&#xff0c;因此我们应该看到一点…plot(FR,addTRUE)然后&#xff0c;我们可以检索英国退欧公投数据referendumddply(referendum,.(Region,HASC_code),summarise,Remainsum(Remain),Leavesum(Leave))我们可以发现&#xff0c;脱欧赢得了51.89…

概率潜在语义分析(Probabilistic Latent Semantic Analysis,PLSA)

文章目录1. 概率潜在语义分析模型1.1 基本想法1.2 生成模型1.3 共现模型1.4 模型性质2. 概率潜在语义分析的算法概率潜在语义分析&#xff08;probabilistic latent semantic analysis&#xff0c;PLSA&#xff09;&#xff0c;也称概率潜在语义索引&#xff08;probabilistic …

网站变成灰色调

为方便站点哀悼&#xff0c;特提供css滤镜代码&#xff0c;以表哀悼。以下为全站CSS代码。html { filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale1); } 使用方法&#xff1a;这段代码可以变网页为黑白&#xff0c;将代码加到CSS最顶端就可以实现素装。建议全国…

马尔可夫链蒙特卡罗法(Markov Chain Monte Carlo,MCMC)

文章目录1. 蒙特卡罗法2. 马尔可夫链3. 马尔可夫链蒙特卡罗法4. Metropolis-Hastings 算法5. 吉布斯抽样蒙特卡罗法&#xff08;Monte Carlo method&#xff09;&#xff0c;也称为统计模拟方法&#xff08;statistical simulation method&#xff09;&#xff0c;是通过从概率…

NHibernate 异常及解决办法(长期添加中)

Mapping 错误&#xff1a; 1&#xff09; Could not determine type for:Namespance.Class,AssemblyName, for columns: NHibernate.Mapping.Column(ColumnName) 通常是Mapping中的 type attribute设定错误&#xff0c;在Assembly找不到。如 <property name"PropertyNa…

mysql scope runtime_maven scope provided和runtime的例子

maven常用的scope有compile,provided,runtime,test。complie是默认值&#xff0c;表示在build,test,runtime阶段的classpath下都有依赖关系。test表示只在test阶段有依赖关系&#xff0c;例如junitprovided表示在build,test阶段都有依赖&#xff0c;在runtime时并不输出依赖关系…

[网站seo优化] 史上最全增加外链的方法!

目前在国内网站在百度的权重尤为重要 百度的权重主要取决于 1&#xff0c;收录量2&#xff0c;外链数与质量3&#xff0c;建站时间 可见外链的重要性现在就分享一篇关于外链的文章&#xff0c;希望对大家有用。 一、网站内容1. 写一篇权威的文章(毫无疑问是获得链接的最好方法…

python自动化安装软件_python自动化安装源码软件包

#!/usr/bin/env python# -*- coding:utf:8 -*-#create by 、矿泉水 2015/7/30import sys,commandsif len(sys.argv) 2:SOFTWARE sys.argv[1]commands.getstatusoutput(‘tar zxvf %s &> install.log 2>&1‘%SOFTWARE)SOFTWARE SOFTWARE.split(‘.‘)SOFTWARE.…

蒙特卡罗法近似求解圆周率π

文章目录1. 原理2. 模拟代码1. 原理 给出 x∈[0,1),y∈[0,1)x \in [0,1),y\in[0,1)x∈[0,1),y∈[0,1) 的均匀分布随机点&#xff0c;模拟 ttt 次&#xff0c;落在以 (0,0)(0,0)(0,0) 为圆心&#xff0c;半径 r1r1r1 的圆以内的次数为 ccc当模拟次数足够大时&#xff0c;可以看成…

算法导论2.3-7

Q: 请给出一个运行时间为θ(nlgn)的算法&#xff0c;使之能在一个由n个整数构成的集合S和另一个整数X时&#xff0c;判断出S中是否存在有两个其和等于X的元素。A: 先对S[1 TO N]进行合并排序--------------------------------θ(nlgn) FOR a <- [1 TO N-1]-----------------…

LeetCode 1318. 或运算的最小翻转次数(位运算)

1. 题目 给你三个正整数 a、b 和 c。 你可以对 a 和 b 的二进制表示进行位翻转操作&#xff0c;返回能够使按位或运算 a OR b c 成立的最小翻转次数。 「位翻转操作」是指将一个数的二进制表示任何单个位上的 1 变成 0 或者 0 变成 1 。 示例 1&#xff1a; 输入&#x…

redis和mysql数据不一致_高并发下为什么 redis 和数据库不一致?怎么解决?

现在的web架构一般都用redis作为缓存层来减轻数据库的压力&#xff0c;数据在此架构下的读取问题&#xff0c;一般都是先判断redis缓存是否有数据&#xff0c;如果有&#xff0c;直接返回&#xff0c;否则读取数据库的数据&#xff0c;写入redis&#xff0c;返回数据&#xff0…

LeetCode 91. 解码方法(动态规划)

1. 题目 一条包含字母 A-Z 的消息通过以下方式进行了编码&#xff1a; A -> 1 B -> 2 ... Z -> 26给定一个只包含数字的非空字符串&#xff0c;请计算解码方法的总数。 示例 1: 输入: "12" 输出: 2 解释: 它可以解码为 "AB"&#xff08;1 2&am…

vim粘贴板和系统粘贴板的共享(linux)

不的不说,当你习惯了vim给你的编程带来乐趣后&#xff0c;你将会越来越喜欢它&#xff01; 在以前刚开始用vim的时候&#xff0c;总觉的在vim里面&#xff0c;鼠标没有起到像其他编辑器那样的功能&#xff0c;不能通过鼠标控制vim下光标移动&#xff0c;而当时又不熟悉vim的移动…

java的vector_java中的Vector类

public class VectorVector 类实现了可动态扩充的对象数组。类似数组&#xff0c;它包含的元素可通过数组下标来访问。但是&#xff0c;在 Vector 创建之后。Vector 可根据增加和删除元素的需要来扩大或缩小。每个向量可通过维护 capacity 和 capacityIncrement 来优化存储空间…

LeetCode 1238. 循环码排列(格雷编码+旋转数组)

1. 题目 给你两个整数 n 和 start。你的任务是返回任意 (0,1,2,,...,2^n-1) 的排列 p&#xff0c;并且满足&#xff1a; p[0] start p[i] 和 p[i1] 的二进制表示形式只有一位不同 p[0] 和 p[2^n -1] 的二进制表示形式也只有一位不同示例 1&#xff1a; 输入&#xff1a;n 2…

java 0 1背包_浅谈java实现背包算法(0-1背包问题)

0-1背包的问题背包问题(Knapsack problem)是一种组合优化的NP完全问题。问题可以描述为:给定一组物品&#xff0c;每种物品都有自己的重量和价格&#xff0c;在限定的总重量内&#xff0c;我们如何选择&#xff0c;才能使得物品的总价格最高。问题的名称来源于如何选择最合适的…

关于Python的应用发布技术

收集如何 将Py应用打包发布的各种技巧: 1.1. 工具 {{{k <yanbo.yuangmail.com> reply-to python-cngooglegroups.com, to python-cngooglegroups.com, date Tue, Apr 1, 2008 at 2:58 PM subject [CPyUG:45605]}}}[http://groups.google.com/group/python-cn/t/24…

LeetCode 第 25 场双周赛(718/1832,前39.2%)

文章目录1. 比赛结果2. 题目1. LeetCode 5384. 拥有最多糖果的孩子 easy2. LeetCode 5385. 改变一个整数能得到的最大差值 medium3. LeetCode 5386. 检查一个字符串是否可以打破另一个字符串 medium4. LeetCode 5387. 每个人戴不同帽子的方案数 hard1. 比赛结果 做出来了 1、2…