MCPcopy Create free account
hub / github.com/clips/pattern / similarity

Method similarity

pattern/graph/commonsense.py:155–181  ·  view source on GitHub ↗

Returns the similarity of the given concepts, by cross-comparing shortest path distance between k concept properties. A given concept can also be a flat list of properties, e.g. ["creepy"]. The given heuristic is a tuple of two functions: 1) function(

(self, concept1, concept2, k=3, heuristic=COMMONALITY)

Source from the content-addressed store, hash-verified

153 Graph.remove(self, x)
154
155 def similarity(self, concept1, concept2, k=3, heuristic=COMMONALITY):
156 """ Returns the similarity of the given concepts,
157 by cross-comparing shortest path distance between k concept properties.
158 A given concept can also be a flat list of properties, e.g. ["creepy"].
159 The given heuristic is a tuple of two functions:
160 1) function(concept) returns a list of salient properties,
161 2) function(edge) returns the cost for traversing this edge (0.0-1.0).
162 """
163 if isinstance(concept1, basestring):
164 concept1 = self[concept1]
165 if isinstance(concept2, basestring):
166 concept2 = self[concept2]
167 if isinstance(concept1, Node):
168 concept1 = heuristic[0](concept1)
169 if isinstance(concept2, Node):
170 concept2 = heuristic[0](concept2)
171 if isinstance(concept1, list):
172 concept1 = [isinstance(n, Node) and n or self[n] for n in concept1]
173 if isinstance(concept2, list):
174 concept2 = [isinstance(n, Node) and n or self[n] for n in concept2]
175 h = lambda id1, id2: heuristic[1](self.edge(id1, id2))
176 w = 0.0
177 for p1 in concept1[:k]:
178 for p2 in concept2[:k]:
179 p = self.shortest_path(p1, p2, heuristic=h)
180 w += 1.0 / (p is None and 1e10 or len(p))
181 return w / k
182
183 def nearest_neighbors(self, concept, concepts=[], k=3):
184 """ Returns the k most similar concepts from the given list.

Callers 8

nearest_neighborsMethod · 0.95
test_similarityMethod · 0.95
test_synsetMethod · 0.45
test_similarityMethod · 0.45
02-model.pyFile · 0.45
06-commonsense.pyFile · 0.45
06-wordnet.pyFile · 0.45

Calls 3

lenFunction · 0.85
shortest_pathMethod · 0.80
edgeMethod · 0.45

Tested by 4

test_similarityMethod · 0.76
test_synsetMethod · 0.36
test_similarityMethod · 0.36