赞
踩
澳大利亚广播公司 ABC 发布的新闻头条数据
导入相关模块:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction import text
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from nltk.tokenize import RegexpTokenizer
from nltk.stem.snowball import SnowballStemmer
%matplotlib inline
读取数据集:数据集下载链接在文章底部
# 读取数据集
data = pd.read_csv("C:/Users/86135/AI/Lesson2/output_2021-08-26-14_37_47/abcnews-date-text(1).csv",error_bad_lines=False,usecols =["headline_text"])
data.head()
data = data.head(10000) # 获取部分数据快速运行,可以尝试修改使用的数据量查看后续的建模效果,不过注意使用的数据越多后续模型训练的时间越长
#print(data.info)# 打印数据信息
通过pandas.DataFrame.duplicated可以查看重复的数据行。具体方法见:DataFrame.duplicated()
# 查看重复的数据行
data[data['headline_text'].duplicated(keep=False)].sort_values('headline_text').head(8)
通过pandas.DataFrame.drop_duplicates 可以查看重复的数据行。具体方法见:DataFrame.drop_duplicates()
# 删除重复行,
data = data.drop_duplicates('headline_text')
进行自然语言处理时,必须将单词转换为机器学习算法可以利用的向量。如果目标是对文本数据进行机器学习建模,例如电影评论或推文或其他任何内容,则需要将文本数据转换为数字。此过程称为“嵌入”或“向量化”。
进行向量化时,请务必记住,它不仅仅是将单个单词变成单个数字。单词可以转换为数字,整个文档就可以转换为向量。向量的维度往往不止一个,而且对于文本数据,向量通常是高维的。这是因为特征数据的每个维度将对应一个单词,而我们所处理的文档通常包含数千个单词。
在信息检索中,tf–idf 或 TFIDF(term frequency–inverse document frequency)是一种数值统计,旨在反映单词对语料库中文档的重要性。在信息检索,文本挖掘和用户建模的搜索中,它通常用作加权因子。 tf-idf 值与单词在文档中出现的次数成正比,同时被单词在语料库中的出现频率所抵消,这有助于调整某些单词通常会更频繁出现的事实。 如今,tf-idf是最流行的术语加权方案之一。在数字图书馆领域,有83%的基于文本的推荐系统使用tf-idf。
搜索引擎经常使用tf–idf加权方案的变体作为在给定用户查询时对文档相关性进行评分和排名的主要工具。tf–idf可成功用于各种领域的停用词过滤,包括文本摘要和分类。
排名函数中最简单的是通过将每个查询词的tf–idf相加得出,许多更复杂的排名函数是此简单模型的变体。
当有TF(词频)和IDF(逆文档频率)后,将这两个词相乘,就能得到一个词的TF-IDF的值。某个词在文章中的TF-IDF越大,那么一般而言这个词在这篇文章的重要性会越高,所以通过计算文章中各个词的TF-IDF,由大到小排序,排在最前面的几个词,就是该文章的关键词
tf-idf算法步骤:
计算词频:
某个词在文章中出现的次数 = p,文章总词数 = n
标准化词频(tf) =
p
/
n
p / n
p/n
计算逆文档频率
此时需要一个语料库来模拟语言的使用环境
逆文档频率(idf) =
log
(
语
料
库
文
档
总
数
/
包
含
该
词
的
文
档
树
+
1
)
\log (语料库文档总数/{包含该词的文档树+1})
log(语料库文档总数/包含该词的文档树+1)
可见一个词越常见,分母就越大,逆文档频率就越小越接近于0,分母+1是为了防止所有文档都不包含该词(防止分母为0)
计算tf-idf
t
f
−
i
d
f
=
词
频
(
t
f
)
∗
逆
文
档
频
率
(
i
d
f
)
tf-idf = 词频(tf) * 逆文档频率(idf)
tf−idf=词频(tf)∗逆文档频率(idf)
TF-IDF优缺点:
TF-IDF的优点是简单快速,而且容易理解。缺点是有时候用词频来衡量文章中的一个词的重要性不够全面,有时候重要的词出现的可能不够多,而且这种计算无法体现位置信息,无法体现词在上下文的重要性。如果要体现词的上下文结构,那么你可能需要使用word2vec算法来支持。
punc = ['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}',"%"]
stop_words = text.ENGLISH_STOP_WORDS.union(punc)
desc = data['headline_text'].values
#print(desc)
vectorizer = TfidfVectorizer(stop_words = stop_words) #类调用
#print(vectorizer)
X = vectorizer.fit_transform(desc) #计算个词语出现的次数
#print(X)
word_features = vectorizer.get_feature_names()#获取词袋中所有文本关键字
#print(word_features)
print(len(word_features))
print(word_features[0:50])
stemming 是将单词还原为词干(即词根形式)的过程。 词根形式不一定是单词本身,而是可以通过连接正确的后缀来生成单词。 例如,“fish”,“fishes”和“fishing”这几个词的词干都是“fish”,这是一个正确的单词。 另一方面,“study”,“studies”和“studying”一词源于“studi”,这不是一个正确的英语单词。
Tokenization 将句子分解为单词和标点符号
stemmer = SnowballStemmer('english')
tokenizer = RegexpTokenizer(r'[a-zA-Z\']+') #按照自己设定的正则表达式来分解句子
wordslist = tokenizer.tokenize(desc[0])
'''
print(wordslist)
for word in wordslist:
print(stemmer.stem(word))
'''
def tokenize(text):
return [stemmer.stem(word) for word in tokenizer.tokenize(text.lower())]
vectorizer2 = TfidfVectorizer(stop_words = stop_words, tokenizer = tokenize)
#print(vectorizer2)
X2 = vectorizer2.fit_transform(desc)
word_features2 = vectorizer2.get_feature_names()
print(len(word_features2))
print(word_features2[:50])
vectorizer3 = TfidfVectorizer(stop_words = stop_words, tokenizer = tokenize, max_features = 1000)
X3 = vectorizer3.fit_transform(desc)
words = vectorizer3.get_feature_names()
print(len(words))
print(words[:50])
随着聚类数k的增大,样本划分会更加的精细,每个簇的聚合程度会逐渐提高,那么误差平方和SSE自然会逐渐变小,并且当k小于真实的簇类数时,由于k的增大会大幅增加每个簇的聚合程度,因此SSE的下降幅度会很大,而当k到达真实聚类数时,再增加k所得到的聚合程度回报会迅速变小,所以SSE的下降幅度会骤减,然后随着k值的继续增大而趋于平缓,也就是说SSE和k的关系类似于手肘的形状,而这个肘部对应的k值就是数据的真实聚类数.因此这种方法被称为手肘法.
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters=i,init='k-means++',max_iter=300,n_init=10,random_state=0)
kmeans.fit(X3)
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.savefig('elbow.png')
plt.show()
效果如图所示:
由于可能产生多个肘点,所以有时候不得不通过反复试验来选择合适数量的簇。下面展示不同数量簇的结果,以找出合适数量的簇。
def MyKMeans(clusters,iters,jobs,datas):
kmeans = KMeans(n_clusters = clusters, n_init = iters, n_jobs = jobs)
kmeans.fit(datas)
# argsort 使用方法详见: https://numpy.org/doc/stable/reference/generated/numpy.argsort.html
common_words = kmeans.cluster_centers_.argsort()[:,-1:-26:-1]
ans = []
for num, centroid in enumerate(common_words):
print(str(num) + ' : ' + ', '.join(words[word] for word in centroid))
MyKMeans(3,20,1,X3)
输出如下:
0 : iraq, plan, govt, new, man, win, say, council, iraqi, claim, charg, warn, report, baghdad, kill, fund, urg, world, water, court, face, nsw, troop, rain, death
1 : polic, probe, man, arrest, search, death, investig, murder, charg, drug, stab, wa, cannabi, station, fatal, car, miss, victim, protest, road, suspect, driver, nt, corrupt, new
2 : war, protest, anti, iraq, howard, ralli, pm, post, say, plan, student, fear, condemn, iraqi, bush, market, thousand, march, downer, warn, deni, start, end, stage, peac
MyKMeans(5,20,1,X3)
输出如下:
0 : polic, man, govt, win, new, council, charg, say, claim, warn, court, report, fund, face, death, baghdad, world, kill, urg, nsw, rain, set, crash, water, cup
1 : iraqi, diplomat, forc, baghdad, expel, coalit, marin, kill, missil, say, war, civilian, bomb, saddam, claim, surrend, suicid, refuge, troop, attack, border, aid, basra, weapon, tv
2 : plan, water, shire, council, park, new, manag, protest, govt, firm, green, begin, group, m, welcom, merger, defend, health, rail, land, farmer, station, burn, concern, union
3 : iraq, war, say, missil, troop, howard, deni, post, bush, destroy, blair, pm, report, bomb, british, attack, forc, kill, turkey, aid, warn, tv, resolut, blix, uk
4 : war, protest, anti, howard, ralli, pm, student, thousand, march, fear, street, condemn, peac, open, say, arrest, melbourn, market, downer, day, warn, start, nz, polic, hous
MyKMeans(8,20,1,X3)
输出如下:
0 : plan, govt, council, iraqi, say, claim, warn, report, baghdad, world, fund, urg, kill, nsw, cup, water, set, crash, troop, lead, final, meet, death, ban, continu
1 : war, protest, anti, howard, ralli, pm, student, plan, iraqi, thousand, fear, say, march, condemn, crean, melbourn, street, market, day, gulf, warn, start, oil, open, stage
2 : polic, man, charg, murder, face, court, probe, stab, death, arrest, search, jail, car, drug, miss, fatal, assault, investig, accid, crash, station, cannabi, sex, wa, attack
3 : iraq, war, say, missil, troop, deni, post, blair, bush, destroy, howard, pm, report, bomb, british, attack, forc, kill, turkey, aid, warn, tv, blix, uk, kuwait
4 : concern, air, aust, strike, rise, toll, worker, pay, death, qld, council, job, baghdad, govt, iraqi, market, teacher, rate, open, cut, saddam, water, group, troop, nz
5 : win, lead, season, fan, m, goal, india, award, open, hope, tiger, championship, world, gold, return, titl, thriller, cup, coast, stage, streak, best, case, celebr, waratah
6 : new, resolut, plan, hope, appoint, ceo, presid, work, open, look, polic, hit, law, high, rate, compani, govt, wa, hospit, servic, iraq, coach, set, board, tas
7 : rain, drought, farmer, water, relief, help, bring, offer, need, qld, boost, fund, restrict, end, toll, break, hope, affect, despit, eas, welcom, impact, nsw, flood, fall
最后,我们可以根据不同簇数量产生的聚类结果,人工判断哪一个聚类的效果最好
数据集:
链接:https://pan.baidu.com/s/1A2eyF7QdoFf0H5Gv92gMaA
提取码:7bk7
–来自百度网盘超级会员V5的分享
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。