Debian Codegraph @

inst/doc/xgboostfromJSON.Rmd

raw
1 ---
2 title: "XGBoost from JSON"
3 output:
4 rmarkdown::html_vignette:
5 number_sections: yes
6 toc: yes
7 author: Roland Stevenson
8 vignette: >
9 %\VignetteIndexEntry{XGBoost from JSON}
10 %\VignetteEngine{knitr::rmarkdown}
11 \usepackage[utf8]{inputenc}
12 ---
13
14 XGBoost from JSON
15 =================
16
17 ## Introduction
18
19 The purpose of this Vignette is to show you how to correctly load and work with an **XGBoost** model that has been dumped to JSON. **XGBoost** internally converts all data to [32-bit floats](https://en.wikipedia.org/wiki/Single-precision_floating-point_format), and the values dumped to JSON are decimal representations of these values. When working with a model that has been parsed from a JSON file, care must be taken to correctly treat:
20
21 - the input data, which should be converted to 32-bit floats
22 - any 32-bit floats that were stored in JSON as decimal representations
23 - any calculations must be done with 32-bit mathematical operators
24
25 ## Setup
26
27 For the purpose of this tutorial we will load the xgboost, jsonlite, and float packages. We'll also set `digits=22` in our options in case we want to inspect many digits of our results.
28
29 ```{r}
30 require(xgboost)
31 require(jsonlite)
32 require(float)
33 options(digits = 22)
34 ```
35
36 We will create a toy binary logistic model based on the example first provided [here](https://github.com/dmlc/xgboost/issues/3960), so that we can easily understand the structure of the dumped JSON model object. This will allow us to understand where discrepancies can occur and how they should be handled.
37
38 ```{r}
39 dates <- c(20180130, 20180130, 20180130,
40 20180130, 20180130, 20180130,
41 20180131, 20180131, 20180131,
42 20180131, 20180131, 20180131,
43 20180131, 20180131, 20180131,
44 20180134, 20180134, 20180134)
45
46 labels <- c(1, 1, 1,
47 1, 1, 1,
48 0, 0, 0,
49 0, 0, 0,
50 0, 0, 0,
51 0, 0, 0)
52
53 data <- data.frame(dates = dates, labels = labels)
54
55 bst <- xgb.train(
56 data = xgb.DMatrix(as.matrix(data$dates), label = labels, missing = NA, nthread = 1),
57 nrounds = 1,
58 params = xgb.params(
59 objective = "binary:logistic",
60 nthread = 2,
61 max_depth = 1
62 )
63 )
64 ```
65
66 ## Comparing results
67 We will now dump the model to JSON and attempt to illustrate a variety of issues that can arise, and how to properly deal with them.
68
69 First let's dump the model to JSON:
70
71 ```{r}
72 bst_json <- xgb.dump(bst, with_stats = FALSE, dump_format = 'json')
73 bst_from_json <- fromJSON(bst_json, simplifyDataFrame = FALSE)
74 node <- bst_from_json[[1]]
75 cat(bst_json)
76 ```
77
78 The tree JSON shown by the above code-chunk tells us that if the data is less than 20180132, the tree will output the value in the first leaf. Otherwise it will output the value in the second leaf. Let's try to reproduce this manually with the data we have and confirm that it matches the model predictions we've already calculated.
79
80 ```{r}
81 bst_preds_logodds <- predict(bst, as.matrix(data$dates), outputmargin = TRUE)
82
83 # calculate the logodds values using the JSON representation
84 bst_from_json_logodds <- ifelse(data$dates < node$split_condition,
85 node$children[[1]]$leaf,
86 node$children[[2]]$leaf)
87
88 bst_preds_logodds
89 bst_from_json_logodds
90
91 # test that values are equal
92 bst_preds_logodds == bst_from_json_logodds
93
94 ```
95 None are equal. What happened?
96
97 At this stage two things happened:
98
99 - input data was not converted to 32-bit floats
100 - the JSON variables were not converted to 32-bit floats
101
102 ### Lesson 1: All data is 32-bit floats
103
104 > When working with imported JSON, all data must be converted to 32-bit floats
105
106 To explain this, let's repeat the comparison and round to two decimals:
107
108 ```{r}
109 round(bst_preds_logodds, 2) == round(bst_from_json_logodds, 2)
110 ```
111
112 If we round to two decimals, we see that only the elements related to data values of `20180131` don't agree. If we convert the data to floats, they agree:
113
114 ```{r}
115 # now convert the dates to floats first
116 bst_from_json_logodds <- ifelse(fl(data$dates) < node$split_condition,
117 node$children[[1]]$leaf,
118 node$children[[2]]$leaf)
119
120 # test that values are equal
121 round(bst_preds_logodds, 2) == round(bst_from_json_logodds, 2)
122 ```
123
124 What's the lesson? If we are going to work with an imported JSON model, any data must be converted to floats first. In this case, since '20180131' cannot be represented as a 32-bit float, it is rounded up to 20180132, as shown here:
125
126 ```{r}
127 fl(20180131)
128 ```
129
130
131 ### Lesson 2: JSON parameters are 32-bit floats
132
133 > All JSON parameters stored as floats must be converted to floats.
134
135 Let's now say we do care about numbers past the first two decimals.
136
137 ```{r}
138 # test that values are equal
139 bst_preds_logodds == bst_from_json_logodds
140 ```
141
142 None are exactly equal. What happened? Although we've converted the data to 32-bit floats, we also need to convert the JSON parameters to 32-bit floats. Let's do this:
143
144 ```{r}
145 # now convert the dates to floats first
146 bst_from_json_logodds <- ifelse(fl(data$dates) < fl(node$split_condition),
147 as.numeric(fl(node$children[[1]]$leaf)),
148 as.numeric(fl(node$children[[2]]$leaf)))
149
150 # test that values are equal
151 bst_preds_logodds == bst_from_json_logodds
152 ```
153 All equal. What's the lesson? If we are going to work with an imported JSON model, any JSON parameters that were stored as floats must also be converted to floats first.
154
155 ### Lesson 3: Use 32-bit math
156
157 > Always use 32-bit numbers and operators
158
159 We were able to get the log-odds to agree, so now let's manually calculate the sigmoid of the log-odds. This should agree with the xgboost predictions.
160
161
162 ```{r}
163 bst_preds <- predict(bst, as.matrix(data$dates))
164
165 # calculate the predictions casting doubles to floats
166 bst_from_json_preds <- ifelse(
167 fl(data$dates) < fl(node$split_condition)
168 , as.numeric(1 / (1 + exp(-1 * fl(node$children[[1]]$leaf))))
169 , as.numeric(1 / (1 + exp(-1 * fl(node$children[[2]]$leaf))))
170 )
171
172 # test that values are equal
173 bst_preds == bst_from_json_preds
174 ```
175
176 None are exactly equal again. What is going on here? Well, since we are using the value `1` in the calculations, we have introduced a double into the calculation. Because of this, all float values are promoted to 64-bit doubles and the 64-bit version of the exponentiation operator `exp` is also used. On the other hand, xgboost uses the 32-bit version of the exponentiation operator in its [sigmoid function](https://github.com/dmlc/xgboost/blob/54980b8959680a0da06a3fc0ec776e47c8cbb0a1/src/common/math.h#L25-L27).
177
178 How do we fix this? We have to ensure we use the correct data types everywhere and the correct operators. If we use only floats, the float library that we have loaded will ensure the 32-bit float exponentiation operator is applied.
179 ```{r}
180 # calculate the predictions casting doubles to floats
181 bst_from_json_preds <- ifelse(
182 fl(data$dates) < fl(node$split_condition)
183 , as.numeric(fl(1) / (fl(1) + exp(fl(-1) * fl(node$children[[1]]$leaf))))
184 , as.numeric(fl(1) / (fl(1) + exp(fl(-1) * fl(node$children[[2]]$leaf))))
185 )
186
187 # test that values are equal
188 bst_preds == bst_from_json_preds
189 ```
190
191 All equal. What's the lesson? We have to ensure that all calculations are done with 32-bit floating point operators if we want to reproduce the results that we see with xgboost.