├── .gitignore
├── .travis.yml
├── LICENSE
├── README.Rmd
├── README.md
├── build.R
├── experiments
├── Tcomp-checks.R
├── experiments.R
├── explore-trends.R
├── maxlags-experiment.R
├── seasonal-adjustment-experiments.R
├── validation.R
└── xreg-experiments.R
├── figure
├── unnamed-chunk-10-1.png
├── unnamed-chunk-16-1.png
├── unnamed-chunk-17-1.png
├── unnamed-chunk-2-1.png
├── unnamed-chunk-3-1.png
├── unnamed-chunk-3-2.png
├── unnamed-chunk-4-1.png
├── unnamed-chunk-5-1.png
├── unnamed-chunk-6-1.png
├── unnamed-chunk-7-1.png
├── unnamed-chunk-8-1.png
├── unnamed-chunk-8-2.png
├── unnamed-chunk-8-3.png
├── unnamed-chunk-9-1.png
└── unnamed-chunk-9-2.png
├── forecastxg-r-package.Rproj
├── pkg
├── .Rbuildignore
├── DESCRIPTION
├── NAMESPACE
├── R
│ ├── extras.R
│ ├── forecast.xgbar.R
│ ├── forecastxgb.R
│ ├── misc-doc.R
│ ├── utils.R
│ ├── validate_xgbar.R
│ └── xgbar.R
├── data
│ ├── Mcomp_results.rda
│ ├── Tcomp_results.rda
│ └── seaice_ts.rda
├── inst
│ └── doc
│ │ ├── xgbar.R
│ │ ├── xgbar.Rmd
│ │ └── xgbar.html
├── man
│ ├── Mcomp_results.Rd
│ ├── Tcomp_results.Rd
│ ├── forecast.xgbar.Rd
│ ├── forecastxgb-package.Rd
│ ├── plot.xgbar.Rd
│ ├── seaice_ts.Rd
│ ├── summary.xgbar.Rd
│ ├── xgbar.Rd
│ └── xgbar_importance.Rd
├── pkg.Rproj
├── tests
│ ├── testthat.R
│ └── testthat
│ │ ├── test-correct-classes.R
│ │ ├── test-irregular-seasons.R
│ │ ├── test-modulus-transform.R
│ │ ├── test-ok-noninteger-frequency.R
│ │ ├── test-seasonal-methods.R
│ │ ├── test-shorter-monthly-data.R
│ │ ├── test-utils.R
│ │ ├── test-works-range-data.R
│ │ └── tests-different-maxlags.R
└── vignettes
│ └── xgbar.Rmd
└── prep
└── get-seaice-data.R
/.gitignore:
--------------------------------------------------------------------------------
1 | # History files
2 | .Rhistory
3 | .Rapp.history
4 |
5 | # Session Data files
6 | .RData
7 |
8 | # Example code in package build process
9 | *-Ex.R
10 |
11 | # Output files from R CMD build
12 | /*.tar.gz
13 |
14 | # Output files from R CMD check
15 | /*.Rcheck/
16 |
17 | # RStudio files
18 | .Rproj.user/
19 |
20 | # produced vignettes
21 | vignettes/*.html
22 | vignettes/*.pdf
23 |
24 | # OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3
25 | .httr-oauth
26 |
27 | # knitr and R markdown default cache directories
28 | /*_cache/
29 | /cache/
30 |
31 | # Temporary files created by R markdown
32 | *.utf8.md
33 | *.knit.md
34 | .Rproj.user
35 |
36 | # temporary files made by xgboost
37 | xgboost.model
38 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | # thanks to https://github.com/travis-ci/travis-ci/issues/5775
2 | sudo: false
3 |
4 | language: r
5 | r:
6 | - oldrel
7 | - release
8 | - devel
9 |
10 | cache: packages
11 |
12 | install:
13 | - Rscript -e 'install.packages(c("devtools","roxygen2","testthat", "knitr", "rmarkdown", "xgboost", "forecast", "fpp", "ggplot2", "scales", "Tcomp", "foreach", "doParallel", "dplyr", "tseries"));devtools::install_deps("pkg")'
14 | script:
15 | - Rscript -e 'devtools::check("pkg")'
16 |
17 | notifications:
18 | email:
19 | on_success: change
20 | on_failure: change
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.Rmd:
--------------------------------------------------------------------------------
1 | # forecastxgb-r-package
2 | The `forecastxgb` package provides time series modelling and forecasting functions that combine the machine learning approach of Chen, He and Benesty's [`xgboost`](https://CRAN.R-project.org/package=xgboost) with the convenient handling of time series and familiar API of Rob Hyndman's [`forecast`](http://github.com/robjhyndman/forecast). It applies to time series the Extreme Gradient Boosting proposed in [*Greedy Function Approximation: A Gradient Boosting Machine*, by Jermoe Friedman in 2001](http://www.jstor.org/stable/2699986). xgboost has become an important machine learning algorithm; nicely explained in [this accessible documentation](http://xgboost.readthedocs.io/en/latest/model.html).
3 |
4 | [](https://travis-ci.org/ellisp/forecastxgb-r-package)
5 | [](http://www.r-pkg.org/pkg/forecastxgb)
6 | [](http://www.r-pkg.org/pkg/forecastxgb)
7 |
8 | **Warning: this package is under active development and is some way off a CRAN release (realistically, no some time in 2017). Currently the forecasting results with the default settings are, frankly, pretty rubbish, but there is hope I can get better settings. The API and default values of arguments should be expected to continue to change.**
9 |
10 | ## Installation
11 | Only on GitHub, but plan for a CRAN release in November 2016. Comments and suggestions welcomed.
12 |
13 | This implementation uses as explanatory features:
14 |
15 | * lagged values of the response variable
16 | * dummy variables for seasons.
17 | * current and lagged values of any external regressors supplied as `xreg`
18 |
19 | ```{r echo = FALSE}
20 | set.seed(123)
21 | library(knitr)
22 | knit_hooks$set(mypar = function(before, options, envir) {
23 | if (before) par(bty = "l", family = "serif")
24 | })
25 | opts_chunk$set(comment=NA, fig.width=7, fig.height=5, cache = FALSE, mypar = TRUE)
26 | ```
27 |
28 |
29 | ```{r eval = FALSE}
30 | devtools::install_github("ellisp/forecastxgb-r-package/pkg")
31 | ```
32 |
33 | ## Usage
34 |
35 |
36 | ## Basic usage
37 |
38 | The workhorse function is `xgbar`. This fits a model to a time series. Under the hood, it creates a matrix of explanatory variables based on lagged versions of the response time series, and (optionally) dummy variables of some sort for seasons. That matrix is then fed as the feature set for `xgboost` to do its stuff.
39 |
40 | ### Univariate
41 |
42 | Usage with default values is straightforward. Here it is fit to Australian monthly gas production 1956-1995, an example dataset provided in `forecast`:
43 | ```{r message = FALSE}
44 | library(forecastxgb)
45 | model <- xgbar(gas)
46 | ```
47 | (Note: the "Stopping. Best iteration..." to the screen is produced by `xgboost::xgb.cv`, which uses `cat()` rather than `message()` to print information on its processing.)
48 |
49 | By default, `xgbar` uses row-wise cross-validation to determine the best number of rounds of iterations for the boosting algorithm without overfitting. A final model is then fit on the full available dataset. The relative importance of the various features in the model can be inspected by `importance_xgb()` or, more conveniently, the `summary` method for objects of class `xgbar`.
50 |
51 |
52 | ```{r}
53 | summary(model)
54 | ```
55 | We see in the case of the gas data that the most important feature in explaining gas production is the production 12 months previously; and then other features decrease in importance from there but still have an impact.
56 |
57 | Forecasting is the main purpose of this package, and a `forecast` method is supplied. The resulting objects are of class `forecast` and familiar generic functions work with them.
58 |
59 | ```{r}
60 | fc <- forecast(model, h = 12)
61 | plot(fc)
62 | ```
63 |
64 | Note that prediction intervals are not currently available.
65 |
66 | See the vignette for more extended examples.
67 |
68 | ### With external regressors
69 | External regressors can be added by using the `xreg` argument familiar from other forecast functions like `auto.arima` and `nnetar`. `xreg` can be a vector or `ts` object but is easiest to integrate into the analysis if it is a matrix (even a matrix with one column) with well-chosen column names; that way feature names persist meaningfully.
70 |
71 | The example below, with data taken from the `fpp` package supporting Athanasopoulos and Hyndman's [Forecasting Principles and Practice](https://www.otexts.org/fpp) book, shows income being used to explain consumption. In the same way that the response variable `y` is expanded into lagged versions of itself, each column in `xreg` is expanded into lagged versions, which are then treated as individual features for `xgboost`.
72 |
73 | ```{r message = FALSE}
74 | library(fpp)
75 | consumption <- usconsumption[ ,1]
76 | income <- matrix(usconsumption[ ,2], dimnames = list(NULL, "Income"))
77 | consumption_model <- xgbar(y = consumption, xreg = income)
78 | summary(consumption_model)
79 | ```
80 | We see that the two most important features explaining consumption are the two previous quarters' values of consumption; followed by the income in this quarter; and so on.
81 |
82 |
83 | The challenge of using external regressors in a forecasting environment is that to forecast, you need values of the future external regressors. One way this is sometimes done is by first forecasting the individual regressors. In the example below we do this, making sure the data structure is the same as the original `xreg`. When the new value of `xreg` is given to `forecast`, it forecasts forward the number of rows of the new `xreg`.
84 | ```{r}
85 | income_future <- matrix(forecast(xgbar(usconsumption[,2]), h = 10)$mean,
86 | dimnames = list(NULL, "Income"))
87 | plot(forecast(consumption_model, xreg = income_future))
88 | ```
89 |
90 | ## Options
91 |
92 | ### Seasonality
93 |
94 | Currently there are three methods of treating seasonality.
95 |
96 | - The current default method is to throw dummy variables for each season into the mix of features for `xgboost` to work with.
97 | - An alternative is to perform classic multiplicative seasonal adjustment on the series before feeding it to `xgboost`. This seems to work better.
98 | - A third option is to create a set of pairs of Fourier transform variables and use them as x regressors
99 |
100 | ```{r echo = FALSE}
101 | model1 <- xgbar(co2, seas_method = "dummies")
102 | model2 <- xgbar(co2, seas_method = "decompose")
103 | model3 <- xgbar(co2, seas_method = "fourier")
104 | plot(forecast(model1), main = "Dummy variables for seasonality")
105 | plot(forecast(model2), main = "Decomposition seasonal adjustment for seasonality")
106 | plot(forecast(model3), main = "Fourier transform pairs as x regressors")
107 | ```
108 |
109 | All methods perform quite poorly at the moment, suffering from the difficulty the default settings have in dealing with non-stationary data (see below).
110 |
111 | ### Transformations
112 |
113 | The data can be transformed by a modulus power transformation (as per John and Draper, 1980) before feeding to `xgboost`. This transformation is similar to a Box-Cox transformation, but works with negative data. Leaving the `lambda` parameter as 1 will effectively switch off this transformation.
114 | ```{r echo = FALSE}
115 | model1 <- xgbar(co2, seas_method = "decompose", lambda = 1)
116 | model2 <- xgbar(co2, seas_method = "decompose", lambda = BoxCox.lambda(co2))
117 | plot(forecast(model1), main = "No transformation")
118 | plot(forecast(model2), main = "With transformation")
119 | ```
120 |
121 | Version 0.0.9 of `forecastxgb` gave `lambda` the default value of `BoxCox.lambda(abs(y))`. This returned spectacularly bad forecasting results. Forcing this to be between 0 and 1 helped a little, but still gave very bad results. So far there isn't evidence (but neither is there enough investigation) that a Box Cox transformation helps xgbar do its model fitting at all.
122 |
123 | ### Non-stationarity
124 | From experiments so far, it seems the basic idea of `xgboost` struggles in this context with extrapolation into a new range of variables not in the training set. This suggests better results might be obtained by transforming the series into a stationary one before modelling - a similar approach to that taken by `forecast::auto.arima`. This option is available by `trend_method = "differencing"` and seems to perform well - certainly better than without - and it will probably be made a default setting once more experience is available.
125 |
126 | ```{r}
127 | model <- xgbar(AirPassengers, trend_method = "differencing", seas_method = "fourier")
128 | plot(forecast(model, 24))
129 | ```
130 |
131 |
132 | ## Future developments
133 | Future work might include:
134 |
135 | * additional automated time-dependent features (eg dummy variables for trading days, Easter, etc)
136 | * ability to include xreg values that don't get lagged
137 | * some kind of automated multiple variable forecasting, similar to a vector-autoregression.
138 | * better choices of defaults for values such as `lambda` (for power transformations), `K` (for Fourier transforms) and, most likely to be effective, `maxlag`.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # forecastxgb-r-package
2 | The `forecastxgb` package provides time series modelling and forecasting functions that combine the machine learning approach of Chen, He and Benesty's [`xgboost`](https://CRAN.R-project.org/package=xgboost) with the convenient handling of time series and familiar API of Rob Hyndman's [`forecast`](http://github.com/robjhyndman/forecast). It applies to time series the Extreme Gradient Boosting proposed in [*Greedy Function Approximation: A Gradient Boosting Machine*, by Jermoe Friedman in 2001](http://www.jstor.org/stable/2699986). xgboost has become an important machine learning algorithm; nicely explained in [this accessible documentation](http://xgboost.readthedocs.io/en/latest/model.html).
3 |
4 | [](https://travis-ci.org/ellisp/forecastxgb-r-package)
5 | [](http://www.r-pkg.org/pkg/forecastxgb)
6 | [](http://www.r-pkg.org/pkg/forecastxgb)
7 |
8 | **Warning: this package is under active development and is some way off a CRAN release (realistically, no some time in 2017). Currently the forecasting results with the default settings are, frankly, pretty rubbish, but there is hope I can get better settings. The API and default values of arguments should be expected to continue to change.**
9 |
10 | ## Installation
11 | Only on GitHub, but plan for a CRAN release in November 2016. Comments and suggestions welcomed.
12 |
13 | This implementation uses as explanatory features:
14 |
15 | * lagged values of the response variable
16 | * dummy variables for seasons.
17 | * current and lagged values of any external regressors supplied as `xreg`
18 |
19 |
20 |
21 |
22 |
23 | ```r
24 | devtools::install_github("ellisp/forecastxgb-r-package/pkg")
25 | ```
26 |
27 | ## Usage
28 |
29 |
30 | ## Basic usage
31 |
32 | The workhorse function is `xgbar`. This fits a model to a time series. Under the hood, it creates a matrix of explanatory variables based on lagged versions of the response time series, and (optionally) dummy variables of some sort for seasons. That matrix is then fed as the feature set for `xgboost` to do its stuff.
33 |
34 | ### Univariate
35 |
36 | Usage with default values is straightforward. Here it is fit to Australian monthly gas production 1956-1995, an example dataset provided in `forecast`:
37 |
38 | ```r
39 | library(forecastxgb)
40 | model <- xgbar(gas)
41 | ```
42 | (Note: the "Stopping. Best iteration..." to the screen is produced by `xgboost::xgb.cv`, which uses `cat()` rather than `message()` to print information on its processing.)
43 |
44 | By default, `xgbar` uses row-wise cross-validation to determine the best number of rounds of iterations for the boosting algorithm without overfitting. A final model is then fit on the full available dataset. The relative importance of the various features in the model can be inspected by `importance_xgb()` or, more conveniently, the `summary` method for objects of class `xgbar`.
45 |
46 |
47 |
48 | ```r
49 | summary(model)
50 | ```
51 |
52 | ```
53 |
54 | Importance of features in the xgboost model:
55 | Feature Gain Cover Frequency
56 | 1: lag12 5.097936e-01 0.1480752533 0.078475336
57 | 2: lag11 2.796867e-01 0.0731403763 0.042600897
58 | 3: lag13 1.043604e-01 0.0355137482 0.031390135
59 | 4: lag24 7.807860e-02 0.1320115774 0.069506726
60 | 5: lag1 1.579312e-02 0.1885383502 0.181614350
61 | 6: lag23 5.616290e-03 0.0471490593 0.042600897
62 | 7: lag9 2.510372e-03 0.0459623734 0.040358744
63 | 8: lag2 6.759874e-04 0.0436179450 0.053811659
64 | 9: lag14 5.874155e-04 0.0311432706 0.026905830
65 | 10: lag10 5.467606e-04 0.0530535456 0.053811659
66 | 11: lag6 3.820611e-04 0.0152243126 0.033632287
67 | 12: lag4 2.188107e-04 0.0098697540 0.035874439
68 | 13: lag22 2.162973e-04 0.0103617945 0.017937220
69 | 14: lag16 2.042320e-04 0.0098118669 0.013452915
70 | 15: lag21 1.962725e-04 0.0149638205 0.026905830
71 | 16: lag18 1.810734e-04 0.0243994211 0.029147982
72 | 17: lag3 1.709305e-04 0.0132850941 0.035874439
73 | 18: lag5 1.439827e-04 0.0231837916 0.033632287
74 | 19: lag15 1.313859e-04 0.0143560058 0.031390135
75 | 20: lag17 1.239889e-04 0.0109696093 0.017937220
76 | 21: season7 1.049934e-04 0.0081041968 0.015695067
77 | 22: lag8 9.773024e-05 0.0123299566 0.026905830
78 | 23: lag19 7.733822e-05 0.0112879884 0.015695067
79 | 24: lag20 5.425515e-05 0.0072648336 0.011210762
80 | 25: lag7 3.772907e-05 0.0105354559 0.020179372
81 | 26: season4 4.067607e-06 0.0010709117 0.002242152
82 | 27: season5 2.863805e-06 0.0022286541 0.006726457
83 | 28: season6 2.628821e-06 0.0021707670 0.002242152
84 | 29: season9 9.226827e-08 0.0003762663 0.002242152
85 | Feature Gain Cover Frequency
86 |
87 | 35 features considered.
88 | 476 original observations.
89 | 452 effective observations after creating lagged features.
90 | ```
91 | We see in the case of the gas data that the most important feature in explaining gas production is the production 12 months previously; and then other features decrease in importance from there but still have an impact.
92 |
93 | Forecasting is the main purpose of this package, and a `forecast` method is supplied. The resulting objects are of class `forecast` and familiar generic functions work with them.
94 |
95 |
96 | ```r
97 | fc <- forecast(model, h = 12)
98 | plot(fc)
99 | ```
100 |
101 | 
102 |
103 | Note that prediction intervals are not currently available.
104 |
105 | See the vignette for more extended examples.
106 |
107 | ### With external regressors
108 | External regressors can be added by using the `xreg` argument familiar from other forecast functions like `auto.arima` and `nnetar`. `xreg` can be a vector or `ts` object but is easiest to integrate into the analysis if it is a matrix (even a matrix with one column) with well-chosen column names; that way feature names persist meaningfully.
109 |
110 | The example below, with data taken from the `fpp` package supporting Athanasopoulos and Hyndman's [Forecasting Principles and Practice](https://www.otexts.org/fpp) book, shows income being used to explain consumption. In the same way that the response variable `y` is expanded into lagged versions of itself, each column in `xreg` is expanded into lagged versions, which are then treated as individual features for `xgboost`.
111 |
112 |
113 | ```r
114 | library(fpp)
115 | consumption <- usconsumption[ ,1]
116 | income <- matrix(usconsumption[ ,2], dimnames = list(NULL, "Income"))
117 | consumption_model <- xgbar(y = consumption, xreg = income)
118 | summary(consumption_model)
119 | ```
120 |
121 | ```
122 |
123 | Importance of features in the xgboost model:
124 | Feature Gain Cover Frequency
125 | 1: lag2 0.253763903 0.082908446 0.124513619
126 | 2: lag1 0.219332682 0.114608734 0.171206226
127 | 3: Income_lag0 0.115604367 0.183107958 0.085603113
128 | 4: lag3 0.064652150 0.093105742 0.089494163
129 | 5: lag8 0.055645114 0.099756152 0.066147860
130 | 6: Income_lag8 0.050460959 0.049434715 0.050583658
131 | 7: Income_lag1 0.047187235 0.088561295 0.050583658
132 | 8: Income_lag6 0.040512834 0.029150964 0.050583658
133 | 9: lag6 0.031876878 0.044225227 0.054474708
134 | 10: Income_lag2 0.020355402 0.015739304 0.031128405
135 | 11: Income_lag5 0.018011250 0.036577256 0.035019455
136 | 12: lag5 0.017930780 0.032143649 0.035019455
137 | 13: lag7 0.016674036 0.034249612 0.027237354
138 | 14: Income_lag4 0.015952784 0.025714919 0.038910506
139 | 15: Income_lag7 0.009850701 0.021724673 0.019455253
140 | 16: lag4 0.008819146 0.028929284 0.038910506
141 | 17: Income_lag3 0.008720737 0.013855021 0.019455253
142 | 18: season4 0.003152234 0.001551762 0.003891051
143 | 19: season3 0.001496807 0.004655287 0.007782101
144 |
145 | 20 features considered.
146 | 164 original observations.
147 | 156 effective observations after creating lagged features.
148 | ```
149 | We see that the two most important features explaining consumption are the two previous quarters' values of consumption; followed by the income in this quarter; and so on.
150 |
151 |
152 | The challenge of using external regressors in a forecasting environment is that to forecast, you need values of the future external regressors. One way this is sometimes done is by first forecasting the individual regressors. In the example below we do this, making sure the data structure is the same as the original `xreg`. When the new value of `xreg` is given to `forecast`, it forecasts forward the number of rows of the new `xreg`.
153 |
154 | ```r
155 | income_future <- matrix(forecast(xgbar(usconsumption[,2]), h = 10)$mean,
156 | dimnames = list(NULL, "Income"))
157 | plot(forecast(consumption_model, xreg = income_future))
158 | ```
159 |
160 | 
161 |
162 | ## Options
163 |
164 | ### Seasonality
165 |
166 | Currently there are three methods of treating seasonality.
167 |
168 | - The current default method is to throw dummy variables for each season into the mix of features for `xgboost` to work with.
169 | - An alternative is to perform classic multiplicative seasonal adjustment on the series before feeding it to `xgboost`. This seems to work better.
170 | - A third option is to create a set of pairs of Fourier transform variables and use them as x regressors
171 |
172 |
173 | ```
174 | No h provided so forecasting forward 24 periods.
175 | ```
176 |
177 | 
178 |
179 | ```
180 | No h provided so forecasting forward 24 periods.
181 | ```
182 |
183 | 
184 |
185 | ```
186 | No h provided so forecasting forward 24 periods.
187 | ```
188 |
189 | 
190 |
191 | All methods perform quite poorly at the moment, suffering from the difficulty the default settings have in dealing with non-stationary data (see below).
192 |
193 | ### Transformations
194 |
195 | The data can be transformed by a modulus power transformation (as per John and Draper, 1980) before feeding to `xgboost`. This transformation is similar to a Box-Cox transformation, but works with negative data. Leaving the `lambda` parameter as 1 will effectively switch off this transformation.
196 |
197 | ```
198 | No h provided so forecasting forward 24 periods.
199 | ```
200 |
201 | 
202 |
203 | ```
204 | No h provided so forecasting forward 24 periods.
205 | ```
206 |
207 | 
208 |
209 | Version 0.0.9 of `forecastxgb` gave `lambda` the default value of `BoxCox.lambda(abs(y))`. This returned spectacularly bad forecasting results. Forcing this to be between 0 and 1 helped a little, but still gave very bad results. So far there isn't evidence (but neither is there enough investigation) that a Box Cox transformation helps xgbar do its model fitting at all.
210 |
211 | ### Non-stationarity
212 | From experiments so far, it seems the basic idea of `xgboost` struggles in this context with extrapolation into a new range of variables not in the training set. This suggests better results might be obtained by transforming the series into a stationary one before modelling - a similar approach to that taken by `forecast::auto.arima`. This option is available by `trend_method = "differencing"` and seems to perform well - certainly better than without - and it will probably be made a default setting once more experience is available.
213 |
214 |
215 | ```r
216 | model <- xgbar(AirPassengers, trend_method = "differencing", seas_method = "fourier")
217 | plot(forecast(model, 24))
218 | ```
219 |
220 | 
221 |
222 |
223 | ## Future developments
224 | Future work might include:
225 |
226 | * additional automated time-dependent features (eg dummy variables for trading days, Easter, etc)
227 | * ability to include xreg values that don't get lagged
228 | * some kind of automated multiple variable forecasting, similar to a vector-autoregression.
229 | * better choices of defaults for values such as `lambda` (for power transformations), `K` (for Fourier transforms) and, most likely to be effective, `maxlag`.
230 |
--------------------------------------------------------------------------------
/build.R:
--------------------------------------------------------------------------------
1 | library(devtools)
2 | library(knitr)
3 |
4 |
5 | # compile Readme
6 | knit("README.Rmd", "README.md")
7 | test("pkg")
8 |
9 |
10 | document("pkg")
11 | build_vignettes("pkg")
12 | check("pkg")
13 | build("pkg")
14 |
15 |
--------------------------------------------------------------------------------
/experiments/Tcomp-checks.R:
--------------------------------------------------------------------------------
1 |
2 | #=============prep======================
3 | library(Tcomp)
4 | library(foreach)
5 | library(doParallel)
6 | library(forecastxgb)
7 | library(dplyr)
8 | library(ggplot2)
9 | library(scales)
10 | library(Mcomp)
11 | #============set up cluster for parallel computing===========
12 | cluster <- makeCluster(7) # only any good if you have at least 7 processors :)
13 | registerDoParallel(cluster)
14 |
15 | clusterEvalQ(cluster, {
16 | library(Tcomp)
17 | library(forecastxgb)
18 | library(Mcomp)
19 | })
20 |
21 |
22 | #===============the actual analytical function==============
23 | competition <- function(collection, maxfors = length(collection)){
24 | if(class(collection) != "Mcomp"){
25 | stop("This function only works on objects of class Mcomp, eg from the Mcomp or Tcomp packages.")
26 | }
27 | nseries <- length(collection)
28 | mases <- foreach(i = 1:maxfors, .combine = "rbind") %dopar% {
29 | thedata <- collection[[i]]
30 | seas_method <- ifelse(frequency(thedata$x) < 6, "dummies", "fourier")
31 | mod1 <- xgbar(thedata$x, trend_method = "differencing", seas_method = seas_method, lambda = 1, K = 2)
32 | fc1 <- forecast(mod1, h = thedata$h)
33 | fc2 <- thetaf(thedata$x, h = thedata$h)
34 | fc3 <- forecast(auto.arima(thedata$x), h = thedata$h)
35 | fc4 <- forecast(nnetar(thedata$x), h = thedata$h)
36 | # copy the skeleton of fc1 over for ensembles:
37 | fc12 <- fc13 <- fc14 <- fc23 <- fc24 <- fc34 <- fc123 <- fc124 <- fc134 <- fc234 <- fc1234 <- fc1
38 | # replace the point forecasts with averages of member forecasts:
39 | fc12$mean <- (fc1$mean + fc2$mean) / 2
40 | fc13$mean <- (fc1$mean + fc3$mean) / 2
41 | fc14$mean <- (fc1$mean + fc4$mean) / 2
42 | fc23$mean <- (fc2$mean + fc3$mean) / 2
43 | fc24$mean <- (fc2$mean + fc4$mean) / 2
44 | fc34$mean <- (fc3$mean + fc4$mean) / 2
45 | fc123$mean <- (fc1$mean + fc2$mean + fc3$mean) / 3
46 | fc124$mean <- (fc1$mean + fc2$mean + fc4$mean) / 3
47 | fc134$mean <- (fc1$mean + fc3$mean + fc4$mean) / 3
48 | fc234$mean <- (fc2$mean + fc3$mean + fc4$mean) / 3
49 | fc1234$mean <- (fc1$mean + fc2$mean + fc3$mean + fc4$mean) / 4
50 | mase <- c(accuracy(fc1, thedata$xx)[2, 6],
51 | accuracy(fc2, thedata$xx)[2, 6],
52 | accuracy(fc3, thedata$xx)[2, 6],
53 | accuracy(fc4, thedata$xx)[2, 6],
54 | accuracy(fc12, thedata$xx)[2, 6],
55 | accuracy(fc13, thedata$xx)[2, 6],
56 | accuracy(fc14, thedata$xx)[2, 6],
57 | accuracy(fc23, thedata$xx)[2, 6],
58 | accuracy(fc24, thedata$xx)[2, 6],
59 | accuracy(fc34, thedata$xx)[2, 6],
60 | accuracy(fc123, thedata$xx)[2, 6],
61 | accuracy(fc124, thedata$xx)[2, 6],
62 | accuracy(fc134, thedata$xx)[2, 6],
63 | accuracy(fc234, thedata$xx)[2, 6],
64 | accuracy(fc1234, thedata$xx)[2, 6])
65 | mase
66 | }
67 | message("Finished fitting models")
68 | colnames(mases) <- c("x", "f", "a", "n", "xf", "xa", "xn", "fa", "fn", "an",
69 | "xfa", "xfn", "xan", "fan", "xfan")
70 | return(mases)
71 | }
72 |
73 |
74 |
75 | ## Test on a small set of data, useful during dev
76 | small_collection <- list(tourism[[100]], tourism[[200]], tourism[[300]], tourism[[400]], tourism[[500]], tourism[[600]])
77 | class(small_collection) <- "Mcomp"
78 | test1 <- competition(small_collection)
79 | round(test1, 1)
80 |
81 | #========Fit models==============
82 | system.time(t1 <- competition(subset(tourism, "yearly")))
83 | system.time(t4 <- competition(subset(tourism, "quarterly")))
84 | system.time(t12 <- competition(subset(tourism, "monthly")))
85 |
86 |
87 | system.time(m1 <- competition(subset(M3, "yearly")))
88 | system.time(m4 <- competition(subset(M3, "quarterly")))
89 | system.time(m12 <- competition(subset(M3, "monthly")))
90 | system.time(mo <- competition(subset(M3, "other")))
91 |
92 | # shut down cluster to avoid any mess:
93 | stopCluster(cluster)
94 |
95 |
96 | #==============present tourism results================
97 | results <- c(apply(t1, 2, mean),
98 | apply(t4, 2, mean),
99 | apply(t12, 2, mean))
100 |
101 | results_df <- data.frame(MASE = results)
102 | results_df$model <- as.character(names(results))
103 | periods <- c("Annual", "Quarterly", "Monthly")
104 | results_df$Frequency <- rep.int(periods, times = c(15, 15, 15))
105 |
106 | best <- results_df %>%
107 | group_by(model) %>%
108 | summarise(MASE = mean(MASE)) %>%
109 | arrange(MASE) %>%
110 | mutate(Frequency = "Average")
111 |
112 | Tcomp_results <- results_df %>%
113 | rbind(best) %>%
114 | mutate(model = factor(model, levels = best$model)) %>%
115 | mutate(Frequency = factor(Frequency, levels = c("Annual", "Average", "Quarterly", "Monthly")))
116 |
117 | save(Tcomp_results, file = "pkg/data/Tcomp_results.rda")
118 |
119 | leg <- "f: Theta; forecast::thetaf\na: ARIMA; forecast::auto.arima
120 | n: Neural network; forecast::nnetar\nx: Extreme gradient boosting; forecastxgb::xgbar"
121 |
122 | Tcomp_results %>%
123 | ggplot(aes(x = model, y = MASE, colour = Frequency, label = model)) +
124 | geom_text(size = 6) +
125 | geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
126 | scale_y_continuous("Mean scaled absolute error\n(smaller numbers are better)") +
127 | annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
128 | ggtitle("Average error of four different timeseries forecasting methods\n2010 Tourism Forecasting Competition data") +
129 | labs(x = "Model, or ensemble of models\n(further to the left means better overall performance)")
130 |
131 |
132 |
133 | # the results for Theta and ARIMA match those at
134 | # https://cran.r-project.org/web/packages/Tcomp/vignettes/tourism-comp.html
135 |
136 |
137 | #======================Present M3 results========================
138 | results <- c(apply(m1, 2, mean),
139 | apply(m4, 2, mean),
140 | apply(m12, 2, mean),
141 | apply(mo, 2, mean))
142 |
143 | results_df <- data.frame(MASE = results)
144 | results_df$model <- as.character(names(results))
145 | periods <- c("Annual", "Quarterly", "Monthly", "Other")
146 | results_df$Frequency <- rep.int(periods, times = c(15, 15, 15, 15))
147 |
148 | best <- results_df %>%
149 | group_by(model) %>%
150 | summarise(MASE = mean(MASE)) %>%
151 | arrange(MASE) %>%
152 | mutate(Frequency = "Average")
153 |
154 | Mcomp_results <- results_df %>%
155 | rbind(best) %>%
156 | mutate(model = factor(model, levels = best$model)) %>%
157 | mutate(Frequency = factor(Frequency, levels = c("Annual", "Average", "Quarterly", "Monthly", "Other")))
158 |
159 | save(Mcomp_results, file = "pkg/data/Mcomp_results.rda")
160 |
161 | leg <- "f: Theta; forecast::thetaf\na: ARIMA; forecast::auto.arima
162 | n: Neural network; forecast::nnetar\nx: Extreme gradient boosting; forecastxgb::xgbar"
163 |
164 | Mcomp_results %>%
165 | ggplot(aes(x = model, y = MASE, colour = Frequency, label = model)) +
166 | geom_text(size = 6) +
167 | geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
168 | scale_y_continuous("Mean scaled absolute error\n(smaller numbers are better)") +
169 | annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
170 | ggtitle("Average error of four different timeseries forecasting methods\nM3 Forecasting Competition data") +
171 | labs(x = "Model, or ensemble of models\n(further to the left means better overall performance)")
172 |
173 |
--------------------------------------------------------------------------------
/experiments/experiments.R:
--------------------------------------------------------------------------------
1 | library(forecastxgb)
2 |
3 | fc1 <- forecast(auto.arima(AirPassengers), level = FALSE, h = 36)
4 | accuracy(fc1)
5 | object <- xgbar(AirPassengers, maxlag = 12)
6 | plot(object)
7 |
8 | fc2 <- forecast(object, h = 36)
9 | plot(fc1)
10 | plot(fc2)
11 | accuracy(fc2) # looks like rather extreme overfitting!
12 |
13 | xgb.importance(colnames(object$x), model = object$model)
14 |
15 | fc1$mean
16 | fc2$mean
17 | fc2$x
18 | fc1$x
19 |
20 | names(fc1)
21 |
22 | class(fc1$x)
23 | class(fc2$x)
24 | class(fc1$mean)
25 | class(fc2$mean)
26 | frequency(fc1$mean)
27 | frequency(fc2$mean)
28 | fc1$fitted
29 | fc2$fitted
30 | fc1$model
31 | fc2$model
32 | fc1$x
33 | fc2$x
34 | fc1$method
35 | fc2$method
36 | plot(fc1)
37 | plot(fc2)
38 |
39 | modnile <- xgbar(Nile, maxlag = 4)
40 | plot(modnile)
41 |
--------------------------------------------------------------------------------
/experiments/explore-trends.R:
--------------------------------------------------------------------------------
1 | library(forecastxgb)
2 | library(dplyr)
3 | library(ggplot2)
4 | library(gridExtra)
5 | # rubbish at picking trends. Why?
6 |
7 | #--------simulated data--------------
8 | y <- ts(1:100 * rnorm(100, 1, 0.01), frequency = 1)
9 | plot(y)
10 |
11 |
12 | mod1 <- auto.arima(y)
13 | mod2 <- naive(y,h = 20)
14 | mod3 <- ets(y)
15 | mod4 <- nnetar(y)
16 | p1 <- autoplot(forecast(mod1, h = 20))
17 | p2 <- autoplot(forecast(mod2, h = 20))
18 | p3 <- autoplot(forecast(mod3, h = 20))
19 | p4 <- autoplot(forecast(mod4, h = 20))
20 |
21 | grid.arrange(p1, p2, p3, p4)
22 |
23 |
24 | mod5 <- xgbar(y, maxlag = 8)
25 | fc5 <- forecast(mod5, h = 20)
26 | p5 <- autoplot(fc5)
27 | p5
28 | fc5$newx
29 | names(fc5)
30 |
31 |
32 | grid.arrange(p1, p3, p4, p5)
33 |
34 | #----------------real data--------------
35 | mod1 <- xgbar(AirPassengers, seas_method = "fourier", trend_method = "differencing")
36 | mod2 <- xgbar(AirPassengers, seas_method = "dummies", trend_method = "differencing")
37 | mod3 <- xgbar(AirPassengers, seas_method = "decompose", trend_method = "differencing")
38 | mod4 <- xgbar(AirPassengers, seas_method = "fourier", trend_method = "none")
39 | mod5 <- xgbar(AirPassengers, seas_method = "dummies", trend_method = "none")
40 | mod6 <- xgbar(AirPassengers, seas_method = "decompose", trend_method = "none")
41 | mod7 <- xgbar(AirPassengers, seas_method = "fourier", trend_method = "differencing", lambda = 1)
42 | mod8 <- xgbar(AirPassengers, seas_method = "dummies", trend_method = "differencing", lambda = 1)
43 | mod9 <- xgbar(AirPassengers, seas_method = "decompose", trend_method = "differencing", lambda = 1)
44 |
45 |
46 |
47 | fc1 <- forecast(mod1, h = 24)
48 | fc2 <- forecast(mod2, h = 24)
49 | fc3 <- forecast(mod3, h = 24)
50 | fc4 <- forecast(mod4, h = 24)
51 | fc5 <- forecast(mod5, h = 24)
52 | fc6 <- forecast(mod6, h = 24)
53 | fc7 <- forecast(mod7, h = 24)
54 | fc8 <- forecast(mod8, h = 24)
55 | fc9 <- forecast(mod9, h = 24)
56 |
57 |
58 | plot(fc1)
59 | plot(fc2)
60 | plot(fc3)
61 | plot(fc4)
62 | plot(fc5)
63 | plot(fc6)
64 | plot(fc7)
65 | plot(fc8)
66 | plot(fc9)
67 |
68 |
69 |
70 | mod9 <- xgbar(AirPassengers, seas_method = "decompose", trend_method = "differencing")
71 | fc9 <- forecast(mod9, h = 24)
72 | plot(fc9)
73 |
--------------------------------------------------------------------------------
/experiments/maxlags-experiment.R:
--------------------------------------------------------------------------------
1 | library(forecastxgb)
2 | library(Mcomp)
3 | library(foreach)
4 | library(doParallel)
5 |
6 |
7 | cluster <- makeCluster(4)
8 | registerDoParallel(cluster)
9 |
10 | clusterEvalQ(cluster, {
11 | library(Tcomp)
12 | library(forecastxgb)
13 | library(Mcomp)
14 | })
15 |
16 | collection <- subset(M1, "quarterly")
17 |
18 |
19 | #================identify best maxlags for a collection=====================
20 | allmases <- list(length(collection))
21 |
22 | for(i in 1:length(collection)){
23 | cat(paste("Dataset", i, "\n"))
24 | thedata <- collection[[i]]
25 |
26 | n <- length(thedata$x)
27 | f <- frequency(thedata$x)
28 | maxP <- trunc(n / f / 2)
29 | thedata_mases <- numeric(maxP)
30 |
31 | for(p in 1:maxP){
32 | mod <- xgbar(thedata$x, maxlag = p * f, nrounds_method = "cv")
33 | fc <- forecast(mod, h = thedata$h)
34 | thisacc <- accuracy(fc, thedata$xx)[2, 6]
35 | print(thisacc)
36 | thedata_mases[p] <- thisacc
37 | }
38 | thedata_mases_rounded <- round(thedata_mases, 1)
39 | bl <- min(which(thedata_mases_rounded == min(thedata_mases_rounded, na.rm = TRUE))) * f
40 |
41 | allmases[[i]] <- list(mases = thedata_mases, bl = bl, n = n, f = f)
42 |
43 | }
44 |
45 | # issue - crashes with the 7th quarterly dataset. n = 13, f = 4. Too short even for v validation.
--------------------------------------------------------------------------------
/experiments/seasonal-adjustment-experiments.R:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | model1 <- xgbar(AirPassengers, maxlag = 24, trend_method = "none", seas_method = "dummies")
5 | model2 <- xgbar(AirPassengers, maxlag = 24, trend_method = "none", seas_method = "decompose")
6 | model3 <- xgbar(AirPassengers, maxlag = 24, trend_method = "none", seas_method = "fourier")
7 | model4 <- xgbar(AirPassengers, maxlag = 24, trend_method = "none", seas_method = "none")
8 |
9 | model5 <- xgbar(AirPassengers, maxlag = 24, trend_method = "differencing", seas_method = "dummies")
10 | model6 <- xgbar(AirPassengers, maxlag = 24, trend_method = "differencing", seas_method = "decompose")
11 | model7 <- xgbar(AirPassengers, maxlag = 24, trend_method = "differencing", seas_method = "fourier")
12 | model8 <- xgbar(AirPassengers, maxlag = 24, trend_method = "differencing", seas_method = "none")
13 |
14 | fc1 <- forecast(model1, h = 24)
15 | fc2 <- forecast(model2, h = 24)
16 | fc3 <- forecast(model3, h = 24)
17 | fc4 <- forecast(model4, h = 24)
18 |
19 | fc5 <- forecast(model5, h = 24)
20 | fc6 <- forecast(model6, h = 24)
21 | fc7 <- forecast(model7, h = 24)
22 | fc8 <- forecast(model8, h = 24)
23 |
24 |
25 | par(mfrow = c(2, 2), bty = "l")
26 | plot(fc1, main = "dummies"); grid()
27 | plot(fc2, main = "decompose"); grid()
28 | plot(fc3, main = "fourier"); grid()
29 | plot(fc4, main = "none"); grid()
30 |
31 |
32 | par(mfrow = c(2, 2), bty = "l")
33 | plot(fc5, main = "dummies"); grid()
34 | plot(fc6, main = "decompose"); grid()
35 | plot(fc7, main = "fourier"); grid()
36 | plot(fc8, main = "none"); grid()
37 |
38 |
39 | summary(model3)
40 |
--------------------------------------------------------------------------------
/experiments/validation.R:
--------------------------------------------------------------------------------
1 |
2 |
3 | validate_xgbar(Nile)
4 | tmp <- xgbar(Nile)
5 |
6 | validate_xgbar(AirPassengers)
7 | tmp <- xgbar(AirPassengers)
8 |
9 | validate_xgbar(WWWusage)
10 | tmp <- xgbar(WWWusage)
11 |
12 | validate_xgbar(USAccDeaths)
13 | tmp <- xgbar(USAccDeaths)
--------------------------------------------------------------------------------
/experiments/xreg-experiments.R:
--------------------------------------------------------------------------------
1 | library(fpp)
2 | fit1 <- Arima(usconsumption[,1], xreg=usconsumption[,2],
3 | order=c(2,0,0))
4 | tsdisplay(arima.errors(fit1), main="ARIMA errors")
5 | summary(fit1)
6 | fc1 <- forecast(fit1, xreg = income_future)
7 | names(fc1)
8 | fc$method
9 |
10 | fit2 <- xgbar(y = usconsumption[,1], xreg = matrix(usconsumption[,2], dimnames = list(NULL, "Income")))
11 | fit3 <- xgbar(y = usconsumption[,1])
12 | forecast(fit3)
13 | summary(fit2)
14 | fit2$origxreg
15 |
16 |
17 | income_future <- matrix(forecast(xgbar(usconsumption[,2]), h = 10)$mean, dimnames = list(NULL, "Income"))
18 |
19 | fc2 <- forecast(object = fit2, xreg = income_future)
20 | plot(fc2)
21 |
22 | fc3 <- forecast(fit3)
23 | plot(fit2)
24 | plot(fc3)
25 | names(fc2)
26 | fc2$method
27 | fc1$method
28 | fc2$model
29 | class(fc1$model)
30 |
31 | class(xreg)
32 | plot(xreg)
33 | is.numeric(xreg)
34 | as.matrix(xreg)
35 | dim(xreg)
36 | ncol(xreg)
37 |
--------------------------------------------------------------------------------
/figure/unnamed-chunk-10-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-10-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-16-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-16-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-17-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-17-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-2-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-2-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-3-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-3-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-3-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-3-2.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-4-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-4-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-5-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-5-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-6-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-6-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-7-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-7-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-8-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-8-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-8-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-8-2.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-8-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-8-3.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-9-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-9-1.png
--------------------------------------------------------------------------------
/figure/unnamed-chunk-9-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/figure/unnamed-chunk-9-2.png
--------------------------------------------------------------------------------
/forecastxg-r-package.Rproj:
--------------------------------------------------------------------------------
1 | Version: 1.0
2 |
3 | RestoreWorkspace: Default
4 | SaveWorkspace: Default
5 | AlwaysSaveHistory: Default
6 |
7 | EnableCodeIndexing: Yes
8 | UseSpacesForTab: Yes
9 | NumSpacesForTab: 2
10 | Encoding: UTF-8
11 |
12 | RnwWeave: knitr
13 | LaTeX: pdfLaTeX
14 |
15 | BuildType: Package
16 | PackageUseDevtools: Yes
17 | PackagePath: pkg
18 | PackageInstallArgs: --no-multiarch --with-keep.source
19 | PackageRoxygenize: rd,collate,namespace
20 |
--------------------------------------------------------------------------------
/pkg/.Rbuildignore:
--------------------------------------------------------------------------------
1 | ^.*\.Rproj$
2 | ^\.Rproj\.user$
3 |
--------------------------------------------------------------------------------
/pkg/DESCRIPTION:
--------------------------------------------------------------------------------
1 | Package: forecastxgb
2 | Title: Time Series Models and Forecasts using "xgboost"
3 | Version: 0.1.2.9000
4 | Authors@R: person("Peter", "Ellis", email = "peter.ellis2013nz@gmail.com", role = c("aut", "cre"))
5 | Description: What the package does (one paragraph).
6 | Depends:
7 | R (>= 3.1.2),
8 | forecast,
9 | xgboost (>= 0.6-4)
10 | License: GPL-3
11 | Encoding: UTF-8
12 | LazyData: true
13 | RoxygenNote: 6.0.1
14 | Imports:
15 | tseries
16 | Suggests:
17 | testthat,
18 | knitr,
19 | rmarkdown,
20 | Tcomp,
21 | foreach,
22 | doParallel,
23 | dplyr,
24 | ggplot2,
25 | scales,
26 | fpp
27 | VignetteBuilder: knitr
28 |
--------------------------------------------------------------------------------
/pkg/NAMESPACE:
--------------------------------------------------------------------------------
1 | # Generated by roxygen2: do not edit by hand
2 |
3 | S3method(forecast,xgbar)
4 | S3method(plot,xgbar)
5 | S3method(print,summary.xgbar)
6 | S3method(summary,xgbar)
7 | export(xgbar)
8 | export(xgbar_importance)
9 | import(forecast)
10 | import(graphics)
11 | import(stats)
12 | import(xgboost)
13 | importFrom(tseries,kpss.test)
14 | importFrom(utils,tail)
15 |
--------------------------------------------------------------------------------
/pkg/R/extras.R:
--------------------------------------------------------------------------------
1 | #' Show importance of features in a xgbar model
2 | #'
3 | #' This is a light wrapper for \code{xgboost::xbg.importance} to make it easier to use with objects of class \code{xgbar}
4 | #' @export
5 | #' @param object An object of class \code{xgbar}, usually created with \code{xgbar()}
6 | #' @param ... Extra parameters passed through to \code{xgb.importance}
7 | #' @return A \code{data.table} of the features used in the model with their average gain
8 | #' (and their weight for boosted tree model) in the model.
9 | #' @seealso \code{\link[xgboost]{xgb.importance}}, \code{\link{summary.xgbar}}, \code{\link{xgbar}}.
10 | #' @author Peter Ellis
11 | xgbar_importance <- function(object, ...){
12 | if(class(object) != "xgbar"){
13 | stop("'object' should be an object of class xgbar.")
14 | }
15 | xgb.importance(colnames(object$x), model = object$model, ...)
16 | }
17 |
18 | #' Summary of an xgbar object
19 | #'
20 | #' summary method for an object created by xgbar
21 | #' @aliases print.summary.xgbar
22 | #' @export
23 | #' @param object An object created by \code{\link{xgbar}}
24 | #' @param ... Ignored.
25 | #' @author Peter Ellis
26 | #' @seealso \code{\link{xgbar}}
27 | #' @examples
28 | #' \dontrun{
29 | #' # Half-hourly electricity demand in England and Wales, takes a few minutes
30 | #' electricity_model <- xgbar(taylor)
31 | #' summary(electricity_model)
32 | #' electricity_fc <- forecast(electricity_model, h = 500)
33 | #' plot(electricity_fc)
34 | #' }
35 | summary.xgbar <- function(object, ...){
36 | ans <- object
37 | ans$importance <- xgbar_importance(object)
38 | ans$n <- length(object$y)
39 | ans$effectn <- length(object$y2)
40 | ans$ncolx <- ncol(object$x)
41 | class(ans) <- "summary.xgbar"
42 | return(ans)
43 | }
44 |
45 | #' @export
46 | #' @method print summary.xgbar
47 | print.summary.xgbar <- function(x, ...){
48 |
49 | cat("\nImportance of features in the xgboost model:\n")
50 | print(x$importance)
51 |
52 | cat(paste("\n", x$ncolx, "features considered.\n"))
53 | cat(paste0(x$n, " original observations.\n",
54 | x$effectn, " effective observations after creating lagged features.\n"))
55 | }
56 |
57 |
58 | #' Plot xgbar object
59 | #'
60 | #' plot method for an object created by xgbar
61 | #' @export
62 | #' @import graphics
63 | #' @method plot xgbar
64 | #' @param x An object created by \code{xgbar}
65 | #' @param ... Additional arguments passed through to \code{plot()}
66 | #' @author Peter Ellis
67 | #' @seealso \code{\link{xgbar}}
68 | #' @examples
69 | #' model <- xgbar(AirPassengers)
70 | #' plot(model)
71 | plot.xgbar <- function(x, ...){
72 | ts.plot(x$y, col = "brown", ...)
73 | lines(x$fitted, col = "blue")
74 |
75 | }
76 |
77 |
78 | #' Tourism forecasting results
79 | #'
80 | #' Summary data from four models, and 11 combinations of models, against the data from the 2010 tourism forecasting competition.
81 | #'
82 | #' Full details of how this was generated are in the Vignette. This shows the average mean absolute scaled error
83 | #' (MASE) from using \code{xgbar} (x), \code{auto.arima} (a), \code{nnetar} (n) and \code{thetaf} (f) to generate forecasts of 1,311 tourism data series.
84 | #'
85 | #'
86 | #' \itemize{
87 | #' \item MASE A mean mean absolute squared error
88 | #' \item model model, or ensemble of models, to which the MASE applies
89 | #' \item Frequency The frequency of the subset of data from which the mean MASE was calculated.
90 | #' }
91 | #' @format A data frame with 60 rows and three columns.
92 | #' @author Peter Ellis
93 | #' @examples
94 | #' if(require(ggplot2)){
95 | #' leg <- "f: Theta; forecast::thetaf\na: ARIMA; forecast::auto.arima
96 | #' n: Neural network; forecast::nnetar\nx: Extreme gradient boosting; forecastxgb::xgbar"
97 | #'
98 | #' ggplot(Tcomp_results, aes(x = model, y = MASE, colour = Frequency, label = model)) +
99 | #' geom_text(size = 4) +
100 | #' geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
101 | #' annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
102 | #' ggtitle("Average error of four different timeseries forecasting methods
103 | #'2010 Tourism Forecasting Competition data") +
104 | #' labs(x = "Model, or ensemble of models
105 | #'(further to the left means better overall performance)",
106 | #' y = "Mean scaled absolute error\n(smaller numbers are better)") +
107 | #' theme_grey(9)
108 | #' }
109 | "Tcomp_results"
110 |
111 |
112 |
113 | #' M3 forecasting results
114 | #'
115 | #' Summary data from four models, and 11 combinations of models, against the data from the M3 forecasting competition.
116 | #'
117 | #' Full details are in the vignette of how a similar series with tourism competition data was generated.
118 | #' The data shows the average mean absolute scaled error
119 | #' (MASE) from using \code{xgbar} (x), \code{auto.arima} (a), \code{nnetar} (n) and \code{thetaf} (f) to
120 | #' generate forecasts of 3,003 data series from a range of sectors, in the M3 forecasting competition.
121 | #'
122 | #'
123 | #' \itemize{
124 | #' \item MASE A mean mean absolute squared error
125 | #' \item model model, or ensemble of models, to which the MASE applies
126 | #' \item Frequency The frequency of the subset of data from which the mean MASE was calculated.
127 | #' }
128 | #' @format A data frame with 75 rows and three columns.
129 | #' @author Peter Ellis
130 | #' @examples
131 | #' if(require(ggplot2)){
132 | #' leg <- "f: Theta; forecast::thetaf\na: ARIMA; forecast::auto.arima
133 | #' n: Neural network; forecast::nnetar\nx: Extreme gradient boosting; forecastxgb::xgbar"
134 | #'
135 | #' ggplot(Mcomp_results, aes(x = model, y = MASE, colour = Frequency, label = model)) +
136 | #' geom_text(size = 4) +
137 | #' geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
138 | #' annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
139 | #' ggtitle("Average error of four different timeseries forecasting methods
140 | #'M3 Forecasting Competition data") +
141 | #' labs(x = "Model, or ensemble of models
142 | #'(further to the left means better overall performance)",
143 | #' y = "Mean scaled absolute error\n(smaller numbers are better)") +
144 | #' theme_grey(9)
145 | #' }
146 | "Mcomp_results"
147 |
148 |
149 |
--------------------------------------------------------------------------------
/pkg/R/forecast.xgbar.R:
--------------------------------------------------------------------------------
1 | #' Forecasting using xgboost models
2 | #'
3 | #' Returns forecasts and other information for xgboost timeseries modesl fit with \code{xbgts}
4 | #'
5 | #' @export
6 | #' @import forecast
7 | #' @import xgboost
8 | #' @importFrom utils tail
9 | #' @method forecast xgbar
10 | #' @param object An object of class "\code{xgbar}". Usually the result of a call to \code{\link{xgbar}}.
11 | #' @param h Number of periods for forecasting. If \code{xreg} is provided, the number of rows of \code{xreg} will be
12 | #' used and \code{h} is ignored with a warning. If both \code{h} and \code{xreg} are \code{NULL} then
13 | #' \code{h = ifelse(frequency(object$y) > 1, 2 * frequency(object$y), 10)}
14 | #' @param xreg Future values of regression variables.
15 | #' @param ... Ignored.
16 | #' @return An object of class \code{forecast}
17 | #' @author Peter Ellis
18 | #' @seealso \code{\link{xgbar}}, \code{\link[forecast]{forecast}}
19 | #' @examples
20 | #' # Australian monthly gas production
21 | #' gas_model <- xgbar(gas)
22 | #' summary(gas_model)
23 | #' gas_fc <- forecast(gas_model, h = 12)
24 | #' plot(gas_fc)
25 | forecast.xgbar <- function(object,
26 | h = NULL,
27 | xreg = NULL, ...){
28 | # validity checks on xreg
29 | if(!is.null(xreg)){
30 | if(is.null(object$ncolxreg)){
31 | stop("You supplied an xreg, but there is none in the original xgbar object.")
32 | }
33 |
34 | if(class(xreg) == "ts" | "data.frame" %in% class(xreg)){
35 | message("Converting xreg into a matrix")
36 | # TODO - not sure this works when it's two dimensional
37 | xreg <- as.matrix(xreg)
38 | }
39 |
40 | if(!is.numeric(xreg) | !is.matrix(xreg)){
41 | stop("xreg should be a numeric and able to be coerced to a matrix")
42 | }
43 |
44 | if(ncol(xreg) != object$ncolxreg){
45 | stop("Number of columns in xreg doesn't match the original xgbar object.")
46 | }
47 |
48 | if(!is.null(h)){
49 | warning(paste("Ignoring h and forecasting", nrow(xreg), "periods from xreg."))
50 | }
51 |
52 | # add the lagged versions of xreg. Some of the lags need to come from the original data
53 | h <- nrow(xreg)
54 | xreg2 <- lagvm(rbind(xreg, object$origxreg), maxlag = object$maxlag)
55 | # we just want the last h rows of that big matrix:
56 | nn <- nrow(xreg2)
57 | xreg3 <- xreg2[(nn - h + 1):nn, ]
58 | }
59 |
60 | if(is.null(h)){
61 | h <- ifelse(frequency(object$y) > 1, 2 * frequency(object$y), 10)
62 | message(paste("No h provided so forecasting forward", h, "periods."))
63 | }
64 |
65 | # clear up space to avoid using an old xreg3 if it exists
66 | if(is.null(xreg)){
67 | xreg3 <- NULL
68 | }
69 |
70 | f <- frequency(object$y)
71 | lambda <- object$lambda
72 | seas_method <- object$seas_method
73 |
74 | # forecast time x variable
75 | htime <- time(ts(rep(0, h), frequency = f, start = max(time(object$y)) + 1 / f))
76 |
77 | # forecast fourier pairs
78 | if(f > 1 & seas_method == "fourier"){
79 | fxh <- fourier(object$y2, K = object$K, h = h)
80 | }
81 |
82 | forward1 <- function(x, y, model, xregpred, i){
83 | newrow <- c(
84 | # latest lagged value:
85 | y[length(y)],
86 | # previous lagged values:
87 | x[nrow(x), 1:(object$maxlag - 1)])
88 | if(object$maxlag == 1){
89 | newrow = newrow[-1]
90 | }
91 |
92 | # seasonal dummies if 'dummies':
93 | if(f > 1 & seas_method == "dummies"){
94 | # for dummy variables it's ok to just take the set of dummies from f time periods before:
95 | newrow <- c(newrow, x[(nrow(x) + 1 - f), (object$maxlag + 1):(object$maxlag + f - 1)])
96 | }
97 | # seasonal dummies if 'fourier':
98 | if(f > 1 & seas_method == 'fourier'){
99 | # for fourier variables,
100 | newrow <- c(newrow, fxh[i, ])
101 | }
102 |
103 | if(!is.null(xregpred)){
104 | newrow <- c(newrow, xregpred)
105 | }
106 |
107 | newrow <- matrix(newrow, nrow = 1)
108 | colnames(newrow) <- colnames(x)
109 |
110 | pred <- predict(model, newdata = newrow)
111 |
112 | return(list(
113 | x = rbind(x, newrow),
114 | y = c(y, pred)
115 | ))
116 | }
117 |
118 | x <- object$x
119 | y <- object$y2
120 |
121 |
122 | for(i in 1:h){
123 | tmp <- forward1(x, y, model = object$model, xregpred = xreg3[i, ], i = i)
124 | x <- tmp$x
125 | y <- tmp$y
126 | }
127 |
128 |
129 | # fitted and forecast object, on possibly untransformed, undifferenced and seasonally adjusted scale
130 | y <- ts(y[-(1:length(object$y2))],
131 | frequency = f,
132 | start = max(time(object$y)) + 1 / f)
133 |
134 | # back transform the differencing
135 | if(object$diffs > 0){
136 | for(i in 1:object$diffs){
137 | y <- ts(cumsum(y) , start = start(y), frequency = f)
138 | }
139 | y <- y + JDMod(object$y[length(object$y)], lambda = lambda)
140 | }
141 |
142 | # back transform the seasonal adjustment:
143 | if(seas_method == "decompose"){
144 | multipliers <- utils::tail(object$decomp$seasonal, f)
145 | if(h < f){
146 | multipliers <- multipliers[1:h]
147 | }
148 | y <- y * as.vector(multipliers)
149 | }
150 |
151 | # back transform the modulus power transform:
152 | y <- InvJDMod(y, lambda = lambda)
153 |
154 | output <- list(
155 | x = object$y,
156 | mean = y,
157 | fitted = object$fitted,
158 | newx = x,
159 | method = object$method
160 | )
161 | class(output) <- "forecast"
162 | return(output)
163 |
164 | }
165 |
--------------------------------------------------------------------------------
/pkg/R/forecastxgb.R:
--------------------------------------------------------------------------------
1 | #' Extreme gradient boosting time series forecasting
2 | #'
3 | #' The \code{forecastxgb} package provides time series modelling and forecasting functions that combine
4 | #' the machine learning approach of Chen, He and Benesty's \code{xgboost}
5 | #' with the convenient handling of time series and familiar API of Rob Hyndman's \code{forecast}.
6 | #'
7 | #' It applies to time series the Extreme Gradient Boosting proposed in \emph{Greedy Function Approximation: A
8 | #' Gradient Boosting Machine, by Jermoe Friedman in 2001} (http://www.jstor.org/stable/2699986).
9 | #'
10 | "_PACKAGE"
--------------------------------------------------------------------------------
/pkg/R/misc-doc.R:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | #' Arctic sea ice
6 | #'
7 | #' Extent in millions of square kilometres of sea ice in the Arctic from 21 August 1987 to 24 November 2016.
8 | #'
9 | #' @source National Snow and Ice Data Center, \url{https://nsidc.org/data/docs/noaa/g02135_seaice_index/#daily_data_files"}
10 | #' @examples
11 | #' plot(seaice_ts)
12 | "seaice_ts"
--------------------------------------------------------------------------------
/pkg/R/utils.R:
--------------------------------------------------------------------------------
1 |
2 | # not exported
3 | # function to take a vector and create a matrix of itself and lagged values
4 | lagv <- function(x, maxlag, keeporig = TRUE){
5 | if(!is.vector(x) & !is.ts(x)){
6 | stop("x must be a vector or time series")
7 | }
8 | x <- as.vector(x)
9 | n <- length(x)
10 | z <- matrix(0, nrow = (n - maxlag), ncol = maxlag + 1)
11 | for(i in 1:ncol(z)){
12 | z[ , i] <- x[(maxlag + 2 - i):(n + 1 - i)]
13 | }
14 | varname <- "x"
15 | colnames(z) <- c(varname, paste0(varname, "_lag", 1:maxlag))
16 | if(!keeporig){
17 | z <- z[ ,-1]
18 | }
19 | return(z)
20 | }
21 |
22 | # not exported
23 | # function to take a matrix and make a wider matrix with many lagged versions
24 | lagvm <- function(x, maxlag){
25 | if(!is.matrix(x)){
26 | stop("X needs to be a matrix")
27 | }
28 |
29 | if(is.null(colnames(x))){
30 | colnames(x) <- paste0("Var", 1:ncol(x))
31 | }
32 | n <- nrow(x)
33 | M <- matrix(0, nrow = (n - maxlag), ncol = (maxlag + 1) * ncol(x))
34 | for(i in 1:ncol(x)){
35 | M[ , 1:(maxlag + 1) + (i - 1) * (maxlag + 1)] <- lagv(x[ ,i], maxlag = maxlag)
36 | }
37 | thenames <- character()
38 | for(i in 1:ncol(x)){
39 | thenames <- c(thenames, paste0(colnames(x)[i], "_lag", 0:maxlag))
40 | }
41 | colnames(M) <- thenames
42 |
43 | return(M)
44 | }
45 |
46 |
47 | # not exported
48 | # function to perform transformation as per John and Draper's "An Alternative Family of Transformations"
49 | # John and Draper's modulus transformation
50 | JDMod <- function(y, lambda){
51 | if(lambda != 0){
52 | yt <- sign(y) * (((abs(y) + 1) ^ lambda - 1) / lambda)
53 | } else {
54 | yt = sign(y) * (log(abs(y) + 1))
55 | }
56 | return(yt)
57 | }
58 |
59 | InvJDMod <- function(yt, lambda){
60 | if(lambda != 0){
61 | y <- ((abs(yt) * lambda + 1) ^ (1 / lambda) - 1) * sign(yt)
62 | } else {
63 | y <- (exp(abs(yt)) - 1) * sign(yt)
64 |
65 | }
66 | return(y)
67 | }
68 |
69 |
--------------------------------------------------------------------------------
/pkg/R/validate_xgbar.R:
--------------------------------------------------------------------------------
1 | validate_xgbar <- function(y, xreg = NULL, nrounds = 50, ...){
2 | n <- length(y)
3 | spl <- round(0.8 * n)
4 |
5 | trainy <- ts(y[1:spl], start = start(y), frequency = frequency(y))
6 | testy <- y[(spl + 1):n]
7 | h <- length(testy)
8 |
9 | if(!is.null(xreg)){
10 | trainxreg <- xreg[1:spl, ]
11 | testxreg <- xreg[(spl + 1):n, ]
12 | }
13 |
14 | grunt <- function(nrounds){
15 | if(!is.null(xreg)){
16 | trainmod <- xgbar(trainy, xreg = xreg, nrounds_method = "manual", nrounds = nrounds)
17 | } else {
18 | trainmod <- xgbar(trainy, nrounds_method = "manual", nrounds = nrounds)
19 | }
20 | fc <- forecast(trainmod, h = h)
21 | result <- accuracy(fc, testy)[2,6]
22 | return(result)
23 | }
24 |
25 | mases <- sapply(as.list(1:nrounds), grunt)
26 |
27 | best_nrounds <- min(which(mases == min(mases)))
28 | output <- list(
29 | best_nrounds = best_nrounds,
30 | best_mase = min(mases)
31 | )
32 | return(output)
33 | }
34 |
35 |
36 |
--------------------------------------------------------------------------------
/pkg/R/xgbar.R:
--------------------------------------------------------------------------------
1 |
2 | #' xgboost time series modelling
3 | #'
4 | #' Fit a model to a time series using xgboost
5 | #'
6 | #' @export
7 | #' @aliases xgbts
8 | #' @import xgboost
9 | #' @import forecast
10 | #' @import stats
11 | #' @importFrom tseries kpss.test
12 | #' @param y A univariate time series.
13 | #' @param xreg Optionally, a vector or matrix of external regressors, which must have the same number of rows as y.
14 | #' @param nrounds Maximum number of iterations \code{xgboost} will perform. If \code{nrounds_method = 'cv'},
15 | #' the value of \code{nrounds} passed to \code{xgboost} is chosen by cross-validation; if it is \code{'v'}
16 | #' then the value of \code{nrounds} passed to \code{xgboost} is chosen by splitting the data into a training
17 | #' set (first 80 per cent) and test set (20 per cent) and choosing the number of iterations with the best value.
18 | #' If \code{nrounds_method = 'manual'} then \code{nrounds} iterations will be performed - unless you have chosen
19 | #' it carefully this is likely to lead to overfitting and poor forecasts.
20 | #' @param nfold Number of equal size subsamples during cross validation, used if \code{nrounds_method = 'cv'}.
21 | #' @param maxlag The maximum number of lags of \code{y} and \code{xreg} (if included) to be considered as features.
22 | #' @param verbose Passed on to \code{xgboost} and \code{xgb.cv}.
23 | #' @param nrounds_method Method used to determine the value of nrounds actually given for \code{xgboost} for
24 | #' the final model. Options are \code{"cv"} for row-wise cross-validation, \code{"v"} for validation on a testing
25 | #' set of the most recent 20 per cent of data, \code{"manual"} in which case \code{nrounds} is passed through directly.
26 | #' @param lambda Value of lambda to be used for modulus power transformation of \code{y} (which is similar to Box-Cox transformation
27 | #' but works with negative values too), performed before using xgboost (and inverse transformed to the original scale afterwards).
28 | #' Set \code{lambda = 1} if no transformation is desired.
29 | #' The transformation is only applied to \code{y}, not \code{xreg}.
30 | #' @param seas_method Method for dealing with seasonality.
31 | #' @param K if \code{seas_method == 'fourier'}, the value of \code{K} passed through to \code{fourier} for order of Fourier series to be generated as seasonal regressor variables.
32 | #' @param trend_method How should the \code{xgboost} try to deal with trends? Currently the only options to \code{none} is
33 | #' \code{auto.arima}-style \code{differencing}, which is based on successive KPSS tests until there is no significant evidence the
34 | #' remaining series is non-stationary.
35 | #' @param ... Additional arguments passed to \code{xgboost}. Only works if nrounds_method is "cv" or "manual".
36 | #' @details This is the workhorse function for the \code{forecastxgb} package.
37 | #' It fits a model to a time series. Under the hood, it creates a matrix of explanatory variables
38 | #' based on lagged versions of the response time series, and (optionally) dummy variables (simple hot one encoding, or Fourier transforms) for seasons. That
39 | #' matrix is then fed as the feature set for \code{xgboost} to do its stuff.
40 | #' @return An object of class \code{xgbar}. These have a \code{forecast} method and are generally
41 | #' expected to be used in a way such as \code{forecast(my_xgbar_model, h = 24)}. But the \code{xgbar}
42 | #' object itself can be of use in model checking and diagnosis. It is list with the following elements:
43 | #' \describe{
44 | #' \item{\code{y}}{The original value of \code{y} fed to \code{xgbar}}
45 | #' \item{\code{y2}}{\code{y} except for its first \code{maxlag} values. }
46 | #' \item{\code{x}}{The features used by \code{xgboost} to model \code{y2}. \code{x} is basically
47 | #' a matrix of numbers created by the automated feature generation of \code{xgbar}, in particular
48 | #' the differencing (if asked for), seasonal adjustment (if asked for), and creation of lagged
49 | #' values. If \code{y} is univariate,
50 | #' \code{x} will be just the lagged values of \code{y} and will have \code{length(y) - maxlag} rows
51 | #' and \code{maxlag} columns. If \code{xreg} was supplied, \code{x} will have \code{maxlag * (ncol(xreg) + 1)}
52 | #' columns - a set of columns for the lagged values of y, and a set of columns for each lagged value
53 | #' of the xreg matrix.}
54 | #' \item{\code{model}}{Object of class \code{xgb.Booster} returned by \code{xgboost}. The actual
55 | #' xgboost model that regressed \code{y2} on \code{x}.}
56 | #' \item{\code{fitted}}{Fitted values of \code{y}. The first \code{maxlag} values will be \code{NA}.
57 | #' The remainder are the predicted values of the xgboost regression of \code{y2} on \code{x}.}
58 | #' \item{\code{maxlag}}{The original user-supplied value of \code{maxlag}, stored for future use by
59 | #' \code{forecast.xgbar}.}
60 | #' \item{\code{seas_method}}{The original user-supplied value of \code{seas_method}, stored for future use by
61 | #' \code{forecast.xgbar}.}
62 | #' \item{\code{diffs}}{The number of rounds of differencing applied to y to make it stationary, if
63 | #' \code{trend_method = "differencing"} was used.}
64 | #' \item{\code{lambda}}{The original user-supplied value of \code{lambda} for modulus transformation,
65 | #' stored for future use by \code{forecast.xgbar}.}
66 | #' \item{\code{method}}{A character string summarising the key arguments to xgbar, of the structure
67 | #' \code{xgbar(maxlag, diffs, seas_method)}.}
68 | #' \item{\code{origxreg}}{The original user-supplied value of \code{origxreg},
69 | #' stored for future use by \code{forecast.xgbar} (needed to create future values of lagged \code{xreg}
70 | #' for the forecast period) .}
71 | #' \item{code{ncolxreg}}{The number of columns in the original \code{xreg} matrix.}
72 | #' \item{\code{decomp}}{If \code{seas_method = "decompose"} was used, this will be a list of the output
73 | #' from \code{decompose}, which decomposes y (called \code{x} by \code{decompose}) into seasonal, trend
74 | #' and random components.}
75 | #' }
76 | #' @seealso \code{\link{summary.xgbar}}, \code{\link{plot.xgbar}}, \code{\link{forecast.xgbar}}, \code{\link{xgbar_importance}},
77 | #' \code{\link[xgboost]{xgboost}}.
78 | #' @author Peter Ellis
79 | #' @references J. A. John and N. R. Draper (1980), "An Alternative Family of Transformations", \emph{Journal of the Royal Statistical
80 | #' Society}.
81 | #' @examples
82 | #' # Univariate example - quarterly production of woolen yarn in Australia
83 | #' woolmod <- xgbar(woolyrnq)
84 | #' summary(woolmod)
85 | #' plot(woolmod)
86 | #' fc <- forecast(woolmod, h = 8)
87 | #' plot(fc)
88 | #'
89 | #' # Bivariate example - quarterly income and consumption in the US
90 | #' if(require(fpp)){
91 | #' consumption <- usconsumption[ ,1]
92 | #' income <- matrix(usconsumption[ ,2], dimnames = list(NULL, "Income"))
93 | #' consumption_model <- xgbar(y = consumption, xreg = income)
94 | #' summary(consumption_model)
95 | #' }
96 | xgbar <- function(y, xreg = NULL, maxlag = max(8, 2 * frequency(y)), nrounds = 100,
97 | nrounds_method = c("cv", "v", "manual"),
98 | nfold = ifelse(length(y) > 30, 10, 5),
99 | lambda = 1,
100 | verbose = FALSE,
101 | seas_method = c("dummies", "decompose", "fourier", "none"),
102 | K = max(1, min(round(f / 4 - 1), 10)),
103 | trend_method = c("none", "differencing"), ...){
104 | # y <- AirPassengers; nrounds_method = "cv"; nrounds = 100; seas_method = "fourier"; trend_method = "differencing"; verbose = TRUE; xreg = NULL; maxlag = 8; lambda = 1; K = 1
105 |
106 | nrounds_method = match.arg(nrounds_method)
107 | seas_method = match.arg(seas_method)
108 | trend_method = match.arg(trend_method)
109 |
110 | # check y is a univariate time series
111 | if(!"ts" %in% class(y)){
112 | stop("y must be a univariate time series")
113 | }
114 |
115 | # check xreg, if it exists, is a numeric matrix
116 | if(!is.null(xreg)){
117 | if(class(xreg) == "ts" | "data.frame" %in% class(xreg)){
118 | message("Converting xreg into a matrix")
119 | xreg <- as.matrix(xreg)
120 | }
121 |
122 | if(!is.numeric(xreg) | !is.matrix(xreg)){
123 | stop("xreg should be a numeric and able to be coerced to a matrix")
124 | }
125 | }
126 | f <- stats::frequency(y)
127 | untransformedy <- y
128 | origy <- JDMod(y, lambda = lambda)
129 |
130 | # seasonal adjustment if asked for
131 | if(seas_method == "decompose"){
132 | decomp <- decompose(origy, type = "multiplicative")
133 | origy <- seasadj(decomp)
134 | }
135 |
136 | # de-trend the y if option was asked for
137 | # `diffs` is the number of differencing operations done, and is defined even if
138 | # trend_method != "differencing"
139 | diffs <- 0
140 | if(trend_method == "differencing"){
141 | alpha = 0.05
142 | dodiff <- TRUE
143 | while(dodiff){
144 | suppressWarnings(dodiff <- tseries::kpss.test(origy)$p.value < alpha)
145 | if(dodiff){
146 | diffs <- diffs + 1
147 | origy <- ts(c(0, diff(origy)), start = start(origy), frequency = f)
148 | }
149 | }
150 | }
151 |
152 | if(maxlag < f & seas_method == "dummies"){
153 | stop("At least one full period of lags needed when seas_method = dummies.")
154 | }
155 |
156 | orign <- length(y)
157 |
158 | if(orign < 4){
159 | stop("Too short. I need at least four observations.")
160 | }
161 |
162 | if(maxlag > (orign - f - round(f / 4))){
163 | warning(paste("y is too short for", maxlag, "to be the value of maxlag. Reducing maxlags to",
164 | orign - f - round(f / 4),
165 | "instead."))
166 | maxlag <- orign - f - round(f / 4)
167 | }
168 |
169 | if (maxlag != round(maxlag)){
170 | maxlag <- ceiling(maxlag)
171 | if(verbose){message(paste("Rounding maxlag up to", maxlag))}
172 | }
173 |
174 |
175 | origxreg <- xreg
176 | n <- orign - maxlag
177 | y2 <- ts(origy[-(1:(maxlag))], start = time(origy)[maxlag + 1], frequency = f)
178 |
179 | if(nrounds_method == "cv" & n < 15){
180 | warning("y is too short for cross-validation. Will validate on the most recent 20 per cent instead.")
181 | nrounds_method <- "v"
182 | }
183 |
184 |
185 |
186 | #----------------------------creating x--------------------
187 | # set up the matrix "x" of lagged versions of y, time series trend, and seasonal treatment:
188 | if(seas_method == "dummies" & f > 1){ncolx <- maxlag + f - 1}
189 | if(seas_method == "decompose"){ncolx <- maxlag }
190 | if(seas_method == "fourier" & f > 1){ncolx <- maxlag + K * 2}
191 | if(seas_method == "none" | f == 1){ncolx <- maxlag}
192 | x <- matrix(0, nrow = n, ncol = ncolx)
193 |
194 | # All models get the lagged values of y as regressors:
195 | x[ , 1:maxlag] <- lagv(origy, maxlag, keeporig = FALSE)
196 |
197 | # Some models get one hot encoding of seasons
198 | if(f > 1 & seas_method == "dummies"){
199 | tmp <- data.frame(y = 1, x = as.character(rep_len(1:f, n)))
200 | seasons <- model.matrix(y ~ x, data = tmp)[ ,-1]
201 | x[ , maxlag + 1:(f - 1)] <- seasons
202 |
203 | colnames(x) <- c(paste0("lag", 1:maxlag), paste0("season", 2:f))
204 | }
205 |
206 | # Fourier models get fourier cycles:
207 | if(f > 1 & seas_method == "fourier"){
208 | fx <- fourier(y2, K = K)
209 | x[ , (maxlag + 1):ncolx] <- fx
210 | colnames(x) <- c(paste0("lag", 1:maxlag), colnames(fx))
211 | }
212 |
213 | # Some models get no seasonal treatment at all:
214 | if(f == 1 || seas_method == "decompose" || seas_method == "none"){
215 | colnames(x) <- c(paste0("lag", 1:maxlag))
216 | }
217 |
218 | # add xreg, if present
219 | if(!is.null(xreg)){
220 | xreg <- lagvm(xreg, maxlag = maxlag)
221 | x <- cbind(x, xreg[ , , drop = FALSE])
222 | }
223 |
224 |
225 | #---------------model fitting--------------------
226 | if(nrounds_method == "cv"){
227 | if(verbose){message("Starting cross-validation")}
228 | cv <- xgb.cv(data = x, label = y2, nrounds = nrounds, nfold = nfold,
229 | early_stopping_rounds = 5, maximize = FALSE, verbose = verbose, ...) # should finish with , ...
230 | # TODO - xgb.cv uses cat() to give messages, very poor practice. Sink them somewhere if verbose = FALSE?
231 |
232 | nrounds_use <- cv$best_iteration
233 | } else {if(nrounds_method == "v"){
234 | nrounds_use <- validate_xgbar(y, xreg = xreg, ...) $best_nrounds
235 | } else {
236 | nrounds_use <- nrounds
237 | }
238 | }
239 |
240 | if(verbose){message("Fitting xgboost model")}
241 | model <- xgboost(data = x, label = y2, nrounds = nrounds_use, verbose = verbose)
242 |
243 | fitted <- ts(c(rep(NA, maxlag),
244 | predict(model, newdata = x)),
245 | frequency = f, start = min(time(origy)))
246 |
247 | # back transform the differencing
248 | if(trend_method == "differencing"){
249 | for(i in 1:diffs){
250 | fitted[!is.na(fitted)] <- ts(cumsum(fitted[!is.na(fitted)]), start = start(origy), frequency = f)
251 | }
252 | fitted <- fitted + JDMod(untransformedy[maxlag + 1], lambda = lambda)
253 | }
254 |
255 | # back transform the seasonal adjustment:
256 | if(seas_method == "decompose"){
257 | fitted <- fitted * decomp$seasonal
258 | }
259 |
260 |
261 | # back transform the modulus power transform:
262 | fitted <- InvJDMod(fitted, lambda = lambda)
263 |
264 |
265 | method <- paste0("xgbar(", maxlag, ", ", diffs, ", ")
266 |
267 | if(f == 1 | seas_method == "none"){
268 | method <- paste0(method, "'non-seasonal')")
269 | } else {
270 | method <- paste0(method, "'", seas_method, "')")
271 | }
272 |
273 | output <- list(
274 | y = untransformedy, # original scale
275 | y2 = y2, # possibly all three of transformed, differenced and seasonally adjusted
276 | x = x,
277 | model = model,
278 | fitted = fitted, # original scale
279 | maxlag = maxlag,
280 | seas_method = seas_method,
281 | diffs = diffs,
282 | lambda = lambda,
283 | method = method
284 | )
285 | if(seas_method == "decompose"){
286 | output$decomp <- decomp
287 | }
288 |
289 | if(seas_method == "fourier" & f != 1){
290 | output$fx <- fx
291 | output$K <- K
292 | }
293 |
294 | if(!is.null(xreg)){
295 | output$ origxreg = origxreg
296 | output$ncolxreg <- ncol(origxreg)
297 | }
298 | class(output) <- "xgbar"
299 | return(output)
300 |
301 | }
302 |
303 | #`` @export
304 | xgbts <- function(...){
305 | warning("xgbts is deprecated terminology and will soon be removed.
306 | Please use xgbar instead.")
307 | xgbar(...)
308 | }
309 |
310 |
--------------------------------------------------------------------------------
/pkg/data/Mcomp_results.rda:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/pkg/data/Mcomp_results.rda
--------------------------------------------------------------------------------
/pkg/data/Tcomp_results.rda:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/pkg/data/Tcomp_results.rda
--------------------------------------------------------------------------------
/pkg/data/seaice_ts.rda:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ellisp/forecastxgb-r-package/fe2894aa43a1805b94c881a32f7a5291e53654d6/pkg/data/seaice_ts.rda
--------------------------------------------------------------------------------
/pkg/inst/doc/xgbar.R:
--------------------------------------------------------------------------------
1 | ## ----echo = FALSE, cache = FALSE-----------------------------------------
2 | set.seed(123)
3 | library(knitr)
4 | knit_hooks$set(mypar = function(before, options, envir) {
5 | if (before) par(bty = "l", family = "serif")
6 | })
7 | opts_chunk$set(comment=NA, fig.width=7, fig.height=5, cache = FALSE, mypar = TRUE)
8 |
9 | ## ----message = FALSE-----------------------------------------------------
10 | library(forecastxgb)
11 | model <- xgbar(gas)
12 |
13 | ## ------------------------------------------------------------------------
14 | summary(model)
15 |
16 | ## ------------------------------------------------------------------------
17 | fc <- forecast(model, h = 12)
18 | plot(fc)
19 |
20 | ## ----message = FALSE-----------------------------------------------------
21 | library(fpp)
22 | consumption <- usconsumption[ ,1]
23 | income <- matrix(usconsumption[ ,2], dimnames = list(NULL, "Income"))
24 | consumption_model <- xgbar(y = consumption, xreg = income)
25 | summary(consumption_model)
26 |
27 | ## ------------------------------------------------------------------------
28 | income_future <- matrix(forecast(xgbar(usconsumption[,2]), h = 10)$mean,
29 | dimnames = list(NULL, "Income"))
30 | plot(forecast(consumption_model, xreg = income_future))
31 |
32 | ## ----echo = FALSE--------------------------------------------------------
33 | model1 <- xgbar(co2, seas_method = "dummies")
34 | model2 <- xgbar(co2, seas_method = "decompose")
35 | model3 <- xgbar(co2, seas_method = "fourier")
36 | plot(forecast(model1), main = "Dummy variables for seasonality")
37 | # plot(forecast(model2), main = "Decomposition seasonal adjustment for seasonality")
38 | plot(forecast(model3), main = "Fourier transform pairs as x regressors")
39 |
40 | ## ----echo = FALSE--------------------------------------------------------
41 | model1 <- xgbar(co2, seas_method = "decompose", lambda = 1)
42 | model2 <- xgbar(co2, seas_method = "decompose", lambda = BoxCox.lambda(co2))
43 | plot(forecast(model1), main = "No transformation")
44 | plot(forecast(model2), main = "With transformation")
45 |
46 | ## ------------------------------------------------------------------------
47 | model <- xgbar(AirPassengers, trend_method = "differencing", seas_method = "fourier")
48 | plot(forecast(model, 24))
49 |
50 | ## ----message = FALSE-----------------------------------------------------
51 | #=============prep======================
52 | library(Tcomp)
53 | library(foreach)
54 | library(doParallel)
55 | library(forecastxgb)
56 | library(dplyr)
57 | library(ggplot2)
58 | library(scales)
59 |
60 | ## ----eval = FALSE--------------------------------------------------------
61 | # #============set up cluster for parallel computing===========
62 | # cluster <- makeCluster(7) # only any good if you have at least 7 processors :)
63 | # registerDoParallel(cluster)
64 | #
65 | # clusterEvalQ(cluster, {
66 | # library(Tcomp)
67 | # library(forecastxgb)
68 | # })
69 | #
70 | #
71 | # #===============the actual analytical function==============
72 | # competition <- function(collection, maxfors = length(collection)){
73 | # if(class(collection) != "Mcomp"){
74 | # stop("This function only works on objects of class Mcomp, eg from the Mcomp or Tcomp packages.")
75 | # }
76 | # nseries <- length(collection)
77 | # mases <- foreach(i = 1:maxfors, .combine = "rbind") %dopar% {
78 | # thedata <- collection[[i]]
79 | # seas_method <- ifelse(frequency(thedata$x) < 6, "dummies", "fourier")
80 | # mod1 <- xgbar(thedata$x, trend_method = "differencing", seas_method = seas_method, lambda = 1, K = 2)
81 | # fc1 <- forecast(mod1, h = thedata$h)
82 | # fc2 <- thetaf(thedata$x, h = thedata$h)
83 | # fc3 <- forecast(auto.arima(thedata$x), h = thedata$h)
84 | # fc4 <- forecast(nnetar(thedata$x), h = thedata$h)
85 | # # copy the skeleton of fc1 over for ensembles:
86 | # fc12 <- fc13 <- fc14 <- fc23 <- fc24 <- fc34 <- fc123 <- fc124 <- fc134 <- fc234 <- fc1234 <- fc1
87 | # # replace the point forecasts with averages of member forecasts:
88 | # fc12$mean <- (fc1$mean + fc2$mean) / 2
89 | # fc13$mean <- (fc1$mean + fc3$mean) / 2
90 | # fc14$mean <- (fc1$mean + fc4$mean) / 2
91 | # fc23$mean <- (fc2$mean + fc3$mean) / 2
92 | # fc24$mean <- (fc2$mean + fc4$mean) / 2
93 | # fc34$mean <- (fc3$mean + fc4$mean) / 2
94 | # fc123$mean <- (fc1$mean + fc2$mean + fc3$mean) / 3
95 | # fc124$mean <- (fc1$mean + fc2$mean + fc4$mean) / 3
96 | # fc134$mean <- (fc1$mean + fc3$mean + fc4$mean) / 3
97 | # fc234$mean <- (fc2$mean + fc3$mean + fc4$mean) / 3
98 | # fc1234$mean <- (fc1$mean + fc2$mean + fc3$mean + fc4$mean) / 4
99 | # mase <- c(accuracy(fc1, thedata$xx)[2, 6],
100 | # accuracy(fc2, thedata$xx)[2, 6],
101 | # accuracy(fc3, thedata$xx)[2, 6],
102 | # accuracy(fc4, thedata$xx)[2, 6],
103 | # accuracy(fc12, thedata$xx)[2, 6],
104 | # accuracy(fc13, thedata$xx)[2, 6],
105 | # accuracy(fc14, thedata$xx)[2, 6],
106 | # accuracy(fc23, thedata$xx)[2, 6],
107 | # accuracy(fc24, thedata$xx)[2, 6],
108 | # accuracy(fc34, thedata$xx)[2, 6],
109 | # accuracy(fc123, thedata$xx)[2, 6],
110 | # accuracy(fc124, thedata$xx)[2, 6],
111 | # accuracy(fc134, thedata$xx)[2, 6],
112 | # accuracy(fc234, thedata$xx)[2, 6],
113 | # accuracy(fc1234, thedata$xx)[2, 6])
114 | # mase
115 | # }
116 | # message("Finished fitting models")
117 | # colnames(mases) <- c("x", "f", "a", "n", "xf", "xa", "xn", "fa", "fn", "an",
118 | # "xfa", "xfn", "xan", "fan", "xfan")
119 | # return(mases)
120 | # }
121 |
122 | ## ----eval = FALSE--------------------------------------------------------
123 | # #========Fit models==============
124 | # system.time(t1 <- competition(subset(tourism, "yearly")))
125 | # system.time(t4 <- competition(subset(tourism, "quarterly")))
126 | # system.time(t12 <- competition(subset(tourism, "monthly")))
127 | #
128 | # # shut down cluster to avoid any mess:
129 | # stopCluster(cluster)
130 |
131 | ## ----eval = FALSE--------------------------------------------------------
132 | # #==============present results================
133 | # results <- c(apply(t1, 2, mean),
134 | # apply(t4, 2, mean),
135 | # apply(t12, 2, mean))
136 | #
137 | # results_df <- data.frame(MASE = results)
138 | # results_df$model <- as.character(names(results))
139 | # periods <- c("Annual", "Quarterly", "Monthly")
140 | # results_df$Frequency <- rep.int(periods, times = c(15, 15, 15))
141 | #
142 | # best <- results_df %>%
143 | # group_by(model) %>%
144 | # summarise(MASE = mean(MASE)) %>%
145 | # arrange(MASE) %>%
146 | # mutate(Frequency = "Average")
147 | #
148 | # Tcomp_results <- results_df %>%
149 | # rbind(best) %>%
150 | # mutate(model = factor(model, levels = best$model)) %>%
151 | # mutate(Frequency = factor(Frequency, levels = c("Annual", "Average", "Quarterly", "Monthly")))
152 |
153 | ## ---- fig.width = 8, fig.height = 6--------------------------------------
154 | leg <- "f: Theta; forecast::thetaf\na: ARIMA; forecast::auto.arima
155 | n: Neural network; forecast::nnetar\nx: Extreme gradient boosting; forecastxgb::xgbar"
156 |
157 | Tcomp_results %>%
158 | ggplot(aes(x = model, y = MASE, colour = Frequency, label = model)) +
159 | geom_text(size = 4) +
160 | geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
161 | scale_y_continuous("Mean scaled absolute error\n(smaller numbers are better)") +
162 | annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
163 | ggtitle("Average error of four different timeseries forecasting methods\n2010 Tourism Forecasting Competition data") +
164 | labs(x = "Model, or ensemble of models\n(further to the left means better overall performance)") +
165 | theme_grey(9)
166 |
167 |
--------------------------------------------------------------------------------
/pkg/inst/doc/xgbar.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Extreme gradient boosting time series forecasting"
3 | author: "Peter Ellis"
4 | date: "26 November 2016"
5 | output: rmarkdown::html_vignette
6 | vignette: >
7 | %\VignetteIndexEntry{Extreme gradient boosting time series forecasting}
8 | %\VignetteEngine{knitr::rmarkdown}
9 | %\VignetteEncoding{UTF-8}
10 | ---
11 |
12 | The `forecastxgb` package provides time series modelling and forecasting functions that combine the machine learning approach of Chen, He and Benesty's [`xgboost`](https://CRAN.R-project.org/package=xgboost) with the convenient handling of time series and familiar API of Rob Hyndman's [`forecast`](http://github.com/robjhyndman/forecast). It applies to time series the Extreme Gradient Boosting proposed in [*Greedy Function Approximation: A Gradient Boosting Machine*, by Jerome Friedman in 2001](http://www.jstor.org/stable/2699986). xgboost has become an important machine learning algorithm; nicely explained in [this accessible documentation](http://xgboost.readthedocs.io/en/latest/model.html).
13 |
14 | **Warning: this package is under active development. The API and default settings should be expected to continue to change.**
15 |
16 | ## Basic usage
17 |
18 | The workhorse function is `xgbar`. This fits a model to a time series. Under the hood, it creates a matrix of explanatory variables based on lagged versions of the response time series, and (optionally) dummy variables of some sort for seasons. That matrix is then fed as the feature set for `xgboost` to do its stuff.
19 |
20 | ```{r echo = FALSE, cache = FALSE}
21 | set.seed(123)
22 | library(knitr)
23 | knit_hooks$set(mypar = function(before, options, envir) {
24 | if (before) par(bty = "l", family = "serif")
25 | })
26 | opts_chunk$set(comment=NA, fig.width=7, fig.height=5, cache = FALSE, mypar = TRUE)
27 | ```
28 |
29 | ### Univariate
30 |
31 | Usage with default values is straightforward. Here it is fit to Australian monthly gas production 1956-1995, an example dataset provided in `forecast`:
32 | ```{r message = FALSE}
33 | library(forecastxgb)
34 | model <- xgbar(gas)
35 | ```
36 | (Note: the "Stopping. Best iteration..." to the screen is produced by `xgboost::xgb.cv`, which uses `cat()` rather than `message()` to print information on its processing.)
37 |
38 | By default, `xgbar` uses row-wise cross-validation to determine the best number of rounds of iterations for the boosting algorithm without overfitting. A final model is then fit on the full available dataset. The relative importance of the various features in the model can be inspected by `importance_xgb()` or, more conveniently, the `summary` method for objects of class `xgbar`.
39 |
40 |
41 | ```{r}
42 | summary(model)
43 | ```
44 | We see in the case of the gas data that the most important feature in explaining gas production is the production 12 months previously; and then other features decrease in importance from there but still have an impact.
45 |
46 | Forecasting is the main purpose of this package, and a `forecast` method is supplied. The resulting objects are of class `forecast` and familiar generic functions work with them.
47 |
48 | ```{r}
49 | fc <- forecast(model, h = 12)
50 | plot(fc)
51 | ```
52 | Note that prediction intervals are not currently available.
53 |
54 | ### With external regressors
55 | External regressors can be added by using the `xreg` argument familiar from other forecast functions like `auto.arima` and `nnetar`. `xreg` can be a vector or `ts` object but is easiest to integrate into the analysis if it is a matrix (even a matrix with one column) with well-chosen column names; that way feature names persist meaningfully.
56 |
57 | The example below, with data taken from the `fpp` package supporting Athanasopoulos and Hyndman's [Forecasting Principles and Practice](https://www.otexts.org/fpp) book, shows income being used to explain consumption. In the same way that the response variable `y` is expanded into lagged versions of itself, each column in `xreg` is expanded into lagged versions, which are then treated as individual features for `xgboost`.
58 |
59 | ```{r message = FALSE}
60 | library(fpp)
61 | consumption <- usconsumption[ ,1]
62 | income <- matrix(usconsumption[ ,2], dimnames = list(NULL, "Income"))
63 | consumption_model <- xgbar(y = consumption, xreg = income)
64 | summary(consumption_model)
65 | ```
66 | We see that the two most important features explaining consumption are the two previous quarters' values of consumption; followed by the income in this quarter; and so on.
67 |
68 |
69 | The challenge of using external regressors in a forecasting environment is that to forecast, you need values of the future external regressors. One way this is sometimes done is by first forecasting the individual regressors. In the example below we do this, making sure the data structure is the same as the original `xreg`. When the new value of `xreg` is given to `forecast`, it forecasts forward the number of rows of the new `xreg`.
70 | ```{r}
71 | income_future <- matrix(forecast(xgbar(usconsumption[,2]), h = 10)$mean,
72 | dimnames = list(NULL, "Income"))
73 | plot(forecast(consumption_model, xreg = income_future))
74 | ```
75 |
76 |
77 | ## Advanced usage
78 | The default settings for `xgbar` give reasonable results. The key things that can be changed by the user include:
79 |
80 | - the maximum number of lags to include as explanatory variables. There is a trade-off here, as each number higher this gets, the less rows of data you have. Generally at least two full seasonal cycles are desired, and the default is `max(8, 2 * frequency(y))`. When the data gets very short this value is sometimes forced lower, with a warning.
81 | - the method for choosing the maximum number of boosting iterations. The default is row-wise cross validation, after the matrix of lagged explanatory variables has been created. This is not a traditional approach for cross validation of time series, because the resampling does not preserve the original ordering. However, the presence of the lagged values means this is less of an issue. The main alternative (`nrounds_method = "v"`) is to set aside the final 20% of data and use that for validation of the various numbers of rounds of iterations of the first 80% of training data. Experiments so far suggest that both methods give similar results; if anything the cross-validation method generally recommends a slightly lower number of iterations than does the alternative.
82 |
83 | ## Options
84 |
85 | ### Seasonality
86 |
87 | Currently there are three methods of treating seasonality.
88 |
89 | - The current default method is to throw dummy variables for each season into the mix of features for `xgboost` to work with.
90 | - An alternative is to perform classic multiplicative seasonal adjustment on the series before feeding it to `xgboost`. This seems to work better.
91 | - A third option is to create a set of pairs of Fourier transform variables and use them as x regressors
92 |
93 | ```{r echo = FALSE}
94 | model1 <- xgbar(co2, seas_method = "dummies")
95 | model2 <- xgbar(co2, seas_method = "decompose")
96 | model3 <- xgbar(co2, seas_method = "fourier")
97 | plot(forecast(model1), main = "Dummy variables for seasonality")
98 | # plot(forecast(model2), main = "Decomposition seasonal adjustment for seasonality")
99 | plot(forecast(model3), main = "Fourier transform pairs as x regressors")
100 | ```
101 |
102 | All methods perform quite poorly at the moment, suffering from the difficulty the default settings have in dealing with non-stationary data (see below).
103 |
104 | ### Transformations
105 |
106 | The data can be transformed by a modulus power transformation (as per John and Draper, 1980) before feeding to `xgboost`. This transformation is similar to a Box-Cox transformation, but works with negative data. Leaving the `lambda` parameter as 1 will effectively switch off this transformation.
107 | ```{r echo = FALSE}
108 | model1 <- xgbar(co2, seas_method = "decompose", lambda = 1)
109 | model2 <- xgbar(co2, seas_method = "decompose", lambda = BoxCox.lambda(co2))
110 | plot(forecast(model1), main = "No transformation")
111 | plot(forecast(model2), main = "With transformation")
112 | ```
113 |
114 | Version 0.0.9 of `forecastxgb` gave `lambda` the default value of `BoxCox.lambda(abs(y))`. This returned spectacularly bad forecasting results. Forcing this to be between 0 and 1 helped a little, but still gave very bad results. So far there isn't evidence (but neither is there enough investigation) that a Box Cox transformation helps xgbar do its model fitting at all.
115 |
116 | ### Non-stationarity
117 | From experiments so far, it seems the basic idea of `xgboost` struggles in this context with extrapolation into a new range of variables not in the training set. This suggests better results might be obtained by transforming the series into a stationary one before modelling - a similar approach to that taken by `forecast::auto.arima`. This option is available by `trend_method = "differencing"` and seems to perform well - certainly better than without - and it will probably be made a default setting once more experience is available.
118 |
119 | ```{r}
120 | model <- xgbar(AirPassengers, trend_method = "differencing", seas_method = "fourier")
121 | plot(forecast(model, 24))
122 | ```
123 |
124 |
125 | ## Future developments
126 | Future work might include:
127 |
128 | * additional automated time-dependent features (eg dummy variables for trading days, Easter, etc)
129 | * ability to include xreg values that don't get lagged
130 | * some kind of automated multiple variable forecasting, similar to a vector-autoregression.
131 | * better choices of defaults for values such as `lambda` (for power transformations), `K` (for Fourier transforms) and, most likely to be effective, `maxlag`.
132 |
133 | ## Tourism forecasting competition
134 | Here is a more substantive example. I use the 1,311 datasets from the 2010 Tourism Forecasting Competition described in
135 | in [Athanasopoulos et al (2011)](http://robjhyndman.com/papers/forecompijf.pdf), originally in the International Journal of Forecasting (2011) 27(3), 822-844. The data are available in the CRAN package [Tcomp](https://cran.r-project.org/package=Tcomp). Each data object is a list, with elements inlcuding `x` (the original training data), `h` (the forecasting period) and `xx` (the test data of length `h`). Only univariate time series are included.
136 |
137 | To give the `xgbar` model a good test, I am going to compare its performance in forecasting the 1,311 `xx` time series from the matching `x` series with three other modelling approaches:
138 |
139 | - Auto-regressive integrated moving average (ARIMA)
140 | - Theta
141 | - Neural networks
142 |
143 | Those three are all from Rob Hyndman's `forecast` package. I am also going to look at the performance of ensembles of the four model types. With all combinations this means 15 models in total.
144 |
145 | Because all four models use the `forecast` paradigm it is relatively straightforward to structure the analysis. The code below is a little repetitive but should be fairly transparent. Because of the scale and the embarrassingly parallel nature of the work (ie no particular reason to do it in any particular order, so easy to split into tasks for different processes to do in parallel), I use `foreach` and `doParallel` to make the best use of my 8 logical processors. The code below sets up a cluster for the parallel computing and a function `competition` which will work on any object of class `Mcomp`, which `Tcomp` inherits from the `Mcomp` package providing the first three "M" forecasting competition data collections.
146 |
147 | ```{r message = FALSE}
148 | #=============prep======================
149 | library(Tcomp)
150 | library(foreach)
151 | library(doParallel)
152 | library(forecastxgb)
153 | library(dplyr)
154 | library(ggplot2)
155 | library(scales)
156 | ```
157 | ```{r eval = FALSE}
158 | #============set up cluster for parallel computing===========
159 | cluster <- makeCluster(7) # only any good if you have at least 7 processors :)
160 | registerDoParallel(cluster)
161 |
162 | clusterEvalQ(cluster, {
163 | library(Tcomp)
164 | library(forecastxgb)
165 | })
166 |
167 |
168 | #===============the actual analytical function==============
169 | competition <- function(collection, maxfors = length(collection)){
170 | if(class(collection) != "Mcomp"){
171 | stop("This function only works on objects of class Mcomp, eg from the Mcomp or Tcomp packages.")
172 | }
173 | nseries <- length(collection)
174 | mases <- foreach(i = 1:maxfors, .combine = "rbind") %dopar% {
175 | thedata <- collection[[i]]
176 | seas_method <- ifelse(frequency(thedata$x) < 6, "dummies", "fourier")
177 | mod1 <- xgbar(thedata$x, trend_method = "differencing", seas_method = seas_method, lambda = 1, K = 2)
178 | fc1 <- forecast(mod1, h = thedata$h)
179 | fc2 <- thetaf(thedata$x, h = thedata$h)
180 | fc3 <- forecast(auto.arima(thedata$x), h = thedata$h)
181 | fc4 <- forecast(nnetar(thedata$x), h = thedata$h)
182 | # copy the skeleton of fc1 over for ensembles:
183 | fc12 <- fc13 <- fc14 <- fc23 <- fc24 <- fc34 <- fc123 <- fc124 <- fc134 <- fc234 <- fc1234 <- fc1
184 | # replace the point forecasts with averages of member forecasts:
185 | fc12$mean <- (fc1$mean + fc2$mean) / 2
186 | fc13$mean <- (fc1$mean + fc3$mean) / 2
187 | fc14$mean <- (fc1$mean + fc4$mean) / 2
188 | fc23$mean <- (fc2$mean + fc3$mean) / 2
189 | fc24$mean <- (fc2$mean + fc4$mean) / 2
190 | fc34$mean <- (fc3$mean + fc4$mean) / 2
191 | fc123$mean <- (fc1$mean + fc2$mean + fc3$mean) / 3
192 | fc124$mean <- (fc1$mean + fc2$mean + fc4$mean) / 3
193 | fc134$mean <- (fc1$mean + fc3$mean + fc4$mean) / 3
194 | fc234$mean <- (fc2$mean + fc3$mean + fc4$mean) / 3
195 | fc1234$mean <- (fc1$mean + fc2$mean + fc3$mean + fc4$mean) / 4
196 | mase <- c(accuracy(fc1, thedata$xx)[2, 6],
197 | accuracy(fc2, thedata$xx)[2, 6],
198 | accuracy(fc3, thedata$xx)[2, 6],
199 | accuracy(fc4, thedata$xx)[2, 6],
200 | accuracy(fc12, thedata$xx)[2, 6],
201 | accuracy(fc13, thedata$xx)[2, 6],
202 | accuracy(fc14, thedata$xx)[2, 6],
203 | accuracy(fc23, thedata$xx)[2, 6],
204 | accuracy(fc24, thedata$xx)[2, 6],
205 | accuracy(fc34, thedata$xx)[2, 6],
206 | accuracy(fc123, thedata$xx)[2, 6],
207 | accuracy(fc124, thedata$xx)[2, 6],
208 | accuracy(fc134, thedata$xx)[2, 6],
209 | accuracy(fc234, thedata$xx)[2, 6],
210 | accuracy(fc1234, thedata$xx)[2, 6])
211 | mase
212 | }
213 | message("Finished fitting models")
214 | colnames(mases) <- c("x", "f", "a", "n", "xf", "xa", "xn", "fa", "fn", "an",
215 | "xfa", "xfn", "xan", "fan", "xfan")
216 | return(mases)
217 | }
218 | ```
219 |
220 | Applying this function to the three different subsets of tourism data (by different frequency) is straightforward but takes a few minutes to run:
221 |
222 | ```{r eval = FALSE}
223 | #========Fit models==============
224 | system.time(t1 <- competition(subset(tourism, "yearly")))
225 | system.time(t4 <- competition(subset(tourism, "quarterly")))
226 | system.time(t12 <- competition(subset(tourism, "monthly")))
227 |
228 | # shut down cluster to avoid any mess:
229 | stopCluster(cluster)
230 | ```
231 |
232 | The `competition` function returns the mean absolute scaled error (MASE) of every model combination for every dataset. The following code creates a summary object from the objects `t1`, `t4` and `t12` that hold those individual results:
233 |
234 | ```{r eval = FALSE}
235 | #==============present results================
236 | results <- c(apply(t1, 2, mean),
237 | apply(t4, 2, mean),
238 | apply(t12, 2, mean))
239 |
240 | results_df <- data.frame(MASE = results)
241 | results_df$model <- as.character(names(results))
242 | periods <- c("Annual", "Quarterly", "Monthly")
243 | results_df$Frequency <- rep.int(periods, times = c(15, 15, 15))
244 |
245 | best <- results_df %>%
246 | group_by(model) %>%
247 | summarise(MASE = mean(MASE)) %>%
248 | arrange(MASE) %>%
249 | mutate(Frequency = "Average")
250 |
251 | Tcomp_results <- results_df %>%
252 | rbind(best) %>%
253 | mutate(model = factor(model, levels = best$model)) %>%
254 | mutate(Frequency = factor(Frequency, levels = c("Annual", "Average", "Quarterly", "Monthly")))
255 | ```
256 |
257 | The resulting object, `Tcomp_results`, is provided with the `forecastxgb` package. Visual inspection shows that the average values of MASE provided for the Theta and ARIMA models match those in the [`Tcomp` vignette](https://cran.r-project.org/web/packages/Tcomp/vignettes/tourism-comp.html). The results are easiest to understand graphically.
258 |
259 | ```{r, fig.width = 8, fig.height = 6}
260 | leg <- "f: Theta; forecast::thetaf\na: ARIMA; forecast::auto.arima
261 | n: Neural network; forecast::nnetar\nx: Extreme gradient boosting; forecastxgb::xgbar"
262 |
263 | Tcomp_results %>%
264 | ggplot(aes(x = model, y = MASE, colour = Frequency, label = model)) +
265 | geom_text(size = 4) +
266 | geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
267 | scale_y_continuous("Mean scaled absolute error\n(smaller numbers are better)") +
268 | annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
269 | ggtitle("Average error of four different timeseries forecasting methods\n2010 Tourism Forecasting Competition data") +
270 | labs(x = "Model, or ensemble of models\n(further to the left means better overall performance)") +
271 | theme_grey(9)
272 | ```
273 |
274 |
275 | We see the overall best performing ensemble is the average of the Theta and ARIMA models - the two from the more traditional timeseries forecasting approach. The two machine learning methods (neural network and extreme gradient boosting) are not as effective, at least in these implementations. As individual methods, they are the two weakest, although the extreme gradient boosting method provided in `forecastxgb` performs noticeably better than `forecast::nnetar` for the annual and quarterly data.
276 |
277 | Theta by itself is the best performing with the annual data - simple methods work well when the dataset is small and highly aggregate. The best that can be said of the `xgbar` approach in this context is that it doesn't damage the Theta method much when included in a combination - several of the better performing ensembles have `xgbar` as one of their members. In contrast, the neural network models do badly with this collection of annual data.
278 |
279 | Adding `auto.arima` and `xgbar` to an ensemble of quarterly or monthly data definitely improves on Theta by itself. The best performing single model for quarterly or monthly data is `auto.arima` followed by `thetaf`. Again, neural networks are the poorest of the four individual models.
280 |
281 | Overall, I conclude that with univariate data, `xgbar` has little to add to an ensemble that already contains `auto.arima` and `thetaf` (or - not shown - the closely related `ets`). I believe however that inclusion of `xreg` external regressors would shift the balance in favour of `xgbar` and maybe even `nnetar` - the more complex and larger the dataset, the better the chance that these methods will have something to offer. If and when I find a large collection of timeseries competition data with external regressors I will probably add a second vignette, or at least a blog post at [http://ellisp.github.io](http://ellisp.github.io).
--------------------------------------------------------------------------------
/pkg/man/Mcomp_results.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/extras.R
3 | \docType{data}
4 | \name{Mcomp_results}
5 | \alias{Mcomp_results}
6 | \title{M3 forecasting results}
7 | \format{A data frame with 75 rows and three columns.}
8 | \usage{
9 | Mcomp_results
10 | }
11 | \description{
12 | Summary data from four models, and 11 combinations of models, against the data from the M3 forecasting competition.
13 | }
14 | \details{
15 | Full details are in the vignette of how a similar series with tourism competition data was generated.
16 | The data shows the average mean absolute scaled error
17 | (MASE) from using \code{xgbar} (x), \code{auto.arima} (a), \code{nnetar} (n) and \code{thetaf} (f) to
18 | generate forecasts of 3,003 data series from a range of sectors, in the M3 forecasting competition.
19 |
20 | \itemize{
21 | \item MASE A mean mean absolute squared error
22 | \item model model, or ensemble of models, to which the MASE applies
23 | \item Frequency The frequency of the subset of data from which the mean MASE was calculated.
24 | }
25 | }
26 | \examples{
27 | if(require(ggplot2)){
28 | leg <- "f: Theta; forecast::thetaf\\na: ARIMA; forecast::auto.arima
29 | n: Neural network; forecast::nnetar\\nx: Extreme gradient boosting; forecastxgb::xgbar"
30 |
31 | ggplot(Mcomp_results, aes(x = model, y = MASE, colour = Frequency, label = model)) +
32 | geom_text(size = 4) +
33 | geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
34 | annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
35 | ggtitle("Average error of four different timeseries forecasting methods
36 | M3 Forecasting Competition data") +
37 | labs(x = "Model, or ensemble of models
38 | (further to the left means better overall performance)",
39 | y = "Mean scaled absolute error\\n(smaller numbers are better)") +
40 | theme_grey(9)
41 | }
42 | }
43 | \author{
44 | Peter Ellis
45 | }
46 | \keyword{datasets}
47 |
--------------------------------------------------------------------------------
/pkg/man/Tcomp_results.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/extras.R
3 | \docType{data}
4 | \name{Tcomp_results}
5 | \alias{Tcomp_results}
6 | \title{Tourism forecasting results}
7 | \format{A data frame with 60 rows and three columns.}
8 | \usage{
9 | Tcomp_results
10 | }
11 | \description{
12 | Summary data from four models, and 11 combinations of models, against the data from the 2010 tourism forecasting competition.
13 | }
14 | \details{
15 | Full details of how this was generated are in the Vignette. This shows the average mean absolute scaled error
16 | (MASE) from using \code{xgbar} (x), \code{auto.arima} (a), \code{nnetar} (n) and \code{thetaf} (f) to generate forecasts of 1,311 tourism data series.
17 |
18 | \itemize{
19 | \item MASE A mean mean absolute squared error
20 | \item model model, or ensemble of models, to which the MASE applies
21 | \item Frequency The frequency of the subset of data from which the mean MASE was calculated.
22 | }
23 | }
24 | \examples{
25 | if(require(ggplot2)){
26 | leg <- "f: Theta; forecast::thetaf\\na: ARIMA; forecast::auto.arima
27 | n: Neural network; forecast::nnetar\\nx: Extreme gradient boosting; forecastxgb::xgbar"
28 |
29 | ggplot(Tcomp_results, aes(x = model, y = MASE, colour = Frequency, label = model)) +
30 | geom_text(size = 4) +
31 | geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
32 | annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
33 | ggtitle("Average error of four different timeseries forecasting methods
34 | 2010 Tourism Forecasting Competition data") +
35 | labs(x = "Model, or ensemble of models
36 | (further to the left means better overall performance)",
37 | y = "Mean scaled absolute error\\n(smaller numbers are better)") +
38 | theme_grey(9)
39 | }
40 | }
41 | \author{
42 | Peter Ellis
43 | }
44 | \keyword{datasets}
45 |
--------------------------------------------------------------------------------
/pkg/man/forecast.xgbar.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/forecast.xgbar.R
3 | \name{forecast.xgbar}
4 | \alias{forecast.xgbar}
5 | \title{Forecasting using xgboost models}
6 | \usage{
7 | \method{forecast}{xgbar}(object, h = NULL, xreg = NULL, ...)
8 | }
9 | \arguments{
10 | \item{object}{An object of class "\code{xgbar}". Usually the result of a call to \code{\link{xgbar}}.}
11 |
12 | \item{h}{Number of periods for forecasting. If \code{xreg} is provided, the number of rows of \code{xreg} will be
13 | used and \code{h} is ignored with a warning. If both \code{h} and \code{xreg} are \code{NULL} then
14 | \code{h = ifelse(frequency(object$y) > 1, 2 * frequency(object$y), 10)}}
15 |
16 | \item{xreg}{Future values of regression variables.}
17 |
18 | \item{...}{Ignored.}
19 | }
20 | \value{
21 | An object of class \code{forecast}
22 | }
23 | \description{
24 | Returns forecasts and other information for xgboost timeseries modesl fit with \code{xbgts}
25 | }
26 | \examples{
27 | # Australian monthly gas production
28 | gas_model <- xgbar(gas)
29 | summary(gas_model)
30 | gas_fc <- forecast(gas_model, h = 12)
31 | plot(gas_fc)
32 | }
33 | \seealso{
34 | \code{\link{xgbar}}, \code{\link[forecast]{forecast}}
35 | }
36 | \author{
37 | Peter Ellis
38 | }
39 |
--------------------------------------------------------------------------------
/pkg/man/forecastxgb-package.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/forecastxgb.R
3 | \docType{package}
4 | \name{forecastxgb-package}
5 | \alias{forecastxgb}
6 | \alias{forecastxgb-package}
7 | \title{Extreme gradient boosting time series forecasting}
8 | \description{
9 | The \code{forecastxgb} package provides time series modelling and forecasting functions that combine
10 | the machine learning approach of Chen, He and Benesty's \code{xgboost}
11 | with the convenient handling of time series and familiar API of Rob Hyndman's \code{forecast}.
12 | }
13 | \details{
14 | It applies to time series the Extreme Gradient Boosting proposed in \emph{Greedy Function Approximation: A
15 | Gradient Boosting Machine, by Jermoe Friedman in 2001} (http://www.jstor.org/stable/2699986).
16 | }
17 | \author{
18 | \strong{Maintainer}: Peter Ellis \email{peter.ellis2013nz@gmail.com}
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/pkg/man/plot.xgbar.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/extras.R
3 | \name{plot.xgbar}
4 | \alias{plot.xgbar}
5 | \title{Plot xgbar object}
6 | \usage{
7 | \method{plot}{xgbar}(x, ...)
8 | }
9 | \arguments{
10 | \item{x}{An object created by \code{xgbar}}
11 |
12 | \item{...}{Additional arguments passed through to \code{plot()}}
13 | }
14 | \description{
15 | plot method for an object created by xgbar
16 | }
17 | \examples{
18 | model <- xgbar(AirPassengers)
19 | plot(model)
20 | }
21 | \seealso{
22 | \code{\link{xgbar}}
23 | }
24 | \author{
25 | Peter Ellis
26 | }
27 |
--------------------------------------------------------------------------------
/pkg/man/seaice_ts.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/misc-doc.R
3 | \docType{data}
4 | \name{seaice_ts}
5 | \alias{seaice_ts}
6 | \title{Arctic sea ice}
7 | \format{An object of class \code{ts} of length 10647.}
8 | \source{
9 | National Snow and Ice Data Center, \url{https://nsidc.org/data/docs/noaa/g02135_seaice_index/#daily_data_files"}
10 | }
11 | \usage{
12 | seaice_ts
13 | }
14 | \description{
15 | Extent in millions of square kilometres of sea ice in the Arctic from 21 August 1987 to 24 November 2016.
16 | }
17 | \examples{
18 | plot(seaice_ts)
19 | }
20 | \keyword{datasets}
21 |
--------------------------------------------------------------------------------
/pkg/man/summary.xgbar.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/extras.R
3 | \name{summary.xgbar}
4 | \alias{summary.xgbar}
5 | \alias{print.summary.xgbar}
6 | \title{Summary of an xgbar object}
7 | \usage{
8 | \method{summary}{xgbar}(object, ...)
9 | }
10 | \arguments{
11 | \item{object}{An object created by \code{\link{xgbar}}}
12 |
13 | \item{...}{Ignored.}
14 | }
15 | \description{
16 | summary method for an object created by xgbar
17 | }
18 | \examples{
19 | \dontrun{
20 | # Half-hourly electricity demand in England and Wales, takes a few minutes
21 | electricity_model <- xgbar(taylor)
22 | summary(electricity_model)
23 | electricity_fc <- forecast(electricity_model, h = 500)
24 | plot(electricity_fc)
25 | }
26 | }
27 | \seealso{
28 | \code{\link{xgbar}}
29 | }
30 | \author{
31 | Peter Ellis
32 | }
33 |
--------------------------------------------------------------------------------
/pkg/man/xgbar.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/xgbar.R
3 | \name{xgbar}
4 | \alias{xgbar}
5 | \alias{xgbts}
6 | \title{xgboost time series modelling}
7 | \usage{
8 | xgbar(y, xreg = NULL, maxlag = max(8, 2 * frequency(y)), nrounds = 100,
9 | nrounds_method = c("cv", "v", "manual"), nfold = ifelse(length(y) > 30,
10 | 10, 5), lambda = 1, verbose = FALSE, seas_method = c("dummies",
11 | "decompose", "fourier", "none"), K = max(1, min(round(f/4 - 1), 10)),
12 | trend_method = c("none", "differencing"), ...)
13 | }
14 | \arguments{
15 | \item{y}{A univariate time series.}
16 |
17 | \item{xreg}{Optionally, a vector or matrix of external regressors, which must have the same number of rows as y.}
18 |
19 | \item{maxlag}{The maximum number of lags of \code{y} and \code{xreg} (if included) to be considered as features.}
20 |
21 | \item{nrounds}{Maximum number of iterations \code{xgboost} will perform. If \code{nrounds_method = 'cv'},
22 | the value of \code{nrounds} passed to \code{xgboost} is chosen by cross-validation; if it is \code{'v'}
23 | then the value of \code{nrounds} passed to \code{xgboost} is chosen by splitting the data into a training
24 | set (first 80 per cent) and test set (20 per cent) and choosing the number of iterations with the best value.
25 | If \code{nrounds_method = 'manual'} then \code{nrounds} iterations will be performed - unless you have chosen
26 | it carefully this is likely to lead to overfitting and poor forecasts.}
27 |
28 | \item{nrounds_method}{Method used to determine the value of nrounds actually given for \code{xgboost} for
29 | the final model. Options are \code{"cv"} for row-wise cross-validation, \code{"v"} for validation on a testing
30 | set of the most recent 20 per cent of data, \code{"manual"} in which case \code{nrounds} is passed through directly.}
31 |
32 | \item{nfold}{Number of equal size subsamples during cross validation, used if \code{nrounds_method = 'cv'}.}
33 |
34 | \item{lambda}{Value of lambda to be used for modulus power transformation of \code{y} (which is similar to Box-Cox transformation
35 | but works with negative values too), performed before using xgboost (and inverse transformed to the original scale afterwards).
36 | Set \code{lambda = 1} if no transformation is desired.
37 | The transformation is only applied to \code{y}, not \code{xreg}.}
38 |
39 | \item{verbose}{Passed on to \code{xgboost} and \code{xgb.cv}.}
40 |
41 | \item{seas_method}{Method for dealing with seasonality.}
42 |
43 | \item{K}{if \code{seas_method == 'fourier'}, the value of \code{K} passed through to \code{fourier} for order of Fourier series to be generated as seasonal regressor variables.}
44 |
45 | \item{trend_method}{How should the \code{xgboost} try to deal with trends? Currently the only options to \code{none} is
46 | \code{auto.arima}-style \code{differencing}, which is based on successive KPSS tests until there is no significant evidence the
47 | remaining series is non-stationary.}
48 |
49 | \item{...}{Additional arguments passed to \code{xgboost}. Only works if nrounds_method is "cv" or "manual".}
50 | }
51 | \value{
52 | An object of class \code{xgbar}. These have a \code{forecast} method and are generally
53 | expected to be used in a way such as \code{forecast(my_xgbar_model, h = 24)}. But the \code{xgbar}
54 | object itself can be of use in model checking and diagnosis. It is list with the following elements:
55 | \describe{
56 | \item{\code{y}}{The original value of \code{y} fed to \code{xgbar}}
57 | \item{\code{y2}}{\code{y} except for its first \code{maxlag} values. }
58 | \item{\code{x}}{The features used by \code{xgboost} to model \code{y2}. \code{x} is basically
59 | a matrix of numbers created by the automated feature generation of \code{xgbar}, in particular
60 | the differencing (if asked for), seasonal adjustment (if asked for), and creation of lagged
61 | values. If \code{y} is univariate,
62 | \code{x} will be just the lagged values of \code{y} and will have \code{length(y) - maxlag} rows
63 | and \code{maxlag} columns. If \code{xreg} was supplied, \code{x} will have \code{maxlag * (ncol(xreg) + 1)}
64 | columns - a set of columns for the lagged values of y, and a set of columns for each lagged value
65 | of the xreg matrix.}
66 | \item{\code{model}}{Object of class \code{xgb.Booster} returned by \code{xgboost}. The actual
67 | xgboost model that regressed \code{y2} on \code{x}.}
68 | \item{\code{fitted}}{Fitted values of \code{y}. The first \code{maxlag} values will be \code{NA}.
69 | The remainder are the predicted values of the xgboost regression of \code{y2} on \code{x}.}
70 | \item{\code{maxlag}}{The original user-supplied value of \code{maxlag}, stored for future use by
71 | \code{forecast.xgbar}.}
72 | \item{\code{seas_method}}{The original user-supplied value of \code{seas_method}, stored for future use by
73 | \code{forecast.xgbar}.}
74 | \item{\code{diffs}}{The number of rounds of differencing applied to y to make it stationary, if
75 | \code{trend_method = "differencing"} was used.}
76 | \item{\code{lambda}}{The original user-supplied value of \code{lambda} for modulus transformation,
77 | stored for future use by \code{forecast.xgbar}.}
78 | \item{\code{method}}{A character string summarising the key arguments to xgbar, of the structure
79 | \code{xgbar(maxlag, diffs, seas_method)}.}
80 | \item{\code{origxreg}}{The original user-supplied value of \code{origxreg},
81 | stored for future use by \code{forecast.xgbar} (needed to create future values of lagged \code{xreg}
82 | for the forecast period) .}
83 | \item{code{ncolxreg}}{The number of columns in the original \code{xreg} matrix.}
84 | \item{\code{decomp}}{If \code{seas_method = "decompose"} was used, this will be a list of the output
85 | from \code{decompose}, which decomposes y (called \code{x} by \code{decompose}) into seasonal, trend
86 | and random components.}
87 | }
88 | }
89 | \description{
90 | Fit a model to a time series using xgboost
91 | }
92 | \details{
93 | This is the workhorse function for the \code{forecastxgb} package.
94 | It fits a model to a time series. Under the hood, it creates a matrix of explanatory variables
95 | based on lagged versions of the response time series, and (optionally) dummy variables (simple hot one encoding, or Fourier transforms) for seasons. That
96 | matrix is then fed as the feature set for \code{xgboost} to do its stuff.
97 | }
98 | \examples{
99 | # Univariate example - quarterly production of woolen yarn in Australia
100 | woolmod <- xgbar(woolyrnq)
101 | summary(woolmod)
102 | plot(woolmod)
103 | fc <- forecast(woolmod, h = 8)
104 | plot(fc)
105 |
106 | # Bivariate example - quarterly income and consumption in the US
107 | if(require(fpp)){
108 | consumption <- usconsumption[ ,1]
109 | income <- matrix(usconsumption[ ,2], dimnames = list(NULL, "Income"))
110 | consumption_model <- xgbar(y = consumption, xreg = income)
111 | summary(consumption_model)
112 | }
113 | }
114 | \references{
115 | J. A. John and N. R. Draper (1980), "An Alternative Family of Transformations", \emph{Journal of the Royal Statistical
116 | Society}.
117 | }
118 | \seealso{
119 | \code{\link{summary.xgbar}}, \code{\link{plot.xgbar}}, \code{\link{forecast.xgbar}}, \code{\link{xgbar_importance}},
120 | \code{\link[xgboost]{xgboost}}.
121 | }
122 | \author{
123 | Peter Ellis
124 | }
125 |
--------------------------------------------------------------------------------
/pkg/man/xgbar_importance.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/extras.R
3 | \name{xgbar_importance}
4 | \alias{xgbar_importance}
5 | \title{Show importance of features in a xgbar model}
6 | \usage{
7 | xgbar_importance(object, ...)
8 | }
9 | \arguments{
10 | \item{object}{An object of class \code{xgbar}, usually created with \code{xgbar()}}
11 |
12 | \item{...}{Extra parameters passed through to \code{xgb.importance}}
13 | }
14 | \value{
15 | A \code{data.table} of the features used in the model with their average gain
16 | (and their weight for boosted tree model) in the model.
17 | }
18 | \description{
19 | This is a light wrapper for \code{xgboost::xbg.importance} to make it easier to use with objects of class \code{xgbar}
20 | }
21 | \seealso{
22 | \code{\link[xgboost]{xgb.importance}}, \code{\link{summary.xgbar}}, \code{\link{xgbar}}.
23 | }
24 | \author{
25 | Peter Ellis
26 | }
27 |
--------------------------------------------------------------------------------
/pkg/pkg.Rproj:
--------------------------------------------------------------------------------
1 | Version: 1.0
2 |
3 | RestoreWorkspace: No
4 | SaveWorkspace: No
5 | AlwaysSaveHistory: Default
6 |
7 | EnableCodeIndexing: Yes
8 | Encoding: UTF-8
9 |
10 | AutoAppendNewline: Yes
11 | StripTrailingWhitespace: Yes
12 |
13 | BuildType: Package
14 | PackageUseDevtools: Yes
15 | PackageInstallArgs: --no-multiarch --with-keep.source
16 | PackageRoxygenize: rd,collate,namespace
17 |
--------------------------------------------------------------------------------
/pkg/tests/testthat.R:
--------------------------------------------------------------------------------
1 | library(testthat)
2 | library(forecastxgb)
3 |
4 | test_check("forecastxgb")
5 |
--------------------------------------------------------------------------------
/pkg/tests/testthat/test-correct-classes.R:
--------------------------------------------------------------------------------
1 |
2 | #=================seasonal=====================
3 | fc1 <- forecast(AirPassengers, level = FALSE)
4 | object <- xgbar(AirPassengers, maxlag = 30)
5 | fc2 <- forecast(object)
6 |
7 |
8 | expect_identical(fc1$x, fc2$x)
9 | expect_identical(class(fc1$x), class(fc2$x))
10 | expect_identical(class(fc1$mean), class(fc2$mean))
11 | expect_identical(frequency(fc1$mean), frequency(fc2$mean))
12 |
13 |
14 | #=================non-seasonal================
15 | fc1 <- forecast(Nile, level = FALSE)
16 | object <- xgbar(Nile, maxlag = 30)
17 | fc2 <- forecast(object)
18 |
19 | expect_identical(fc1$x, fc2$x)
20 | expect_identical(class(fc1$x), class(fc2$x))
21 | expect_identical(class(fc1$mean), class(fc2$mean))
22 | expect_identical(frequency(fc1$mean), frequency(fc2$mean))
23 |
24 |
25 |
--------------------------------------------------------------------------------
/pkg/tests/testthat/test-irregular-seasons.R:
--------------------------------------------------------------------------------
1 |
2 | test_that("differencing and decompose work togetherwith data with an irregular set of seasons", {
3 | y <- subset(Tcomp::tourism, "quarterly")[[36]]$x
4 | expect_error(mod1 <- xgbar(y, trend_method = "differencing", seas_method = "decompose"), NA)
5 | plot(forecast(mod1))
6 | })
7 |
--------------------------------------------------------------------------------
/pkg/tests/testthat/test-modulus-transform.R:
--------------------------------------------------------------------------------
1 |
2 | test_that("Modulus transform and inverse work", {
3 | lambda <- BoxCox.lambda(AirPassengers)
4 | trans1 <- JDMod(AirPassengers, lambda = lambda)
5 | trans2 <- BoxCox(AirPassengers, lambda = lambda) # should be similar, not identical
6 | expect_lt(accuracy(trans1, trans2)[ ,"RMSE"], 0.002)
7 |
8 | return1 <- InvJDMod(trans1, lambda = lambda)
9 | expect_equal(AirPassengers, return1)
10 | })
11 |
12 | test_that("Modulus transform works with negative and zero data", {
13 | y <- ts(round(rnorm(100), 1))
14 | lambda <- BoxCox.lambda(abs(y))
15 | expect_error(trans1 <- JDMod(y, lambda = lambda), NA)
16 | expect_error(return1 <- InvJDMod(trans1, lambda = lambda), NA)
17 | expect_equal(y, return1)
18 | })
19 |
20 | test_that("Modulus transform works when lambda = 1 or 0",{
21 | y <- ts(round(rnorm(100), 1))
22 | expect_equal(y, JDMod(y, lambda = 1))
23 | expect_equal(log(AirPassengers + 1), JDMod(AirPassengers, lambda = 0))
24 |
25 | })
26 |
--------------------------------------------------------------------------------
/pkg/tests/testthat/test-ok-noninteger-frequency.R:
--------------------------------------------------------------------------------
1 |
2 |
3 | test_that("xgbar can fit models to time series with a non-integer frequency", {
4 | expect_error(model1 <- xgbar(seaice_ts, seas_method = "dummies"), NA)
5 | expect_error(model2 <- xgbar(seaice_ts, seas_method = "decompose"), NA)
6 | expect_error(model3 <- xgbar(seaice_ts, seas_method = "none"), NA)
7 | expect_error(model4 <- xgbar(seaice_ts, seas_method = "fourier", maxlag = 50), NA)
8 | expect_error(fc1 <- forecast(model1, h = 100), NA)
9 | expect_error(fc2 <- forecast(model2, h = 100), NA)
10 | expect_error(fc3 <- forecast(model2, h = 100), NA)
11 | expect_error(fc4 <- forecast(model2, h = 100), NA)
12 | })
13 |
14 |
15 |
--------------------------------------------------------------------------------
/pkg/tests/testthat/test-seasonal-methods.R:
--------------------------------------------------------------------------------
1 |
2 | test_that("different seasonal methods give different results", {
3 | y <- AirPassengers
4 |
5 |
6 | set.seed(123)
7 | obj1 <- xgbar(y, seas_method = "dummies")
8 | set.seed(123)
9 | obj2 <- xgbar(y, seas_method = "dummie")
10 | set.seed(123)
11 | obj3 <- xgbar(y, seas_method = "decompose")
12 | expect_equal(obj1, obj2)
13 | expect_false(isTRUE(all.equal(obj1, obj3)))
14 | expect_lt(accuracy(obj3$fitted, obj2$fitted)[ , "RMSE"], 8)
15 | })
--------------------------------------------------------------------------------
/pkg/tests/testthat/test-shorter-monthly-data.R:
--------------------------------------------------------------------------------
1 |
2 | test_that("works with series of 35 with frequency 12", {
3 | y <- ts(runif(35, min = 5000, max = 10000), start = c(2013, 12), frequency = 12)
4 | expect_error(bla_1_XGB_model <- xgbar(y = y), NA)
5 | })
--------------------------------------------------------------------------------
/pkg/tests/testthat/test-utils.R:
--------------------------------------------------------------------------------
1 |
2 | test_that("lagv produces the correct lagged matrix", {
3 | m <- cbind(6:10, 5:9, 4:8, 3:7, 2:6, 1:5)
4 | colnames(m) <- c("x", "x_lag1", "x_lag2", "x_lag3", "x_lag4", "x_lag5")
5 | x <- 1:10
6 | expect_equal(m, lagv(x, maxlag = 5))
7 | })
8 |
9 |
10 | test_that("lagvm produces the correct lagged matrix", {
11 | m <- cbind(3:4, 2:3, 1:2, 13:14, 12:13, 11:12)
12 | colnames(m) <- c("A_lag0", "A_lag1", "A_lag2", "B_lag0", "B_lag1","B_lag2")
13 | test <- cbind(1:4, 11:14)
14 | colnames(test) <- c("A", "B")
15 | expect_equal(m, lagvm(test, maxlag = 2))
16 | })
17 |
18 |
--------------------------------------------------------------------------------
/pkg/tests/testthat/test-works-range-data.R:
--------------------------------------------------------------------------------
1 |
2 |
3 | test_that("works with larger high frequency data", {
4 | # electricity_model <- xgbar(taylor)
5 | # electricity_fc <- forecast(electricity_model, 500)
6 | # plot(electricity_fc)
7 |
8 | })
--------------------------------------------------------------------------------
/pkg/tests/testthat/tests-different-maxlags.R:
--------------------------------------------------------------------------------
1 | test_that("forecast works with maxlag = 1", {
2 | mod <- xgbar(Nile, maxlag = 1)
3 | expect_error(fc <- forecast(mod, h = 10), NA)
4 | })
5 |
6 |
7 | test_that("forecast works with maxlag = 12", {
8 | mod <- xgbar(AirPassengers, maxlag = 12)
9 | expect_error(fc <- forecast(mod, h = 10), NA)
10 | })
11 |
12 |
13 | test_that("forecast works with maxlag = 36", {
14 | mod <- xgbar(AirPassengers, maxlag = 36)
15 | expect_error(fc <- forecast(mod, h = 10), NA)
16 | })
17 |
18 |
19 |
20 | test_that("forecast works with maxlag = 50", {
21 | mod <- xgbar(AirPassengers, maxlag = 36)
22 | expect_error(fc <- forecast(mod, h = 10), NA)
23 | })
24 |
25 |
--------------------------------------------------------------------------------
/pkg/vignettes/xgbar.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Extreme gradient boosting time series forecasting"
3 | author: "Peter Ellis"
4 | date: "26 November 2016"
5 | output: rmarkdown::html_vignette
6 | vignette: >
7 | %\VignetteIndexEntry{Extreme gradient boosting time series forecasting}
8 | %\VignetteEngine{knitr::rmarkdown}
9 | %\VignetteEncoding{UTF-8}
10 | ---
11 |
12 | The `forecastxgb` package provides time series modelling and forecasting functions that combine the machine learning approach of Chen, He and Benesty's [`xgboost`](https://CRAN.R-project.org/package=xgboost) with the convenient handling of time series and familiar API of Rob Hyndman's [`forecast`](http://github.com/robjhyndman/forecast). It applies to time series the Extreme Gradient Boosting proposed in [*Greedy Function Approximation: A Gradient Boosting Machine*, by Jerome Friedman in 2001](http://www.jstor.org/stable/2699986). xgboost has become an important machine learning algorithm; nicely explained in [this accessible documentation](http://xgboost.readthedocs.io/en/latest/model.html).
13 |
14 | **Warning: this package is under active development. The API and default settings should be expected to continue to change.**
15 |
16 | ## Basic usage
17 |
18 | The workhorse function is `xgbar`. This fits a model to a time series. Under the hood, it creates a matrix of explanatory variables based on lagged versions of the response time series, and (optionally) dummy variables of some sort for seasons. That matrix is then fed as the feature set for `xgboost` to do its stuff.
19 |
20 | ```{r echo = FALSE, cache = FALSE}
21 | set.seed(123)
22 | library(knitr)
23 | knit_hooks$set(mypar = function(before, options, envir) {
24 | if (before) par(bty = "l", family = "serif")
25 | })
26 | opts_chunk$set(comment=NA, fig.width=7, fig.height=5, cache = FALSE, mypar = TRUE)
27 | ```
28 |
29 | ### Univariate
30 |
31 | Usage with default values is straightforward. Here it is fit to Australian monthly gas production 1956-1995, an example dataset provided in `forecast`:
32 | ```{r message = FALSE}
33 | library(forecastxgb)
34 | model <- xgbar(gas)
35 | ```
36 | (Note: the "Stopping. Best iteration..." to the screen is produced by `xgboost::xgb.cv`, which uses `cat()` rather than `message()` to print information on its processing.)
37 |
38 | By default, `xgbar` uses row-wise cross-validation to determine the best number of rounds of iterations for the boosting algorithm without overfitting. A final model is then fit on the full available dataset. The relative importance of the various features in the model can be inspected by `importance_xgb()` or, more conveniently, the `summary` method for objects of class `xgbar`.
39 |
40 |
41 | ```{r}
42 | summary(model)
43 | ```
44 | We see in the case of the gas data that the most important feature in explaining gas production is the production 12 months previously; and then other features decrease in importance from there but still have an impact.
45 |
46 | Forecasting is the main purpose of this package, and a `forecast` method is supplied. The resulting objects are of class `forecast` and familiar generic functions work with them.
47 |
48 | ```{r}
49 | fc <- forecast(model, h = 12)
50 | plot(fc)
51 | ```
52 | Note that prediction intervals are not currently available.
53 |
54 | ### With external regressors
55 | External regressors can be added by using the `xreg` argument familiar from other forecast functions like `auto.arima` and `nnetar`. `xreg` can be a vector or `ts` object but is easiest to integrate into the analysis if it is a matrix (even a matrix with one column) with well-chosen column names; that way feature names persist meaningfully.
56 |
57 | The example below, with data taken from the `fpp` package supporting Athanasopoulos and Hyndman's [Forecasting Principles and Practice](https://www.otexts.org/fpp) book, shows income being used to explain consumption. In the same way that the response variable `y` is expanded into lagged versions of itself, each column in `xreg` is expanded into lagged versions, which are then treated as individual features for `xgboost`.
58 |
59 | ```{r message = FALSE}
60 | library(fpp)
61 | consumption <- usconsumption[ ,1]
62 | income <- matrix(usconsumption[ ,2], dimnames = list(NULL, "Income"))
63 | consumption_model <- xgbar(y = consumption, xreg = income)
64 | summary(consumption_model)
65 | ```
66 | We see that the two most important features explaining consumption are the two previous quarters' values of consumption; followed by the income in this quarter; and so on.
67 |
68 |
69 | The challenge of using external regressors in a forecasting environment is that to forecast, you need values of the future external regressors. One way this is sometimes done is by first forecasting the individual regressors. In the example below we do this, making sure the data structure is the same as the original `xreg`. When the new value of `xreg` is given to `forecast`, it forecasts forward the number of rows of the new `xreg`.
70 | ```{r}
71 | income_future <- matrix(forecast(xgbar(usconsumption[,2]), h = 10)$mean,
72 | dimnames = list(NULL, "Income"))
73 | plot(forecast(consumption_model, xreg = income_future))
74 | ```
75 |
76 |
77 | ## Advanced usage
78 | The default settings for `xgbar` give reasonable results. The key things that can be changed by the user include:
79 |
80 | - the maximum number of lags to include as explanatory variables. There is a trade-off here, as each number higher this gets, the less rows of data you have. Generally at least two full seasonal cycles are desired, and the default is `max(8, 2 * frequency(y))`. When the data gets very short this value is sometimes forced lower, with a warning.
81 | - the method for choosing the maximum number of boosting iterations. The default is row-wise cross validation, after the matrix of lagged explanatory variables has been created. This is not a traditional approach for cross validation of time series, because the resampling does not preserve the original ordering. However, the presence of the lagged values means this is less of an issue. The main alternative (`nrounds_method = "v"`) is to set aside the final 20% of data and use that for validation of the various numbers of rounds of iterations of the first 80% of training data. Experiments so far suggest that both methods give similar results; if anything the cross-validation method generally recommends a slightly lower number of iterations than does the alternative.
82 |
83 | ## Options
84 |
85 | ### Seasonality
86 |
87 | Currently there are three methods of treating seasonality.
88 |
89 | - The current default method is to throw dummy variables for each season into the mix of features for `xgboost` to work with.
90 | - An alternative is to perform classic multiplicative seasonal adjustment on the series before feeding it to `xgboost`. This seems to work better.
91 | - A third option is to create a set of pairs of Fourier transform variables and use them as x regressors
92 |
93 | ```{r echo = FALSE}
94 | model1 <- xgbar(co2, seas_method = "dummies")
95 | model2 <- xgbar(co2, seas_method = "decompose")
96 | model3 <- xgbar(co2, seas_method = "fourier")
97 | plot(forecast(model1), main = "Dummy variables for seasonality")
98 | plot(forecast(model2), main = "Decomposition seasonal adjustment for seasonality")
99 | plot(forecast(model3), main = "Fourier transform pairs as x regressors")
100 | ```
101 |
102 | All methods perform quite poorly at the moment, suffering from the difficulty the default settings have in dealing with non-stationary data (see below).
103 |
104 | ### Transformations
105 |
106 | The data can be transformed by a modulus power transformation (as per John and Draper, 1980) before feeding to `xgboost`. This transformation is similar to a Box-Cox transformation, but works with negative data. Leaving the `lambda` parameter as 1 will effectively switch off this transformation.
107 | ```{r echo = FALSE}
108 | model1 <- xgbar(co2, seas_method = "decompose", lambda = 1)
109 | model2 <- xgbar(co2, seas_method = "decompose", lambda = BoxCox.lambda(co2))
110 | plot(forecast(model1), main = "No transformation")
111 | plot(forecast(model2), main = "With transformation")
112 | ```
113 |
114 | Version 0.0.9 of `forecastxgb` gave `lambda` the default value of `BoxCox.lambda(abs(y))`. This returned spectacularly bad forecasting results. Forcing this to be between 0 and 1 helped a little, but still gave very bad results. So far there isn't evidence (but neither is there enough investigation) that a Box Cox transformation helps xgbar do its model fitting at all.
115 |
116 | ### Non-stationarity
117 | From experiments so far, it seems the basic idea of `xgboost` struggles in this context with extrapolation into a new range of variables not in the training set. This suggests better results might be obtained by transforming the series into a stationary one before modelling - a similar approach to that taken by `forecast::auto.arima`. This option is available by `trend_method = "differencing"` and seems to perform well - certainly better than without - and it will probably be made a default setting once more experience is available.
118 |
119 | ```{r}
120 | model <- xgbar(AirPassengers, trend_method = "differencing", seas_method = "fourier")
121 | plot(forecast(model, 24))
122 | ```
123 |
124 |
125 | ## Future developments
126 | Future work might include:
127 |
128 | * additional automated time-dependent features (eg dummy variables for trading days, Easter, etc)
129 | * ability to include xreg values that don't get lagged
130 | * some kind of automated multiple variable forecasting, similar to a vector-autoregression.
131 | * better choices of defaults for values such as `lambda` (for power transformations), `K` (for Fourier transforms) and, most likely to be effective, `maxlag`.
132 |
133 | ## Tourism forecasting competition
134 | Here is a more substantive example. I use the 1,311 datasets from the 2010 Tourism Forecasting Competition described in
135 | in [Athanasopoulos et al (2011)](http://robjhyndman.com/papers/forecompijf.pdf), originally in the International Journal of Forecasting (2011) 27(3), 822-844. The data are available in the CRAN package [Tcomp](https://cran.r-project.org/package=Tcomp). Each data object is a list, with elements inlcuding `x` (the original training data), `h` (the forecasting period) and `xx` (the test data of length `h`). Only univariate time series are included.
136 |
137 | To give the `xgbar` model a good test, I am going to compare its performance in forecasting the 1,311 `xx` time series from the matching `x` series with three other modelling approaches:
138 |
139 | - Auto-regressive integrated moving average (ARIMA)
140 | - Theta
141 | - Neural networks
142 |
143 | Those three are all from Rob Hyndman's `forecast` package. I am also going to look at the performance of ensembles of the four model types. With all combinations this means 15 models in total.
144 |
145 | Because all four models use the `forecast` paradigm it is relatively straightforward to structure the analysis. The code below is a little repetitive but should be fairly transparent. Because of the scale and the embarrassingly parallel nature of the work (ie no particular reason to do it in any particular order, so easy to split into tasks for different processes to do in parallel), I use `foreach` and `doParallel` to make the best use of my 8 logical processors. The code below sets up a cluster for the parallel computing and a function `competition` which will work on any object of class `Mcomp`, which `Tcomp` inherits from the `Mcomp` package providing the first three "M" forecasting competition data collections.
146 |
147 | ```{r message = FALSE}
148 | #=============prep======================
149 | library(Tcomp)
150 | library(foreach)
151 | library(doParallel)
152 | library(forecastxgb)
153 | library(dplyr)
154 | library(ggplot2)
155 | library(scales)
156 | ```
157 | ```{r eval = FALSE}
158 | #============set up cluster for parallel computing===========
159 | cluster <- makeCluster(7) # only any good if you have at least 7 processors :)
160 | registerDoParallel(cluster)
161 |
162 | clusterEvalQ(cluster, {
163 | library(Tcomp)
164 | library(forecastxgb)
165 | })
166 |
167 |
168 | #===============the actual analytical function==============
169 | competition <- function(collection, maxfors = length(collection)){
170 | if(class(collection) != "Mcomp"){
171 | stop("This function only works on objects of class Mcomp, eg from the Mcomp or Tcomp packages.")
172 | }
173 | nseries <- length(collection)
174 | mases <- foreach(i = 1:maxfors, .combine = "rbind") %dopar% {
175 | thedata <- collection[[i]]
176 | seas_method <- ifelse(frequency(thedata$x) < 6, "dummies", "fourier")
177 | mod1 <- xgbar(thedata$x, trend_method = "differencing", seas_method = seas_method, lambda = 1, K = 2)
178 | fc1 <- forecast(mod1, h = thedata$h)
179 | fc2 <- thetaf(thedata$x, h = thedata$h)
180 | fc3 <- forecast(auto.arima(thedata$x), h = thedata$h)
181 | fc4 <- forecast(nnetar(thedata$x), h = thedata$h)
182 | # copy the skeleton of fc1 over for ensembles:
183 | fc12 <- fc13 <- fc14 <- fc23 <- fc24 <- fc34 <- fc123 <- fc124 <- fc134 <- fc234 <- fc1234 <- fc1
184 | # replace the point forecasts with averages of member forecasts:
185 | fc12$mean <- (fc1$mean + fc2$mean) / 2
186 | fc13$mean <- (fc1$mean + fc3$mean) / 2
187 | fc14$mean <- (fc1$mean + fc4$mean) / 2
188 | fc23$mean <- (fc2$mean + fc3$mean) / 2
189 | fc24$mean <- (fc2$mean + fc4$mean) / 2
190 | fc34$mean <- (fc3$mean + fc4$mean) / 2
191 | fc123$mean <- (fc1$mean + fc2$mean + fc3$mean) / 3
192 | fc124$mean <- (fc1$mean + fc2$mean + fc4$mean) / 3
193 | fc134$mean <- (fc1$mean + fc3$mean + fc4$mean) / 3
194 | fc234$mean <- (fc2$mean + fc3$mean + fc4$mean) / 3
195 | fc1234$mean <- (fc1$mean + fc2$mean + fc3$mean + fc4$mean) / 4
196 | mase <- c(accuracy(fc1, thedata$xx)[2, 6],
197 | accuracy(fc2, thedata$xx)[2, 6],
198 | accuracy(fc3, thedata$xx)[2, 6],
199 | accuracy(fc4, thedata$xx)[2, 6],
200 | accuracy(fc12, thedata$xx)[2, 6],
201 | accuracy(fc13, thedata$xx)[2, 6],
202 | accuracy(fc14, thedata$xx)[2, 6],
203 | accuracy(fc23, thedata$xx)[2, 6],
204 | accuracy(fc24, thedata$xx)[2, 6],
205 | accuracy(fc34, thedata$xx)[2, 6],
206 | accuracy(fc123, thedata$xx)[2, 6],
207 | accuracy(fc124, thedata$xx)[2, 6],
208 | accuracy(fc134, thedata$xx)[2, 6],
209 | accuracy(fc234, thedata$xx)[2, 6],
210 | accuracy(fc1234, thedata$xx)[2, 6])
211 | mase
212 | }
213 | message("Finished fitting models")
214 | colnames(mases) <- c("x", "f", "a", "n", "xf", "xa", "xn", "fa", "fn", "an",
215 | "xfa", "xfn", "xan", "fan", "xfan")
216 | return(mases)
217 | }
218 | ```
219 |
220 | Applying this function to the three different subsets of tourism data (by different frequency) is straightforward but takes a few minutes to run:
221 |
222 | ```{r eval = FALSE}
223 | #========Fit models==============
224 | system.time(t1 <- competition(subset(tourism, "yearly")))
225 | system.time(t4 <- competition(subset(tourism, "quarterly")))
226 | system.time(t12 <- competition(subset(tourism, "monthly")))
227 |
228 | # shut down cluster to avoid any mess:
229 | stopCluster(cluster)
230 | ```
231 |
232 | The `competition` function returns the mean absolute scaled error (MASE) of every model combination for every dataset. The following code creates a summary object from the objects `t1`, `t4` and `t12` that hold those individual results:
233 |
234 | ```{r eval = FALSE}
235 | #==============present results================
236 | results <- c(apply(t1, 2, mean),
237 | apply(t4, 2, mean),
238 | apply(t12, 2, mean))
239 |
240 | results_df <- data.frame(MASE = results)
241 | results_df$model <- as.character(names(results))
242 | periods <- c("Annual", "Quarterly", "Monthly")
243 | results_df$Frequency <- rep.int(periods, times = c(15, 15, 15))
244 |
245 | best <- results_df %>%
246 | group_by(model) %>%
247 | summarise(MASE = mean(MASE)) %>%
248 | arrange(MASE) %>%
249 | mutate(Frequency = "Average")
250 |
251 | Tcomp_results <- results_df %>%
252 | rbind(best) %>%
253 | mutate(model = factor(model, levels = best$model)) %>%
254 | mutate(Frequency = factor(Frequency, levels = c("Annual", "Average", "Quarterly", "Monthly")))
255 | ```
256 |
257 | The resulting object, `Tcomp_results`, is provided with the `forecastxgb` package. Visual inspection shows that the average values of MASE provided for the Theta and ARIMA models match those in the [`Tcomp` vignette](https://cran.r-project.org/web/packages/Tcomp/vignettes/tourism-comp.html). The results are easiest to understand graphically.
258 |
259 | ```{r, fig.width = 8, fig.height = 6}
260 | leg <- "f: Theta; forecast::thetaf\na: ARIMA; forecast::auto.arima
261 | n: Neural network; forecast::nnetar\nx: Extreme gradient boosting; forecastxgb::xgbar"
262 |
263 | Tcomp_results %>%
264 | ggplot(aes(x = model, y = MASE, colour = Frequency, label = model)) +
265 | geom_text(size = 4) +
266 | geom_line(aes(x = as.numeric(model)), alpha = 0.25) +
267 | scale_y_continuous("Mean scaled absolute error\n(smaller numbers are better)") +
268 | annotate("text", x = 2, y = 3.5, label = leg, hjust = 0) +
269 | ggtitle("Average error of four different timeseries forecasting methods\n2010 Tourism Forecasting Competition data") +
270 | labs(x = "Model, or ensemble of models\n(further to the left means better overall performance)") +
271 | theme_grey(9)
272 | ```
273 |
274 |
275 | We see the overall best performing ensemble is the average of the Theta and ARIMA models - the two from the more traditional timeseries forecasting approach. The two machine learning methods (neural network and extreme gradient boosting) are not as effective, at least in these implementations. As individual methods, they are the two weakest, although the extreme gradient boosting method provided in `forecastxgb` performs noticeably better than `forecast::nnetar` for the annual and quarterly data.
276 |
277 | Theta by itself is the best performing with the annual data - simple methods work well when the dataset is small and highly aggregate. The best that can be said of the `xgbar` approach in this context is that it doesn't damage the Theta method much when included in a combination - several of the better performing ensembles have `xgbar` as one of their members. In contrast, the neural network models do badly with this collection of annual data.
278 |
279 | Adding `auto.arima` and `xgbar` to an ensemble of quarterly or monthly data definitely improves on Theta by itself. The best performing single model for quarterly or monthly data is `auto.arima` followed by `thetaf`. Again, neural networks are the poorest of the four individual models.
280 |
281 | Overall, I conclude that with univariate data, `xgbar` has little to add to an ensemble that already contains `auto.arima` and `thetaf` (or - not shown - the closely related `ets`). I believe however that inclusion of `xreg` external regressors would shift the balance in favour of `xgbar` and maybe even `nnetar` - the more complex and larger the dataset, the better the chance that these methods will have something to offer. If and when I find a large collection of timeseries competition data with external regressors I will probably add a second vignette, or at least a blog post at [http://ellisp.github.io](http://ellisp.github.io).
--------------------------------------------------------------------------------
/prep/get-seaice-data.R:
--------------------------------------------------------------------------------
1 | # This script gets the example Arctic sea ice data
2 | library(dplyr)
3 | library(testthat)
4 | library(lubridate)
5 |
6 | mon <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
7 |
8 | # https://nsidc.org/data/docs/noaa/g02135_seaice_index/#daily_data_files
9 |
10 | # This is the latest incomplete year's "near real time" data:
11 | download.file("ftp://sidads.colorado.edu/DATASETS/NOAA/G02135/north/daily/data/NH_seaice_extent_nrt_v2.csv",
12 | destfile = "seaice_nrt.csv")
13 |
14 | # And this is the earlier, fully definitive years' data
15 | download.file("ftp://sidads.colorado.edu/DATASETS/NOAA/G02135/north/daily/data/NH_seaice_extent_final_v2.csv",
16 | destfile = "seaice_final.csv")
17 |
18 | seaice_nrt <- read.csv("seaice_nrt.csv", skip = 2, header = FALSE)[ , 1:5]
19 | seaice_final <- read.csv("seaice_final.csv", skip = 2, header = FALSE)[ , 1:5]
20 |
21 | seaice <- rbind(seaice_final, seaice_nrt)
22 | names(seaice) <- c("year", "month", "day", "extent", "missing")
23 | expect_equal(sum(seaice$missing == 0), nrow(seaice))
24 |
25 | seaice <- seaice %>%
26 | mutate(date = as.Date(paste(year, month, day, sep = "-"))) %>%
27 | group_by(month) %>%
28 | mutate(monthday = month + day / max(day)) %>%
29 | ungroup() %>%
30 | mutate(month = factor(month, labels = mon)) %>%
31 | arrange(year, month, day) %>%
32 | mutate(timediff = c(NA, diff(date)),
33 | dayofyear = yday(date)) %>%
34 | filter(timediff == 1)
35 |
36 |
37 |
38 | seaice_ts <- ts(seaice$extent, frequency = 365.25, start = c(1987, 233))
39 | save(seaice_ts, file = "pkg/data/seaice_ts.rda")
40 |
41 | # clean up (unless you want to keep the csvs)
42 | unlink("seaice_nrt.csv")
43 | unlink("seaice_final.csv")
--------------------------------------------------------------------------------