Calculate all the distances from testing set to training set
| 24 | |
| 25 | // Calculate all the distances from testing set to training set |
| 26 | array distance(array train, array test) { |
| 27 | const int feat_len = train.dims(1); |
| 28 | const int num_train = train.dims(0); |
| 29 | const int num_test = test.dims(0); |
| 30 | |
| 31 | array dist = constant(0, num_train, num_test); |
| 32 | |
| 33 | // Iterate over each attribute |
| 34 | for (int ii = 0; ii < feat_len; ii++) { |
| 35 | // Get a attribute vectors |
| 36 | array train_i = train(span, ii); |
| 37 | array test_i = test(span, ii).T(); |
| 38 | |
| 39 | // Tile the vectors to generate matrices |
| 40 | array train_tiled = tile(train_i, 1, num_test); |
| 41 | array test_tiled = tile(test_i, num_train, 1); |
| 42 | |
| 43 | // Add the distance for this attribute |
| 44 | dist = dist + abs(train_tiled - test_tiled); |
| 45 | dist.eval(); // Necessary to free up train_i, test_i |
| 46 | } |
| 47 | |
| 48 | return dist; |
| 49 | } |
| 50 | |
| 51 | array knn(array &train_feats, array &test_feats, array &train_labels) { |
| 52 | // Find distances between training and testing sets |