Python 数据科学指南 1.5使用集合

集合:不能存在重复值,是无序同类元素的集合,通常情况下,集合被用来删除列表中的重复值。

操作:集合支持交集、并集、差集和对称差等操作。

一、示例代码:

# --encoding:utf-8--
#1.初始化两个句子
st_1 = "dogs chase cats"
st_2 = "dogs hate cats"

#2.从字符串中创建词的集合,st_1.split()返回列表,我们将其传递给set()函数,去重,并获取集合对象。
st_1_wrds = set(st_1.split())
st_2_wrds = set(st_2.split())

#3.找出每个集合中不重复的词总数,即词表大小
no_wrds_st_1 = len(st_1_wrds)
no_wrds_st_2 = len(st_2_wrds)

#4.找出两个集合中共有的词,保存到列表中,并统计总数
cmn_wrds = st_1_wrds.intersection(st_2_wrds)
no_cmn_wrds = len(st_1_wrds.intersection(st_2_wrds))

#5.找出两个集合并集中不重复的值,保存到列表中,并统计总数
#union是将两个集合进行并集,并将不重复的那些词列出来。这在自然语言处理中被称为词表。
unq_wrds = st_1_wrds.union(st_2_wrds)
no_unq_wrds = len(st_1_wrds.union(st_2_wrds))

#6.计算Jaccard相似度
similarity = no_cmn_wrds / (1.0 * no_unq_wrds)

#7.打印输出
print ("No words in sent_1 = %d"%(no_wrds_st_1))
print ("Sentence 1 word = ",st_1_wrds)
print ("No words in sent_2 =%d"%(no_wrds_st_2))
print ("Sentence 2 words=",st_2_wrds)
print ("No words in common =%d"%(no_cmn_wrds))
print ("Common words = ",cmn_wrds)
print ("Total unique words =%d"%(no_unq_wrds))
print ("Unique words=",unq_wrds)
print ("Similarity = No words in common/No unique words,%d/%d=%.2f"%(no_cmn_wrds,no_unq_wrds,similarity))

 

二、输出结果:

No words in sent_1 = 3

Sentence 1 word =  {'dogs', 'cats', 'chase'}

No words in sent_2 =3

Sentence 2 words= {'dogs', 'hate', 'cats'}

No words in common =2

Common words =  {'dogs', 'cats'}

Total unique words =4

Unique words= {'dogs', 'hate', 'cats', 'chase'}

Similarity = No words in common/No unique words,2/4=0.50

 

三、工作原理

第一步:通过set()函数,将元组或列表转换为集合类型。该过程会丢弃重复元素,并返回一个集合对象。

例如:>>> a=(1,2,1) #元组->集合

>>>set(a)

set([1,2])

>>>b=[1,2,1] #列表->集合

>>>set(b)

set([1,2])

第二步:采用Jaccard系数计算两个句子之间的相似度。具体采用intersection()和union()函数对集合进行操作,来计算相似度。

Jaccard=两个集合共有的词数量/两个集合并集中不重复的词总数

 

四、内容扩展

1.从scikit-learn之类的库中使用内置函数。我们可以尽可能多的使用这些函数,而不必亲自写那些集合的应用函数。

示例代码:

# --encoding:utf-8--
#加载库
from sklearn.metrics import jaccard_similarity_score

#1.初始化两个句子
st_1 = "dogs chase cats"
st_2 = "dogs hate cats"

#2.从字符串中创建词的集合
st_1_wrds = set(st_1.split())
st_2_wrds = set(st_2.split())

unq_wrds = st_1_wrds.union(st_2_wrds)

a=[1 if w in st_1_wrds else 0 for w in unq_wrds]
b=[1 if w in st_2_wrds else 0 for w in unq_wrds]

print (a)
print (b)
print (jaccard_similarity_score(a,b))

输出结果:

[1, 0, 1, 1]

[1, 1, 0, 1]

0.5

注意:输出结果前两行,每次运行,0的位置可能会不一致,原因在于union对两个集合取并集时,集合是无序的,每次运行出来各个单词所在的位置都不一致,因此在最后判断a(或b)中某个单词不存在时,0的位置也会不一致。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值