Beispiel #1
0
 def test_arange(self):
     train = np.arange(150).reshape(5, -1)
     test = np.square(np.arange(2, 122)).reshape(4, -1)
     knn = KNearestNeighbor()
     knn.train(train, None)
     d_two = knn.compute_distances_two_loops(test)
     d_one = knn.compute_distances_one_loop(test)
     d_no = knn.compute_distances_no_loops(test)
     self.assertAlmostEqual(0, np.linalg.norm(d_two - d_one, ord='fro'))
     self.assertAlmostEqual(0, np.linalg.norm(d_no - d_one, ord='fro'))
 def test_arange(self):
     train = np.arange(150).reshape(5, -1)
     test = np.square(np.arange(2, 122)).reshape(4, -1)
     knn = KNearestNeighbor()
     knn.train(train, None)
     d_two = knn.compute_distances_two_loops(test)
     d_one = knn.compute_distances_one_loop(test)
     d_no = knn.compute_distances_no_loops(test)
     self.assertAlmostEqual(0, np.linalg.norm(d_two - d_one, ord='fro'))
     self.assertAlmostEqual(0, np.linalg.norm(d_no - d_one, ord='fro'))
Beispiel #3
0
y_test_pred = classifier.predict_labels(dists, k=1)

# Compute and print the fraction of correctly predicted examples
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))

# k=5时
y_test_pred = classifier.predict_labels(dists, k=5)
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))

####测试三种距离计算法的效率

dists_one = classifier.compute_distances_one_loop(X_test)

difference = np.linalg.norm(dists - dists_one, ord='fro')
print('Difference was: %f' % (difference, ))
if difference < 0.001:
  print('Good! The distance matrices are the same')
else:
  print('Uh-oh! The distance matrices are different')

dists_two = classifier.compute_distances_no_loops(X_test)
difference = np.linalg.norm(dists - dists_two, ord='fro')
print('Difference was: %f' % (difference, ))
if difference < 0.001:
  print('Good! The distance matrices are the same')
else:
  print('Uh-oh! The distance matrices are different')