MCPcopy Index your code
hub / github.com/clips/pattern / Vector

Class Vector

pattern/vector/__init__.py:612–657  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

610# sum(len(d.vector) for d in model.documents) / float(len(model))
611
612class Vector(readonlydict):
613
614 id = 1
615
616 def __init__(self, *args, **kwargs):
617 """ A dictionary of (feature, weight)-items of the features (terms, words) in a Document.
618 A vector can be used to compare the document to another document with a distance metric.
619 For example, vectors with 2 features (x, y) can be compared using 2D Euclidean distance.
620 Vectors that represent text documents can be compared using cosine similarity.
621 """
622 self.id = Vector.id; Vector.id+=1 # Unique ID.
623 self.weight = kwargs.pop("weight", TF) # Vector weights based on tf, tf-idf, binary?
624 self._norm = None
625 readonlydict.__init__(self, *args, **kwargs)
626
627 @property
628 def features(self):
629 return self.keys()
630
631 @property
632 def l2_norm(self):
633 """ Yields the Frobenius matrix norm (cached).
634 n = the square root of the sum of the absolute squares of the values.
635 The matrix norm is used to normalize (0.0-1.0) cosine similarity between documents.
636 """
637 if self._norm is None:
638 self._norm = sum(w * w for w in self.itervalues()) ** 0.5
639 return self._norm
640
641 norm = l2 = L2 = L2norm = l2norm = L2_norm = l2_norm
642
643 def copy(self):
644 return Vector(self, weight=self.weight)
645
646 def __call__(self, vector={}):
647 """ Vector(vector) returns a new vector updated with values from the given vector.
648 No new features are added. For example: Vector({1:1, 2:2})({1:0, 3:3}) => {1:0, 2:2}.
649 """
650 if isinstance(vector, (Document, Model)):
651 vector = vector.vector
652 v = self.copy()
653 s = dict.__setitem__
654 for f, w in vector.iteritems():
655 if f in v:
656 s(v, f, w)
657 return v
658
659#--- VECTOR DISTANCE -------------------------------------------------------------------------------
660# The "distance" between two vectors can be calculated using different metrics.

Callers 8

__init__Method · 0.70
vectorMethod · 0.70
copyMethod · 0.70
vectorMethod · 0.70
__init__Method · 0.70
transformMethod · 0.70
centroidFunction · 0.70
_vectorMethod · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…