当前位置:网站首页>数据科学【九】:SVD(二)
数据科学【九】:SVD(二)
2022-07-02 06:10:00 【swy_swy_swy】
数据科学【九】:SVD(二)
数据准备
我们这次研究文本数据。我们可以从sklearn.datasets获得fetch_20newsgroups,即20个不同范畴的新闻文本集;这里我们选取四个范畴。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.stem.snowball import SnowballStemmer
categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']
news_data = fetch_20newsgroups(subset='train', categories=categories)
分词
每一篇文章可视为一个字符串。这个字符串由空格、换行符以及词组成。需要注意的是,同一个词可能有多种变形,比如时态、复数、变格等等,视语言而定。从诸多变形中“提取”词语,即为分词。我们可以调用SnowballStemmer()实现:
stemmer = SnowballStemmer('english')
stemmed_articles = []
for article in news_data.data:
stemmed_words = []
for word in article.split():
stemmed_words.append(stemmer.stem(word))
stemmed_articles.append(" ".join(stemmed_words))
词的重要性
给定一个词和一个文本集,如何量化这个词的重要性?一个指标是tf-idf特征。tf-idf特征有两部分构成,分别为:
- TF(t, a):词语t在文章a中出现的比率,即t出现的次数/文章总词数。
- IDF(t, s):文章集合的文章数比出现词语t的文章数的对数,即log10(文章总数/出现该词的文章数)
- tf-idf: TF 与IDF的乘积。
通过以上定义,我们知道在一个文本集中,对每一篇文本都有一个特征向量。
我们可以使用from sklearn.feature_extraction.text import TfidfVectorizer来获得tf-idf特征向量。
import pandas as pd
tfidfvctr = TfidfVectorizer(max_df = 0.25, min_df = 0.05)
tfidf_mat = tfidfvctr.fit_transform(stemmed_articles)
tfidf_df = pd.DataFrame(tfidf_mat.toarray())
tfidf_df.to_csv("tfidf.csv", index=False)
对tf-idf使用SVD降维
我们对上文得到的SVD矩阵降维,保留不同秩的特征值,并通过disagreemet distance评价聚类效果。
disagreement_distance = []
original_dataset = pd.read_csv("tfidf.csv", low_memory=False).values
for k in range(1,25):
dim_reduced_dataset = PCA(k).fit_transform(original_dataset)
kmeans = KMeans(n_clusters=4, init='k-means++', max_iter=100, n_init=10, random_state=0)
kmeans.fit_predict(dim_reduced_dataset)
labelsk = kmeans.labels_
disagreement_distance.append(disagreement_dist(labelsk, news_data.target))
plt.plot(range(1,25), disagreement_distance)
plt.ylabel('Disagreement')
plt.xlabel('Dimension')
plt.show()

边栏推荐
- State machine in BGP
- 链表(线性结构)
- ROS create workspace
- In depth understanding of JUC concurrency (II) concurrency theory
- Deep learning classification network -- vggnet
- ROS2----LifecycleNode生命周期节点总结
- ZABBIX server trap command injection vulnerability (cve-2017-2824)
- Step by step | help you easily submit Google play data security form
- Detailed steps of JS foreground parsing of complex JSON data "case: I"
- Common means of modeling: combination
猜你喜欢

500. Keyboard line

日志(常用的日志框架)

Zhuanzhuanben - LAN construction - Notes

ZABBIX server trap command injection vulnerability (cve-2017-2824)

Introduce uview into uni app

经典文献阅读之--SuMa++

Shenji Bailian 3.54-dichotomy of dyeing judgment

Lucene Basics

CNN visualization technology -- detailed explanation of cam & grad cam and concise implementation of pytorch

深入了解JUC并发(二)并发理论
随机推荐
注解和反射详解以及运用
The difference between session and cookies
LeetCode 283. Move zero
Go learning notes integration
WLAN相关知识点总结
MUI底部导航的样式修改
Compte à rebours de 3 jours pour l'inscription à l'accélérateur de démarrage Google Sea, Guide de démarrage collecté à l'avance!
格式校验js
Format check JS
500. Keyboard line
Stc8h8k series assembly and C51 actual combat - digital display ADC, key serial port reply key number and ADC value
Redis key value database [primary]
BGP routing optimization rules and notification principles
Stc8h8k series assembly and C51 actual combat - serial port sending menu interface to select different functions
Use of Arduino wire Library
如何使用MITMPROXy
日志(常用的日志框架)
Invalid operation: Load into table ‘sources_ orderdata‘ failed. Check ‘stl_ load_ errors‘ system table
Comment utiliser mitmproxy
Linkage between esp8266 and stc8h8k single chip microcomputer - Weather Clock