Given the 9-dimensional weight vector which defines a 3 class classifier, predict the class of the given 3-dimensional sample vector. Therefore, the output of this function is either 0, 1, or 2 (i.e. one of the three possible labels).
(weights, sample)
| 62 | |
| 63 | |
| 64 | def predict_label(weights, sample): |
| 65 | """Given the 9-dimensional weight vector which defines a 3 class classifier, |
| 66 | predict the class of the given 3-dimensional sample vector. Therefore, the |
| 67 | output of this function is either 0, 1, or 2 (i.e. one of the three possible |
| 68 | labels).""" |
| 69 | |
| 70 | # Our 3-class classifier model can be thought of as containing 3 separate |
| 71 | # linear classifiers. So to predict the class of a sample vector we |
| 72 | # evaluate each of these three classifiers and then whatever classifier has |
| 73 | # the largest output "wins" and predicts the label of the sample. This is |
| 74 | # the popular one-vs-all multi-class classifier model. |
| 75 | # Keeping this in mind, the code below simply pulls the three separate |
| 76 | # weight vectors out of weights and then evaluates each against sample. The |
| 77 | # individual classifier scores are stored in scores and the highest scoring |
| 78 | # index is returned as the label. |
| 79 | w0 = weights[0:3] |
| 80 | w1 = weights[3:6] |
| 81 | w2 = weights[6:9] |
| 82 | scores = [dot(w0, sample), dot(w1, sample), dot(w2, sample)] |
| 83 | max_scoring_label = scores.index(max(scores)) |
| 84 | return max_scoring_label |
| 85 | |
| 86 | |
| 87 | def dot(a, b): |