Demo of one vs all logistic regression
| 119 | |
| 120 | // Demo of one vs all logistic regression |
| 121 | int logit_demo(bool console, int perc) { |
| 122 | array train_images, train_targets; |
| 123 | array test_images, test_targets; |
| 124 | int num_train, num_test, num_classes; |
| 125 | |
| 126 | // Load mnist data |
| 127 | float frac = (float)(perc) / 100.0; |
| 128 | setup_mnist<true>(&num_classes, &num_train, &num_test, train_images, |
| 129 | test_images, train_targets, test_targets, frac); |
| 130 | |
| 131 | // Reshape images into feature vectors |
| 132 | int feature_length = train_images.elements() / num_train; |
| 133 | array train_feats = moddims(train_images, feature_length, num_train).T(); |
| 134 | array test_feats = moddims(test_images, feature_length, num_test).T(); |
| 135 | |
| 136 | train_targets = train_targets.T(); |
| 137 | test_targets = test_targets.T(); |
| 138 | |
| 139 | // Add a bias that is always 1 |
| 140 | train_feats = join(1, constant(1, num_train, 1), train_feats); |
| 141 | test_feats = join(1, constant(1, num_test, 1), test_feats); |
| 142 | |
| 143 | // Train logistic regression parameters |
| 144 | array Weights = |
| 145 | train(train_feats, train_targets, |
| 146 | 0.1, // learning rate (aka alpha) |
| 147 | 1.0, // regularization constant (aka weight decay, aka lamdba) |
| 148 | 0.01, // maximum error |
| 149 | 1000, // maximum iterations |
| 150 | true); // verbose |
| 151 | |
| 152 | // Predict the results |
| 153 | array train_outputs = predict(train_feats, Weights); |
| 154 | array test_outputs = predict(test_feats, Weights); |
| 155 | |
| 156 | printf("Accuracy on training data: %2.2f\n", |
| 157 | accuracy(train_outputs, train_targets)); |
| 158 | |
| 159 | printf("Accuracy on testing data: %2.2f\n", |
| 160 | accuracy(test_outputs, test_targets)); |
| 161 | |
| 162 | printf("Maximum error on testing data: %2.2f\n", |
| 163 | abserr(test_outputs, test_targets)); |
| 164 | |
| 165 | benchmark_softmax_regression(train_feats, train_targets, test_feats); |
| 166 | |
| 167 | if (!console) { |
| 168 | test_outputs = test_outputs.T(); |
| 169 | // Get 20 random test images. |
| 170 | display_results<true>(test_images, test_outputs, test_targets.T(), 20); |
| 171 | } |
| 172 | |
| 173 | return 0; |
| 174 | } |
| 175 | |
| 176 | int main(int argc, char **argv) { |
| 177 | int device = argc > 1 ? atoi(argv[1]) : 0; |
no test coverage detected