从技术上讲,如果没有虚拟根,car 和 automobile 同义词集将没有相互链接:
>>> from nltk.corpus import wordnet as wn
>>> x = wn.synset('car.n.01')
>>> y = wn.synset('automobile.v.01')
>>> print x.shortest_path_distance(y)
None
>>> print y.shortest_path_distance(x)
None
现在,让我们仔细看看虚拟根问题。首先,NLTK 中有一个简洁的函数可以说明同义词集是否需要虚拟根:
>>> x._needs_root()
False
>>> y._needs_root()
True
接下来,当你查看path_similarity代码(http://nltk.googlecode.com/svn-/trunk/doc/api/nltk.corpus.reader.wordnet-pysrc.html#Synset.path_similarity)时,你可以看到:
def path_similarity(self, other, verbose=False, simulate_root=True):
distance = self.shortest_path_distance(other, \
simulate_root=simulate_root and self._needs_root())
if distance is None or distance < 0:
return None
return 1.0 / (distance + 1)
所以对于automobile synset,当您尝试y.path_similarity(x) 时,此参数simulate_root=simulate_root and self._needs_root() 将始终为True,而当您尝试x.path_similarity(y) 时,它将始终为False,因为x._needs_root() 是False:
>>> True and y._needs_root()
True
>>> True and x._needs_root()
False
现在当path_similarity() 传递给shortest_path_distance() (https://nltk.googlecode.com/svn/trunk/doc/api/nltk.corpus.reader.wordnet-pysrc.html#Synset.shortest_path_distance) 然后传递给hypernym_distances() 时,它将尝试调用上位词列表来检查它们的距离,没有simulate_root = True,automobile synset 不会连接到car,反之亦然:
>>> y.hypernym_distances(simulate_root=True)
set([(Synset('automobile.v.01'), 0), (Synset('*ROOT*'), 2), (Synset('travel.v.01'), 1)])
>>> y.hypernym_distances()
set([(Synset('automobile.v.01'), 0), (Synset('travel.v.01'), 1)])
>>> x.hypernym_distances()
set([(Synset('object.n.01'), 8), (Synset('self-propelled_vehicle.n.01'), 2), (Synset('whole.n.02'), 8), (Synset('artifact.n.01'), 7), (Synset('physical_entity.n.01'), 10), (Synset('entity.n.01'), 11), (Synset('object.n.01'), 9), (Synset('instrumentality.n.03'), 5), (Synset('motor_vehicle.n.01'), 1), (Synset('vehicle.n.01'), 4), (Synset('entity.n.01'), 10), (Synset('physical_entity.n.01'), 9), (Synset('whole.n.02'), 7), (Synset('conveyance.n.03'), 5), (Synset('wheeled_vehicle.n.01'), 3), (Synset('artifact.n.01'), 6), (Synset('car.n.01'), 0), (Synset('container.n.01'), 4), (Synset('instrumentality.n.03'), 6)])
所以理论上,正确的path_similarity是0 / None,但是因为simulate_root=simulate_root and self._needs_root()参数,
NLTK API 中的nltk.corpus.wordnet.path_similarity() 不可交换。
但是代码也没有错误/错误,因为通过根来比较任何同义词集距离将一直很远,因为虚拟*ROOT* 的位置永远不会改变,所以最好的做法是这样做计算路径相似度:
>>> from nltk.corpus import wordnet as wn
>>> x = wn.synset('car.n.01')
>>> y = wn.synset('automobile.v.01')
# When you NEVER want a non-zero value, since going to
# the *ROOT* will always get you some sort of distance
# from synset x to synset y
>>> max(wn.path_similarity(x,y), wn.path_similarity(y,x))
# when you can allow None in synset similarity comparison
>>> min(wn.path_similarity(x,y), wn.path_similarity(y,x))