Similarity measurement based on Gaussian Distribution
504661
def _high_dim_sim(self, v, w, normalize=False, X=None, idx=0):
        """"""

        sim = np.exp((-np.linalg.norm(v - w) ** 2) / (2*self._sigma[idx] ** 2))

        if normalize:
            return sim / sum(map(lambda x: x[1], self._knn(idx, X, high_dim=True)))
        else:
            return sim
883429
def distance_function_match(l1, l2, thresh, dist_fn, norm_funcs=[]):
    """"""
    common = []
    # We will keep track of the global index in the source list as we
    # will successively reduce their sizes.
    l1 = list(enumerate(l1))
    l2 = list(enumerate(l2))

    # Use the distance function and threshold on hints given by normalization.
    # See _match_by_norm_func for implementation details.
    # Also wrap the list element function function to ignore the global list
    # index computed above.
    for norm_fn in norm_funcs:
        new_common, l1, l2 = _match_by_norm_func(
                l1, l2,
                lambda a: norm_fn(a[1]),
                lambda a1, a2: dist_fn(a1[1], a2[1]),
                thresh)
        # Keep only the global list index in the end result.
        common.extend((c1[0], c2[0]) for c1, c2 in new_common)

    # Take any remaining umatched entries and try to match them using the
    # Munkres algorithm.
    dist_matrix = [[dist_fn(e1, e2) for i2, e2 in l2] for i1, e1 in l1]

    # Call Munkres on connected components on the remaining bipartite graph.
    # An edge links an element from l1 with an element from l2 only if
    # the distance between the elements is less (or equal) than the theshold.
    components = BipartiteConnectedComponents()
    for l1_i in range(len(l1)):
        for l2_i in range(len(l2)):
            if dist_matrix[l1_i][l2_i] > thresh:
                continue
            components.add_edge(l1_i, l2_i)

    for l1_indices, l2_indices in components.get_connected_components():
        # Build a partial distance matrix for each connected component.
        part_l1 = [l1[i] for i in l1_indices]
        part_l2 = [l2[i] for i in l2_indices]

        part_dist_matrix = [[dist_matrix[l1_i][l2_i] for l2_i in l2_indices]
                            for l1_i in l1_indices]
        part_cmn = _match_munkres(part_l1, part_l2, part_dist_matrix, thresh)

        common.extend((c1[0], c2[0]) for c1, c2 in part_cmn)

    return common
932682
def Similarity(self, value=None):  # pylint: disable=C0103
        """"""
        if value is None:
            value = 0.0
        return Similarity(value, threshold=self.threshold)
130339
def findAllMatches(self, needle, similarity):
        
        positions = []
        method = cv2.TM_CCOEFF_NORMED

        match = cv2.matchTemplate(self.haystack, self.needle, method)

        indices = (-match).argpartition(100, axis=None)[:100] # Review the 100 top matches
        unraveled_indices = numpy.array(numpy.unravel_index(indices, match.shape)).T
        for location in unraveled_indices:
            y, x = location
            confidence = match[y][x]
            if method == cv2.TM_SQDIFF_NORMED or method == cv2.TM_SQDIFF:
                if confidence <= 1-similarity:
                    positions.append(((x, y), confidence))
            else:
                if confidence >= similarity:
                    positions.append(((x, y), confidence))

        positions.sort(key=lambda x: (x[0][1], x[0][0]))
        return positions
1026667
public List<Similarity> similar(Image object, double threshold) {
        //return getDatastore().find(Similarity.class).field("firstObject").equal(object).order("similarityScore").asList();
        Query<Similarity> q = getDatastore().createQuery(Similarity.class);
        q.or(
                q.criteria("firstObject").equal(object),
                q.criteria("secondObject").equal(object)
        );
        return q.order("-similarityScore").filter("similarityScore >", threshold).asList();
    }
261487
public function similarity(&$A, &$B)
    {
        $alpha = $this->alpha;
        $beta = $this->beta;

        $a = array_fill_keys($A,1);
        $b = array_fill_keys($B,1);

        $min = min(count(array_diff_key($a,$b)),count(array_diff_key($b, $a)));
        $max = max(count(array_diff_key($a,$b)),count(array_diff_key($b, $a)));

        $intersect = count(array_intersect_key($a,$b));

        return $intersect/($intersect + ($beta * ($alpha * $min + $max*(1-$alpha)) ));
    }
1217312
def similarities(string_a, *string_b)
      [*string_b].map { |word| [word, matches[word] = similarity(string_a, word)] }
    end
774039
def similarity(
        M_c, X_L_list, X_D_list, given_row_id, target_row_id,
        target_column=None):
    
    score = 0.0

    # Set col_idxs: defaults to all columns.
    if target_column:
        if type(target_column) == str:
            col_idxs = [M_c['name_to_idx'][target_column]]
        elif type(target_column) == list:
            col_idxs = target_column
        else:
            col_idxs = [target_column]
    else:
        col_idxs = M_c['idx_to_name'].keys()
    col_idxs = [int(col_idx) for col_idx in col_idxs]

    ## Iterate over all latent states.
    for X_L, X_D in zip(X_L_list, X_D_list):
        for col_idx in col_idxs:
            view_idx = X_L['column_partition']['assignments'][col_idx]
            if X_D[view_idx][given_row_id] == X_D[view_idx][target_row_id]:
                score += 1.0

    return score / (len(X_L_list)*len(col_idxs))
644462
def fit(self, weighted, show_progress=True):
        
        self.similarity = all_pairs_knn(weighted, self.K,
                                        show_progress=show_progress,
                                        num_threads=self.num_threads).tocsr()
        self.scorer = NearestNeighboursScorer(self.similarity)
1107273
public IMatrix similar(IMatrix U) {
        IMatrix result = new IMatrix(rows, columns);
        similar(U, result);
        return result;
    }
640727
def similarity(word1: str, word2: str) -> float:
    
    return _MODEL.similarity(word1, word2)
1221541
def get_diversity(self,X):
        """"""
        # diversity in terms of cosine distances between features
        feature_correlations = np.zeros(X.shape[0]-1)
        for i in np.arange(1,X.shape[0]-1):
            feature_correlations[i] = max(0.0,r2_score(X[0],X[i]))
        # pdb.set_trace()
        self.diversity.append(1-np.mean(feature_correlations))
88795
@Override
    public double similarity(int vertexIdx1, int vertexIdx2) {
        if (vertexIdx1 == vertexIdx2)
            return 1.0;

        INDArray vector = Transforms.unitVec(getVertexVector(vertexIdx1));
        INDArray vector2 = Transforms.unitVec(getVertexVector(vertexIdx2));
        return Nd4j.getBlasWrapper().dot(vector, vector2);
    }
563087
def vector_similarity(self, vector, items):
        """"""
        vector = self.normalize(vector)
        items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
        return vector.dot(items_vec.T)
24694
def get_similar(self, limit=None):
        """"""

        params = self._get_params()
        if limit:
            params["limit"] = limit

        doc = self._request(self.ws_prefix + ".getSimilar", True, params)

        names = _extract_all(doc, "name")
        matches = _extract_all(doc, "match")

        artists = []
        for i in range(0, len(names)):
            artists.append(
                SimilarItem(Artist(names[i], self.network), _number(matches[i]))
            )

        return artists
1148735
def feed_forward_gaussian_fun(action_space, config, observations):
  """"""
  if not isinstance(action_space, gym.spaces.box.Box):
    raise ValueError("Expecting continuous action space.")

  mean_weights_initializer = tf.initializers.variance_scaling(
      scale=config.init_mean_factor)
  logstd_initializer = tf.random_normal_initializer(config.init_logstd, 1e-10)

  flat_observations = tf.reshape(observations, [
      tf.shape(observations)[0], tf.shape(observations)[1],
      functools.reduce(operator.mul, observations.shape.as_list()[2:], 1)])

  with tf.variable_scope("network_parameters"):
    with tf.variable_scope("policy"):
      x = flat_observations
      for size in config.policy_layers:
        x = tf.layers.dense(x, size, activation=tf.nn.relu)
      mean = tf.layers.dense(
          x, action_space.shape[0], activation=tf.tanh,
          kernel_initializer=mean_weights_initializer)
      logstd = tf.get_variable(
          "logstd", mean.shape[2:], tf.float32, logstd_initializer)
      logstd = tf.tile(
          logstd[None, None],
          [tf.shape(mean)[0], tf.shape(mean)[1]] + [1] * (mean.shape.ndims - 2))
    with tf.variable_scope("value"):
      x = flat_observations
      for size in config.value_layers:
        x = tf.layers.dense(x, size, activation=tf.nn.relu)
      value = tf.layers.dense(x, 1)[..., 0]
  mean = tf.check_numerics(mean, "mean")
  logstd = tf.check_numerics(logstd, "logstd")
  value = tf.check_numerics(value, "value")

  policy = tfp.distributions.MultivariateNormalDiag(mean, tf.exp(logstd))

  return NetworkOutput(policy, value, lambda a: tf.clip_by_value(a, -2., 2))
391973
def semantic_similarity(go_id1, go_id2, godag, branch_dist=None):
    '''
        
    '''
    dist = semantic_distance(go_id1, go_id2, godag, branch_dist)
    if dist is not None:
        return 1.0 / float(dist)