示例#1
0
def knn_classify(k, labeled_points, new_point):
	'''each labeled point should be a pair (point, label)'''
	
	#order labeled points from nearest to farthest
	by_distance = sorted(labeled_points, key=lambda x: lin_alg.distance(x[0], new_point))
	
	#find the labels for the k-closest
	k_nearest_labels = [label for _, label in by_distance[:k]]
	
	#let them vote
	return majority_vote(k_nearest_labels)
示例#2
0
def find_eigenvector(A, tolerance=0.00001):
	guess = [random.random() for _ in A]
	
	while True:
		result = lin_alg.matrix_operate(A, guess)
		length = lin_alg.magnitude(result)
		next_guess = lin_alg.scalar_multiply(1/length, result)
		
		if lin_alg.distance(guess, next_guess) < tolerance:
			return next_guess, length #eigenvector, eigenvalue
			
		guess = next_guess