| 34 | |
| 35 | |
| 36 | int main() try |
| 37 | { |
| 38 | // The API for doing metric learning is very similar to the API for |
| 39 | // multi-class classification. In fact, the inputs are the same, a bunch of |
| 40 | // labeled objects. So here we create our dataset. We make up some simple |
| 41 | // vectors and label them with the integers 1,2,3,4. The specific values of |
| 42 | // the integer labels don't matter. |
| 43 | std::vector<matrix<double,0,1>> samples; |
| 44 | std::vector<unsigned long> labels; |
| 45 | |
| 46 | // class 1 training vectors |
| 47 | samples.push_back({1,0,0,0,0,0,0,0}); labels.push_back(1); |
| 48 | samples.push_back({0,1,0,0,0,0,0,0}); labels.push_back(1); |
| 49 | |
| 50 | // class 2 training vectors |
| 51 | samples.push_back({0,0,1,0,0,0,0,0}); labels.push_back(2); |
| 52 | samples.push_back({0,0,0,1,0,0,0,0}); labels.push_back(2); |
| 53 | |
| 54 | // class 3 training vectors |
| 55 | samples.push_back({0,0,0,0,1,0,0,0}); labels.push_back(3); |
| 56 | samples.push_back({0,0,0,0,0,1,0,0}); labels.push_back(3); |
| 57 | |
| 58 | // class 4 training vectors |
| 59 | samples.push_back({0,0,0,0,0,0,1,0}); labels.push_back(4); |
| 60 | samples.push_back({0,0,0,0,0,0,0,1}); labels.push_back(4); |
| 61 | |
| 62 | |
| 63 | // Make a network that simply learns a linear mapping from 8D vectors to 2D |
| 64 | // vectors. |
| 65 | using net_type = loss_metric<fc<2,input<matrix<double,0,1>>>>; |
| 66 | net_type net; |
| 67 | dnn_trainer<net_type> trainer(net); |
| 68 | trainer.set_learning_rate(0.1); |
| 69 | |
| 70 | // It should be emphasized out that it's really important that each mini-batch contain |
| 71 | // multiple instances of each class of object. This is because the metric learning |
| 72 | // algorithm needs to consider pairs of objects that should be close as well as pairs |
| 73 | // of objects that should be far apart during each training step. Here we just keep |
| 74 | // training on the same small batch so this constraint is trivially satisfied. |
| 75 | while(trainer.get_learning_rate() >= 1e-4) |
| 76 | trainer.train_one_step(samples, labels); |
| 77 | |
| 78 | // Wait for training threads to stop |
| 79 | trainer.get_net(); |
| 80 | cout << "done training" << endl; |
| 81 | |
| 82 | |
| 83 | // Run all the samples through the network to get their 2D vector embeddings. |
| 84 | std::vector<matrix<float,0,1>> embedded = net(samples); |
| 85 | |
| 86 | // Print the embedding for each sample to the screen. If you look at the |
| 87 | // outputs carefully you should notice that they are grouped together in 2D |
| 88 | // space according to their label. |
| 89 | for (size_t i = 0; i < embedded.size(); ++i) |
| 90 | cout << "label: " << labels[i] << "\t" << trans(embedded[i]); |
| 91 | |
| 92 | // Now, check if the embedding puts things with the same labels near each other and |
| 93 | // things with different labels far apart. |
nothing calls this directly
no test coverage detected