def main():
    logging.info("using the gradient")

    _v = [random.randint(-10, 10) for i in range(3)]

    _tolerance = 0.0000001

    while True:
        # print v, sum_of_squares(v)
        _gradient = sum_of_squares_gradient(_v)  # compute the gradient at v
        next_v = step(_v, _gradient, -0.01)  # take a negative gradient step
        if distance(next_v, _v) < _tolerance:  # stop if we're converging
            break
        _v = next_v  # continue if we're not

    logging.info("%r", "minimum v {}".format(_v))
    logging.info("%r", "minimum value {}".format(sum_of_squares(_v)))

    logging.info("using minimize_batch")

    _v = [random.randint(-10, 10) for i in range(3)]

    _v = minimize_batch(sum_of_squares, sum_of_squares_gradient, _v)

    logging.info("%r", "minimum v  = {}".format(_v))
    logging.info("%r", "minimum value = {}".format(sum_of_squares(_v)))
Ejemplo n.º 2
0
def cluster_distance(cluster1, cluster2, distance_agg=min):
    """finds the aggregate distance between elements of cluster1
    and elements of cluster2"""
    return distance_agg([
        distance(input1, input2) for input1 in get_values(cluster1)
        for input2 in get_values(cluster2)
    ])
Ejemplo n.º 3
0
def find_eigenvector(a_matrix, tolerance=0.00001):
    guess = [1 for __ in a_matrix]

    while True:
        result = matrix_operate(a_matrix, guess)
        length = magnitude(result)
        next_guess = scalar_multiply(1 / length, result)

        if distance(guess, next_guess) < tolerance:
            return next_guess, length  # eigenvector, eigenvalue

        guess = next_guess
Ejemplo n.º 4
0
def knn_classify(k, labeled_points, new_point):
    """each labeled point should be a pair (point, label)"""

    # order the labeled points from nearest to farthest
    by_distance = sorted(
        labeled_points,
        key=lambda point_label: distance(point_label[0], new_point))

    # find the labels for the k closest
    k_nearest_labels = [label for _, label in by_distance[:k]]

    # and let them vote
    return majority_vote(k_nearest_labels)
Ejemplo n.º 5
0
def random_distances(dim, num_pairs):
    return [
        distance(random_point(dim), random_point(dim))
        for _ in range(num_pairs)
    ]