├── .Rbuildignore ├── .gitignore ├── CRAN-SUBMISSION ├── DESCRIPTION ├── LICENSE.md ├── NAMESPACE ├── NEWS.md ├── R ├── arml.R ├── fit_conformal_reg.R ├── forecast.R ├── predict_conformal.R └── utils.R ├── README.Rmd ├── README.md ├── caretForecast.Rproj ├── cran-comments.md ├── data ├── retail.rda └── retail_wide.rda ├── man ├── ARml.Rd ├── conformalRegressor.Rd ├── figures │ ├── README-example-1.png │ ├── README-example-2.png │ ├── README-example-3.png │ ├── README-example-4.png │ ├── README-example-5.png │ ├── README-example-6.png │ ├── README-example2-1.png │ ├── README-example3-1.png │ ├── README-example4-1.png │ ├── README-example4-2.png │ ├── README-example5-1.png │ ├── README-example5-2.png │ ├── README-example6-1.png │ ├── README-example6-2.png │ └── README-example7-1.png ├── forecast.ARml.Rd ├── get_var_imp.Rd ├── predict.conformalRegressor.Rd ├── reexports.Rd ├── retail.Rd ├── retail_wide.Rd ├── split_ts.Rd └── suggested_methods.Rd └── tests ├── testthat.R └── testthat ├── test-ARml.R ├── test-conformal_pred.R ├── test-forecast.ARml.R ├── test-get_var_imp.R ├── test-split_ts.R └── test-suggested_method.R /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^caretForecast\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^LICENSE\.md$ 4 | ^\.travis\.yml$ 5 | ^cran-comments\.md$ 6 | ^README\.Rmd$ 7 | ^_pkgdown\.yml$ 8 | ^docs$ 9 | ^pkgdown$ 10 | ^\.github$ 11 | ^_config.yml 12 | ^CRAN-RELEASE$ 13 | ^CRAN-SUBMISSION$ 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rhistory 2 | .Rapp.history.RData.Ruserdata 3 | *-Ex.R/*.tar.gz/*.Rcheck/.Rproj.user/ 4 | vignettes/*.html 5 | vignettes/*.pdf 6 | .httr-oauth 7 | *_cache/ 8 | /cache/ 9 | *.utf8.md 10 | *.knit.md 11 | .Renviron 12 | po/*~ 13 | .Rapp.history 14 | .RData 15 | .Ruserdata 16 | *-Ex.R 17 | /*.tar.gz 18 | /*.Rcheck/ 19 | .Rproj.user/ 20 | .DS_Store 21 | docs 22 | -------------------------------------------------------------------------------- /CRAN-SUBMISSION: -------------------------------------------------------------------------------- 1 | Version: 0.1.1 2 | Date: 2022-10-23 19:55:28 UTC 3 | SHA: 8f9d65c189202cc31ce9d95940002e2dbfc29d4c 4 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: caretForecast 2 | Title: Conformal Time Series Forecasting Using State of Art Machine Learning Algorithms 3 | Version: 0.1.1 4 | Authors@R: 5 | person(given = "Resul", 6 | family = "Akay", 7 | role = c("aut", "cre"), 8 | email = "resulakay1@gmail.com") 9 | Description: Conformal time series forecasting using the caret infrastructure. 10 | It provides access to state-of-the-art machine learning models for forecasting 11 | applications. The hyperparameter of each model is selected based on time 12 | series cross-validation, and forecasting is done recursively. 13 | License: GPL (>= 3) 14 | URL: https://github.com/Akai01/caretForecast 15 | BugReports: https://github.com/Akai01/caretForecast/issues 16 | Depends: 17 | R (>= 3.6) 18 | Imports: 19 | forecast (>= 8.15), 20 | caret (>= 6.0.88), 21 | magrittr (>= 2.0.1), 22 | methods (>= 4.1.1), 23 | dplyr (>= 1.0.9), 24 | generics (>= 0.1.3) 25 | Suggests: 26 | Cubist (>= 0.3.0), 27 | knitr (>= 1.29), 28 | testthat (>= 2.3.2) 29 | Encoding: UTF-8 30 | LazyData: true 31 | Roxygen: list(markdown = TRUE) 32 | RoxygenNote: 7.2.1 33 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU General Public License 2 | ========================== 3 | 4 | _Version 3, 29 June 2007_ 5 | _Copyright © 2007 Free Software Foundation, Inc. <>_ 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license 8 | document, but changing it is not allowed. 9 | 10 | ## Preamble 11 | 12 | The GNU General Public License is a free, copyleft license for software and other 13 | kinds of works. 14 | 15 | The licenses for most software and other practical works are designed to take away 16 | your freedom to share and change the works. By contrast, the GNU General Public 17 | License is intended to guarantee your freedom to share and change all versions of a 18 | program--to make sure it remains free software for all its users. We, the Free 19 | Software Foundation, use the GNU General Public License for most of our software; it 20 | applies also to any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not price. Our General 24 | Public Licenses are designed to make sure that you have the freedom to distribute 25 | copies of free software (and charge for them if you wish), that you receive source 26 | code or can get it if you want it, that you can change the software or use pieces of 27 | it in new 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 these rights or 30 | asking you to surrender the rights. Therefore, you have certain responsibilities if 31 | you distribute copies of the software, or if you modify it: responsibilities to 32 | respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for a fee, 35 | you must pass on to the recipients the same freedoms that you received. You must make 36 | sure that they, too, receive or can get the source code. And you must show them these 37 | terms so they know their rights. 38 | 39 | Developers that use the GNU GPL protect your rights with two steps: **(1)** assert 40 | copyright on the software, and **(2)** offer you this License giving you legal permission 41 | to copy, distribute and/or modify it. 42 | 43 | For the developers' and authors' protection, the GPL clearly explains that there is 44 | no warranty for this free software. For both users' and authors' sake, the GPL 45 | requires that modified versions be marked as changed, so that their problems will not 46 | be attributed erroneously to authors of previous versions. 47 | 48 | Some devices are designed to deny users access to install or run modified versions of 49 | the software inside them, although the manufacturer can do so. This is fundamentally 50 | incompatible with the aim of protecting users' freedom to change the software. The 51 | systematic pattern of such abuse occurs in the area of products for individuals to 52 | use, which is precisely where it is most unacceptable. Therefore, we have designed 53 | this version of the GPL to prohibit the practice for those products. If such problems 54 | arise substantially in other domains, we stand ready to extend this provision to 55 | those domains in future versions of the GPL, as needed to protect the freedom of 56 | users. 57 | 58 | Finally, every program is threatened constantly by software patents. States should 59 | not allow patents to restrict development and use of software on general-purpose 60 | computers, but in those that do, we wish to avoid the special danger that patents 61 | applied to a free program could make it effectively proprietary. To prevent this, the 62 | GPL assures that patents cannot be used to render the program non-free. 63 | 64 | The precise terms and conditions for copying, distribution and modification follow. 65 | 66 | ## TERMS AND CONDITIONS 67 | 68 | ### 0. Definitions 69 | 70 | “This License” refers to version 3 of the GNU General Public License. 71 | 72 | “Copyright” also means copyright-like laws that apply to other kinds of 73 | works, such as semiconductor masks. 74 | 75 | “The Program” refers to any copyrightable work licensed under this 76 | License. Each licensee is addressed as “you”. “Licensees” and 77 | “recipients” may be individuals or organizations. 78 | 79 | To “modify” a work means to copy from or adapt all or part of the work in 80 | a fashion requiring copyright permission, other than the making of an exact copy. The 81 | resulting work is called a “modified version” of the earlier work or a 82 | work “based on” the earlier work. 83 | 84 | A “covered work” means either the unmodified Program or a work based on 85 | the Program. 86 | 87 | To “propagate” a work means to do anything with it that, without 88 | permission, would make you directly or secondarily liable for infringement under 89 | applicable copyright law, except executing it on a computer or modifying a private 90 | copy. Propagation includes copying, distribution (with or without modification), 91 | making available to the public, and in some countries other activities as well. 92 | 93 | To “convey” a work means any kind of propagation that enables other 94 | parties to make or receive copies. Mere interaction with a user through a computer 95 | network, with no transfer of a copy, is not conveying. 96 | 97 | An interactive user interface displays “Appropriate Legal Notices” to the 98 | extent that it includes a convenient and prominently visible feature that **(1)** 99 | displays an appropriate copyright notice, and **(2)** tells the user that there is no 100 | warranty for the work (except to the extent that warranties are provided), that 101 | licensees may convey the work under this License, and how to view a copy of this 102 | License. If the interface presents a list of user commands or options, such as a 103 | menu, a prominent item in the list meets this criterion. 104 | 105 | ### 1. Source Code 106 | 107 | The “source code” for a work means the preferred form of the work for 108 | making modifications to it. “Object code” means any non-source form of a 109 | work. 110 | 111 | A “Standard Interface” means an interface that either is an official 112 | standard defined by a recognized standards body, or, in the case of interfaces 113 | specified for a particular programming language, one that is widely used among 114 | developers working in that language. 115 | 116 | The “System Libraries” of an executable work include anything, other than 117 | the work as a whole, that **(a)** is included in the normal form of packaging a Major 118 | Component, but which is not part of that Major Component, and **(b)** serves only to 119 | enable use of the work with that Major Component, or to implement a Standard 120 | Interface for which an implementation is available to the public in source code form. 121 | A “Major Component”, in this context, means a major essential component 122 | (kernel, window system, and so on) of the specific operating system (if any) on which 123 | the executable work runs, or a compiler used to produce the work, or an object code 124 | interpreter used to run it. 125 | 126 | The “Corresponding Source” for a work in object code form means all the 127 | source code needed to generate, install, and (for an executable work) run the object 128 | code and to modify the work, including scripts to control those activities. However, 129 | it does not include the work's System Libraries, or general-purpose tools or 130 | generally available free programs which are used unmodified in performing those 131 | activities but which are not part of the work. For example, Corresponding Source 132 | includes interface definition files associated with source files for the work, and 133 | the source code for shared libraries and dynamically linked subprograms that the work 134 | is specifically designed to require, such as by intimate data communication or 135 | control flow between those subprograms and other parts of the work. 136 | 137 | The Corresponding Source need not include anything that users can regenerate 138 | automatically from other parts of the Corresponding Source. 139 | 140 | The Corresponding Source for a work in source code form is that same work. 141 | 142 | ### 2. Basic Permissions 143 | 144 | All rights granted under this License are granted for the term of copyright on the 145 | Program, and are irrevocable provided the stated conditions are met. This License 146 | explicitly affirms your unlimited permission to run the unmodified Program. The 147 | output from running a covered work is covered by this License only if the output, 148 | given its content, constitutes a covered work. This License acknowledges your rights 149 | of fair use or other equivalent, as provided by copyright law. 150 | 151 | You may make, run and propagate covered works that you do not convey, without 152 | conditions so long as your license otherwise remains in force. You may convey covered 153 | works to others for the sole purpose of having them make modifications exclusively 154 | for you, or provide you with facilities for running those works, provided that you 155 | comply with the terms of this License in conveying all material for which you do not 156 | control copyright. Those thus making or running the covered works for you must do so 157 | exclusively on your behalf, under your direction and control, on terms that prohibit 158 | them from making any copies of your copyrighted material outside their relationship 159 | with you. 160 | 161 | Conveying under any other circumstances is permitted solely under the conditions 162 | stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 163 | 164 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law 165 | 166 | No covered work shall be deemed part of an effective technological measure under any 167 | applicable law fulfilling obligations under article 11 of the WIPO copyright treaty 168 | adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention 169 | of such measures. 170 | 171 | When you convey a covered work, you waive any legal power to forbid circumvention of 172 | technological measures to the extent such circumvention is effected by exercising 173 | rights under this License with respect to the covered work, and you disclaim any 174 | intention to limit operation or modification of the work as a means of enforcing, 175 | against the work's users, your or third parties' legal rights to forbid circumvention 176 | of technological measures. 177 | 178 | ### 4. Conveying Verbatim Copies 179 | 180 | You may convey verbatim copies of the Program's source code as you receive it, in any 181 | medium, provided that you conspicuously and appropriately publish on each copy an 182 | appropriate copyright notice; keep intact all notices stating that this License and 183 | any non-permissive terms added in accord with section 7 apply to the code; keep 184 | intact all notices of the absence of any warranty; and give all recipients a copy of 185 | this License along with the Program. 186 | 187 | You may charge any price or no price for each copy that you convey, and you may offer 188 | support or warranty protection for a fee. 189 | 190 | ### 5. Conveying Modified Source Versions 191 | 192 | You may convey a work based on the Program, or the modifications to produce it from 193 | the Program, in the form of source code under the terms of section 4, provided that 194 | you also meet all of these conditions: 195 | 196 | * **a)** The work must carry prominent notices stating that you modified it, and giving a 197 | relevant date. 198 | * **b)** The work must carry prominent notices stating that it is released under this 199 | License and any conditions added under section 7. This requirement modifies the 200 | requirement in section 4 to “keep intact all notices”. 201 | * **c)** You must license the entire work, as a whole, under this License to anyone who 202 | comes into possession of a copy. This License will therefore apply, along with any 203 | applicable section 7 additional terms, to the whole of the work, and all its parts, 204 | regardless of how they are packaged. This License gives no permission to license the 205 | work in any other way, but it does not invalidate such permission if you have 206 | separately received it. 207 | * **d)** If the work has interactive user interfaces, each must display Appropriate Legal 208 | Notices; however, if the Program has interactive interfaces that do not display 209 | Appropriate Legal Notices, your work need not make them do so. 210 | 211 | A compilation of a covered work with other separate and independent works, which are 212 | not by their nature extensions of the covered work, and which are not combined with 213 | it such as to form a larger program, in or on a volume of a storage or distribution 214 | medium, is called an “aggregate” if the compilation and its resulting 215 | copyright are not used to limit the access or legal rights of the compilation's users 216 | beyond what the individual works permit. Inclusion of a covered work in an aggregate 217 | does not cause this License to apply to the other parts of the aggregate. 218 | 219 | ### 6. Conveying Non-Source Forms 220 | 221 | You may convey a covered work in object code form under the terms of sections 4 and 222 | 5, provided that you also convey the machine-readable Corresponding Source under the 223 | terms of this License, in one of these ways: 224 | 225 | * **a)** Convey the object code in, or embodied in, a physical product (including a 226 | physical distribution medium), accompanied by the Corresponding Source fixed on a 227 | durable physical medium customarily used for software interchange. 228 | * **b)** Convey the object code in, or embodied in, a physical product (including a 229 | physical distribution medium), accompanied by a written offer, valid for at least 230 | three years and valid for as long as you offer spare parts or customer support for 231 | that product model, to give anyone who possesses the object code either **(1)** a copy of 232 | the Corresponding Source for all the software in the product that is covered by this 233 | License, on a durable physical medium customarily used for software interchange, for 234 | a price no more than your reasonable cost of physically performing this conveying of 235 | source, or **(2)** access to copy the Corresponding Source from a network server at no 236 | charge. 237 | * **c)** Convey individual copies of the object code with a copy of the written offer to 238 | provide the Corresponding Source. This alternative is allowed only occasionally and 239 | noncommercially, and only if you received the object code with such an offer, in 240 | accord with subsection 6b. 241 | * **d)** Convey the object code by offering access from a designated place (gratis or for 242 | a charge), and offer equivalent access to the Corresponding Source in the same way 243 | through the same place at no further charge. You need not require recipients to copy 244 | the Corresponding Source along with the object code. If the place to copy the object 245 | code is a network server, the Corresponding Source may be on a different server 246 | (operated by you or a third party) that supports equivalent copying facilities, 247 | provided you maintain clear directions next to the object code saying where to find 248 | the Corresponding Source. Regardless of what server hosts the Corresponding Source, 249 | you remain obligated to ensure that it is available for as long as needed to satisfy 250 | these requirements. 251 | * **e)** Convey the object code using peer-to-peer transmission, provided you inform 252 | other peers where the object code and Corresponding Source of the work are being 253 | offered to the general public at no charge under subsection 6d. 254 | 255 | A separable portion of the object code, whose source code is excluded from the 256 | Corresponding Source as a System Library, need not be included in conveying the 257 | object code work. 258 | 259 | A “User Product” is either **(1)** a “consumer product”, which 260 | means any tangible personal property which is normally used for personal, family, or 261 | household purposes, or **(2)** anything designed or sold for incorporation into a 262 | dwelling. In determining whether a product is a consumer product, doubtful cases 263 | shall be resolved in favor of coverage. For a particular product received by a 264 | particular user, “normally used” refers to a typical or common use of 265 | that class of product, regardless of the status of the particular user or of the way 266 | in which the particular user actually uses, or expects or is expected to use, the 267 | product. A product is a consumer product regardless of whether the product has 268 | substantial commercial, industrial or non-consumer uses, unless such uses represent 269 | the only significant mode of use of the product. 270 | 271 | “Installation Information” for a User Product means any methods, 272 | procedures, authorization keys, or other information required to install and execute 273 | modified versions of a covered work in that User Product from a modified version of 274 | its Corresponding Source. The information must suffice to ensure that the continued 275 | functioning of the modified object code is in no case prevented or interfered with 276 | solely because modification has been made. 277 | 278 | If you convey an object code work under this section in, or with, or specifically for 279 | use in, a User Product, and the conveying occurs as part of a transaction in which 280 | the right of possession and use of the User Product is transferred to the recipient 281 | in perpetuity or for a fixed term (regardless of how the transaction is 282 | characterized), the Corresponding Source conveyed under this section must be 283 | accompanied by the Installation Information. But this requirement does not apply if 284 | neither you nor any third party retains the ability to install modified object code 285 | on the User Product (for example, the work has been installed in ROM). 286 | 287 | The requirement to provide Installation Information does not include a requirement to 288 | continue to provide support service, warranty, or updates for a work that has been 289 | modified or installed by the recipient, or for the User Product in which it has been 290 | modified or installed. Access to a network may be denied when the modification itself 291 | materially and adversely affects the operation of the network or violates the rules 292 | and protocols for communication across the network. 293 | 294 | Corresponding Source conveyed, and Installation Information provided, in accord with 295 | this section must be in a format that is publicly documented (and with an 296 | implementation available to the public in source code form), and must require no 297 | special password or key for unpacking, reading or copying. 298 | 299 | ### 7. Additional Terms 300 | 301 | “Additional permissions” are terms that supplement the terms of this 302 | License by making exceptions from one or more of its conditions. Additional 303 | permissions that are applicable to the entire Program shall be treated as though they 304 | were included in this License, to the extent that they are valid under applicable 305 | law. If additional permissions apply only to part of the Program, that part may be 306 | used separately under those permissions, but the entire Program remains governed by 307 | this License without regard to the additional permissions. 308 | 309 | When you convey a copy of a covered work, you may at your option remove any 310 | additional permissions from that copy, or from any part of it. (Additional 311 | permissions may be written to require their own removal in certain cases when you 312 | modify the work.) You may place additional permissions on material, added by you to a 313 | covered work, for which you have or can give appropriate copyright permission. 314 | 315 | Notwithstanding any other provision of this License, for material you add to a 316 | covered work, you may (if authorized by the copyright holders of that material) 317 | supplement the terms of this License with terms: 318 | 319 | * **a)** Disclaiming warranty or limiting liability differently from the terms of 320 | sections 15 and 16 of this License; or 321 | * **b)** Requiring preservation of specified reasonable legal notices or author 322 | attributions in that material or in the Appropriate Legal Notices displayed by works 323 | containing it; or 324 | * **c)** Prohibiting misrepresentation of the origin of that material, or requiring that 325 | modified versions of such material be marked in reasonable ways as different from the 326 | original version; or 327 | * **d)** Limiting the use for publicity purposes of names of licensors or authors of the 328 | material; or 329 | * **e)** Declining to grant rights under trademark law for use of some trade names, 330 | trademarks, or service marks; or 331 | * **f)** Requiring indemnification of licensors and authors of that material by anyone 332 | who conveys the material (or modified versions of it) with contractual assumptions of 333 | liability to the recipient, for any liability that these contractual assumptions 334 | directly impose on those licensors and authors. 335 | 336 | All other non-permissive additional terms are considered “further 337 | restrictions” within the meaning of section 10. If the Program as you received 338 | it, or any part of it, contains a notice stating that it is governed by this License 339 | along with a term that is a further restriction, you may remove that term. If a 340 | license document contains a further restriction but permits relicensing or conveying 341 | under this License, you may add to a covered work material governed by the terms of 342 | that license document, provided that the further restriction does not survive such 343 | relicensing or conveying. 344 | 345 | If you add terms to a covered work in accord with this section, you must place, in 346 | the relevant source files, a statement of the additional terms that apply to those 347 | files, or a notice indicating where to find the applicable terms. 348 | 349 | Additional terms, permissive or non-permissive, may be stated in the form of a 350 | separately written license, or stated as exceptions; the above requirements apply 351 | either way. 352 | 353 | ### 8. Termination 354 | 355 | You may not propagate or modify a covered work except as expressly provided under 356 | this License. Any attempt otherwise to propagate or modify it is void, and will 357 | automatically terminate your rights under this License (including any patent licenses 358 | granted under the third paragraph of section 11). 359 | 360 | However, if you cease all violation of this License, then your license from a 361 | particular copyright holder is reinstated **(a)** provisionally, unless and until the 362 | copyright holder explicitly and finally terminates your license, and **(b)** permanently, 363 | if the copyright holder fails to notify you of the violation by some reasonable means 364 | prior to 60 days after the cessation. 365 | 366 | Moreover, your license from a particular copyright holder is reinstated permanently 367 | if the copyright holder notifies you of the violation by some reasonable means, this 368 | is the first time you have received notice of violation of this License (for any 369 | work) from that copyright holder, and you cure the violation prior to 30 days after 370 | your receipt of the notice. 371 | 372 | Termination of your rights under this section does not terminate the licenses of 373 | parties who have received copies or rights from you under this License. If your 374 | rights have been terminated and not permanently reinstated, you do not qualify to 375 | receive new licenses for the same material under section 10. 376 | 377 | ### 9. Acceptance Not Required for Having Copies 378 | 379 | You are not required to accept this License in order to receive or run a copy of the 380 | Program. Ancillary propagation of a covered work occurring solely as a consequence of 381 | using peer-to-peer transmission to receive a copy likewise does not require 382 | acceptance. However, nothing other than this License grants you permission to 383 | propagate or modify any covered work. These actions infringe copyright if you do not 384 | accept this License. Therefore, by modifying or propagating a covered work, you 385 | indicate your acceptance of this License to do so. 386 | 387 | ### 10. Automatic Licensing of Downstream Recipients 388 | 389 | Each time you convey a covered work, the recipient automatically receives a license 390 | from the original licensors, to run, modify and propagate that work, subject to this 391 | License. You are not responsible for enforcing compliance by third parties with this 392 | License. 393 | 394 | An “entity transaction” is a transaction transferring control of an 395 | organization, or substantially all assets of one, or subdividing an organization, or 396 | merging organizations. If propagation of a covered work results from an entity 397 | transaction, each party to that transaction who receives a copy of the work also 398 | receives whatever licenses to the work the party's predecessor in interest had or 399 | could give under the previous paragraph, plus a right to possession of the 400 | Corresponding Source of the work from the predecessor in interest, if the predecessor 401 | has it or can get it with reasonable efforts. 402 | 403 | You may not impose any further restrictions on the exercise of the rights granted or 404 | affirmed under this License. For example, you may not impose a license fee, royalty, 405 | or other charge for exercise of rights granted under this License, and you may not 406 | initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging 407 | that any patent claim is infringed by making, using, selling, offering for sale, or 408 | importing the Program or any portion of it. 409 | 410 | ### 11. Patents 411 | 412 | A “contributor” is a copyright holder who authorizes use under this 413 | License of the Program or a work on which the Program is based. The work thus 414 | licensed is called the contributor's “contributor version”. 415 | 416 | A contributor's “essential patent claims” are all patent claims owned or 417 | controlled by the contributor, whether already acquired or hereafter acquired, that 418 | would be infringed by some manner, permitted by this License, of making, using, or 419 | selling its contributor version, but do not include claims that would be infringed 420 | only as a consequence of further modification of the contributor version. For 421 | purposes of this definition, “control” includes the right to grant patent 422 | sublicenses in a manner consistent with the requirements of this License. 423 | 424 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license 425 | under the contributor's essential patent claims, to make, use, sell, offer for sale, 426 | import and otherwise run, modify and propagate the contents of its contributor 427 | version. 428 | 429 | In the following three paragraphs, a “patent license” is any express 430 | agreement or commitment, however denominated, not to enforce a patent (such as an 431 | express permission to practice a patent or covenant not to sue for patent 432 | infringement). To “grant” such a patent license to a party means to make 433 | such an agreement or commitment not to enforce a patent against the party. 434 | 435 | If you convey a covered work, knowingly relying on a patent license, and the 436 | Corresponding Source of the work is not available for anyone to copy, free of charge 437 | and under the terms of this License, through a publicly available network server or 438 | other readily accessible means, then you must either **(1)** cause the Corresponding 439 | Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the 440 | patent license for this particular work, or **(3)** arrange, in a manner consistent with 441 | the requirements of this License, to extend the patent license to downstream 442 | recipients. “Knowingly relying” means you have actual knowledge that, but 443 | for the patent license, your conveying the covered work in a country, or your 444 | recipient's use of the covered work in a country, would infringe one or more 445 | identifiable patents in that country that you have reason to believe are valid. 446 | 447 | If, pursuant to or in connection with a single transaction or arrangement, you 448 | convey, or propagate by procuring conveyance of, a covered work, and grant a patent 449 | license to some of the parties receiving the covered work authorizing them to use, 450 | propagate, modify or convey a specific copy of the covered work, then the patent 451 | license you grant is automatically extended to all recipients of the covered work and 452 | works based on it. 453 | 454 | A patent license is “discriminatory” if it does not include within the 455 | scope of its coverage, prohibits the exercise of, or is conditioned on the 456 | non-exercise of one or more of the rights that are specifically granted under this 457 | License. You may not convey a covered work if you are a party to an arrangement with 458 | a third party that is in the business of distributing software, under which you make 459 | payment to the third party based on the extent of your activity of conveying the 460 | work, and under which the third party grants, to any of the parties who would receive 461 | the covered work from you, a discriminatory patent license **(a)** in connection with 462 | copies of the covered work conveyed by you (or copies made from those copies), or **(b)** 463 | primarily for and in connection with specific products or compilations that contain 464 | the covered work, unless you entered into that arrangement, or that patent license 465 | was granted, prior to 28 March 2007. 466 | 467 | Nothing in this License shall be construed as excluding or limiting any implied 468 | license or other defenses to infringement that may otherwise be available to you 469 | under applicable patent law. 470 | 471 | ### 12. No Surrender of Others' Freedom 472 | 473 | If conditions are imposed on you (whether by court order, agreement or otherwise) 474 | that contradict the conditions of this License, they do not excuse you from the 475 | conditions of this License. If you cannot convey a covered work so as to satisfy 476 | simultaneously your obligations under this License and any other pertinent 477 | obligations, then as a consequence you may not convey it at all. For example, if you 478 | agree to terms that obligate you to collect a royalty for further conveying from 479 | those to whom you convey the Program, the only way you could satisfy both those terms 480 | and this License would be to refrain entirely from conveying the Program. 481 | 482 | ### 13. Use with the GNU Affero General Public License 483 | 484 | Notwithstanding any other provision of this License, you have permission to link or 485 | combine any covered work with a work licensed under version 3 of the GNU Affero 486 | General Public License into a single combined work, and to convey the resulting work. 487 | The terms of this License will continue to apply to the part which is the covered 488 | work, but the special requirements of the GNU Affero General Public License, section 489 | 13, concerning interaction through a network will apply to the combination as such. 490 | 491 | ### 14. Revised Versions of this License 492 | 493 | The Free Software Foundation may publish revised and/or new versions of the GNU 494 | General Public License from time to time. Such new versions will be similar in spirit 495 | to the present version, but may differ in detail to address new problems or concerns. 496 | 497 | Each version is given a distinguishing version number. If the Program specifies that 498 | a certain numbered version of the GNU General Public License “or any later 499 | version” applies to it, you have the option of following the terms and 500 | conditions either of that numbered version or of any later version published by the 501 | Free Software Foundation. If the Program does not specify a version number of the GNU 502 | General Public License, you may choose any version ever published by the Free 503 | Software Foundation. 504 | 505 | If the Program specifies that a proxy can decide which future versions of the GNU 506 | General Public License can be used, that proxy's public statement of acceptance of a 507 | version permanently authorizes you to choose that version for the Program. 508 | 509 | Later license versions may give you additional or different permissions. However, no 510 | additional obligations are imposed on any author or copyright holder as a result of 511 | your choosing to follow a later version. 512 | 513 | ### 15. Disclaimer of Warranty 514 | 515 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 516 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 517 | PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER 518 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 519 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 520 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 521 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 522 | 523 | ### 16. Limitation of Liability 524 | 525 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 526 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 527 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 528 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 529 | PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE 530 | OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE 531 | WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 532 | POSSIBILITY OF SUCH DAMAGES. 533 | 534 | ### 17. Interpretation of Sections 15 and 16 535 | 536 | If the disclaimer of warranty and limitation of liability provided above cannot be 537 | given local legal effect according to their terms, reviewing courts shall apply local 538 | law that most closely approximates an absolute waiver of all civil liability in 539 | connection with the Program, unless a warranty or assumption of liability accompanies 540 | a copy of the Program in return for a fee. 541 | 542 | _END OF TERMS AND CONDITIONS_ 543 | 544 | ## How to Apply These Terms to Your New Programs 545 | 546 | If you develop a new program, and you want it to be of the greatest possible use to 547 | the public, the best way to achieve this is to make it free software which everyone 548 | can redistribute and change under these terms. 549 | 550 | To do so, attach the following notices to the program. It is safest to attach them 551 | to the start of each source file to most effectively state the exclusion of warranty; 552 | and each file should have at least the “copyright” line and a pointer to 553 | where the full notice is found. 554 | 555 | 556 | Copyright (C) 557 | 558 | This program is free software: you can redistribute it and/or modify 559 | it under the terms of the GNU General Public License as published by 560 | the Free Software Foundation, either version 3 of the License, or 561 | (at your option) any later version. 562 | 563 | This program is distributed in the hope that it will be useful, 564 | but WITHOUT ANY WARRANTY; without even the implied warranty of 565 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 566 | GNU General Public License for more details. 567 | 568 | You should have received a copy of the GNU General Public License 569 | along with this program. If not, see . 570 | 571 | Also add information on how to contact you by electronic and paper mail. 572 | 573 | If the program does terminal interaction, make it output a short notice like this 574 | when it starts in an interactive mode: 575 | 576 | Copyright (C) 577 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. 578 | This is free software, and you are welcome to redistribute it 579 | under certain conditions; type 'show c' for details. 580 | 581 | The hypothetical commands `show w` and `show c` should show the appropriate parts of 582 | the General Public License. Of course, your program's commands might be different; 583 | for a GUI interface, you would use an “about box”. 584 | 585 | You should also get your employer (if you work as a programmer) or school, if any, to 586 | sign a “copyright disclaimer” for the program, if necessary. For more 587 | information on this, and how to apply and follow the GNU GPL, see 588 | <>. 589 | 590 | The GNU General Public License does not permit incorporating your program into 591 | proprietary programs. If your program is a subroutine library, you may consider it 592 | more useful to permit linking proprietary applications with the library. If this is 593 | what you want to do, use the GNU Lesser General Public License instead of this 594 | License. But first, please read 595 | <>. 596 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | S3method(forecast,ARml) 4 | S3method(predict,conformalRegressor) 5 | S3method(residuals,ARml) 6 | export("%<>%") 7 | export("%>%") 8 | export(ARml) 9 | export(accuracy) 10 | export(autolayer) 11 | export(autoplot) 12 | export(conformalRegressor) 13 | export(forecast) 14 | export(get_var_imp) 15 | export(split_ts) 16 | export(suggested_methods) 17 | importFrom(caret,train) 18 | importFrom(caret,trainControl) 19 | importFrom(caret,varImp) 20 | importFrom(dplyr,bind_cols) 21 | importFrom(forecast,BoxCox) 22 | importFrom(forecast,BoxCox.lambda) 23 | importFrom(forecast,InvBoxCox) 24 | importFrom(forecast,autolayer) 25 | importFrom(forecast,autoplot) 26 | importFrom(forecast,fourier) 27 | importFrom(forecast,is.constant) 28 | importFrom(forecast,na.interp) 29 | importFrom(generics,accuracy) 30 | importFrom(generics,forecast) 31 | importFrom(magrittr,"%<>%") 32 | importFrom(magrittr,"%>%") 33 | importFrom(methods,is) 34 | importFrom(stats,"tsp<-") 35 | importFrom(stats,frequency) 36 | importFrom(stats,is.ts) 37 | importFrom(stats,predict) 38 | importFrom(stats,residuals) 39 | importFrom(stats,sd) 40 | importFrom(stats,start) 41 | importFrom(stats,time) 42 | importFrom(stats,ts) 43 | importFrom(stats,tsp) 44 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | # caretForecast 0.1.1 2 | 3 | # caretForecast 0.0.3 4 | 5 | # caretForecast 0.0.2 6 | 7 | * Added a `NEWS.md` file to track changes to the package. 8 | -------------------------------------------------------------------------------- /R/arml.R: -------------------------------------------------------------------------------- 1 | #' Autoregressive forecasting using various Machine Learning models. 2 | #' 3 | #' @importFrom methods is 4 | #' @importFrom stats frequency is.ts predict sd start time ts 5 | #' @importFrom forecast is.constant na.interp BoxCox.lambda BoxCox InvBoxCox 6 | #' @importFrom caret train trainControl 7 | #' @param y A univariate time series object. 8 | #' @param xreg Optional. A numerical vector or matrix of external regressors, 9 | #' which must have the same number of rows as y. 10 | #' (It should not be a data frame.). 11 | #' @param max_lag Maximum value of lag. 12 | #' @param caret_method A string specifying which classification or 13 | #' regression model to use. 14 | #' Possible values are found using names(getModelInfo()). 15 | #' A list of functions can also be passed for a custom model function. 16 | #' See \url{http://topepo.github.io/caret/} for details. 17 | #' @param metric A string that specifies what summary metric will be used to 18 | #' select the optimal model. See \code{?caret::train}. 19 | #' @param pre_process A string vector that defines a pre-processing of the 20 | #' predictor data. 21 | #' Current possibilities are "BoxCox", "YeoJohnson", "expoTrans", "center", 22 | #' "scale", "range", 23 | #' "knnImpute", "bagImpute", "medianImpute", "pca", "ica" and "spatialSign". 24 | #' The default is no pre-processing. 25 | #' See preProcess and trainControl on the procedures and how to adjust them. 26 | #' Pre-processing code is only designed to work when x is a simple matrix or 27 | #' data frame. 28 | #' @param cv Logical, if \code{cv = TRUE} model selection will be done via 29 | #' cross-validation. If \code{cv = FALSE} user need to provide a specific model 30 | #' via \code{tune_grid} argument. 31 | #' @param cv_horizon The number of consecutive values in test set sample. 32 | #' @param initial_window The initial number of consecutive values in each 33 | #' training set sample. 34 | #' @param fixed_window Logical, if FALSE, all training samples start at 1. 35 | #' @param verbose A logical for printing a training log. 36 | #' @param seasonal Boolean. If \code{seasonal = TRUE} the fourier terms will be 37 | #' used for modeling seasonality. 38 | #' @param K Maximum order(s) of Fourier terms 39 | #' @param tune_grid A data frame with possible tuning values. 40 | #' The columns are named the same as the tuning parameters. 41 | #' Use getModelInfo to get a list of tuning parameters for each model or 42 | #' see \url{http://topepo.github.io/caret/available-models.html}. 43 | #' (NOTE: If given, this argument must be named.) 44 | #' @param lambda BoxCox transformation parameter. If \code{lambda = NULL} 45 | #' If \code{lambda = "auto"}, then the transformation parameter lambda is chosen 46 | #' using \code{\link[forecast]{BoxCox.lambda}}. 47 | #' @param BoxCox_method \code{\link[forecast]{BoxCox.lambda}} argument. 48 | #' Choose method to be used in calculating lambda. 49 | #' @param BoxCox_lower \code{\link[forecast]{BoxCox.lambda}} argument. 50 | #' Lower limit for possible lambda values. 51 | #' @param BoxCox_upper \code{\link[forecast]{BoxCox.lambda}} argument. 52 | #' Upper limit for possible lambda values. 53 | #' @param BoxCox_biasadj \code{\link[forecast]{InvBoxCox}} argument. 54 | #' Use adjusted back-transformed mean for Box-Cox transformations. 55 | #' If transformed data is used to produce forecasts and fitted values, 56 | #' a regular back transformation will result in median forecasts. 57 | #' If biasadj is TRUE, an adjustment will be made to produce mean 58 | #' forecasts and fitted values. 59 | #' @param BoxCox_fvar \code{\link[forecast]{InvBoxCox}} argument. 60 | #' Optional parameter required if biasadj=TRUE. 61 | #' Can either be the forecast variance, or a list containing the interval level, 62 | #' and the corresponding upper and lower intervals. 63 | #' @param allow_parallel If a parallel backend is loaded and available, 64 | #' should the function use it? 65 | #' @param ... Ignored. 66 | #' @return A list class of forecast containing the following elemets 67 | #' * x : The input time series 68 | #' * method : The name of the forecasting method as a character string 69 | #' * mean : Point forecasts as a time series 70 | #' * lower : Lower limits for prediction intervals 71 | #' * upper : Upper limits for prediction intervals 72 | #' * level : The confidence values associated with the prediction intervals 73 | #' * model : A list containing information about the fitted model 74 | #' * newx : A matrix containing regressors 75 | #' @author Resul Akay 76 | #' 77 | #' @examples 78 | #' 79 | #'library(caretForecast) 80 | #' 81 | #'train_data <- window(AirPassengers, end = c(1959, 12)) 82 | #' 83 | #'test <- window(AirPassengers, start = c(1960, 1)) 84 | #' 85 | #'ARml(train_data, caret_method = "lm", max_lag = 12) -> fit 86 | #' 87 | #'forecast(fit, h = length(test)) -> fc 88 | #' 89 | #'autoplot(fc) + autolayer(test) 90 | #' 91 | #'accuracy(fc, test) 92 | #' 93 | #' @export 94 | 95 | ARml <- function(y, 96 | max_lag = 5, 97 | xreg = NULL, 98 | caret_method = "cubist", 99 | metric = "RMSE", 100 | pre_process = NULL, 101 | cv = TRUE, 102 | cv_horizon = 4, 103 | initial_window = NULL, 104 | fixed_window = FALSE, 105 | verbose = TRUE, 106 | seasonal = TRUE, 107 | K = frequency(y) / 2, 108 | tune_grid = NULL, 109 | lambda = NULL, 110 | BoxCox_method = c("guerrero", "loglik"), 111 | BoxCox_lower = -1, 112 | BoxCox_upper = 2, 113 | BoxCox_biasadj = FALSE, 114 | BoxCox_fvar = NULL, 115 | allow_parallel = FALSE, 116 | ...) { 117 | 118 | if ("ts" %notin% class(y)) { 119 | stop("y must be a univariate time series") 120 | } 121 | freq <- stats::frequency(y) 122 | length_y <- length(y) 123 | 124 | if (c(length_y - freq - round(freq / 4)) < max_lag) { 125 | if(length_y > 3){ 126 | max_lag <- length_y + 3 - length_y 127 | } else { 128 | max_lag <- 1 129 | } 130 | if(max_lag >= length_y - max_lag - 2){ 131 | max_lag <- 1 132 | } 133 | 134 | warning(paste("Input data is too short. setting max_lag = ", max_lag)) 135 | } 136 | 137 | if (length_y < 3) { 138 | stop("Not enough data to fit a model") 139 | } 140 | constant_data <- is.constant(na.interp(y)) 141 | if (constant_data) { 142 | warning("Constant data, setting max_lag = 1, seasonal = FALSE, lambda = NULL, 143 | pre_process = NULL") 144 | pre_process <- NULL 145 | lambda <- NULL 146 | max_lag <- 1 147 | } 148 | 149 | if (!is.null(xreg)) { 150 | constant_xreg <- any(apply(as.matrix(xreg), 2, 151 | function(x) { 152 | is.constant(na.interp(x)) 153 | } 154 | ) 155 | ) 156 | if (constant_xreg) { 157 | warning("Constant xreg column, setting pre_process=NULL") 158 | pre_process <- NULL 159 | } 160 | } 161 | 162 | if (max_lag <= 0) { 163 | warning("max_lag increased to 1. max_lag must be max_lag >= 1") 164 | max_lag <- 1 165 | } 166 | 167 | 168 | if (max_lag != round(max_lag)) { 169 | max_lag <- round(max_lag) 170 | message(paste("max_lag must be an integer, max_lag rounded to", max_lag)) 171 | } 172 | 173 | if (!is.null(xreg)) { 174 | if ("matrix" %notin% class(xreg)) { 175 | xreg <- as.matrix(xreg) 176 | } 177 | } 178 | 179 | if (!is.null(xreg)) 180 | { 181 | ncolxreg <- ncol(xreg) 182 | } 183 | 184 | if (is.null(lambda)) { 185 | modified_y <- y 186 | } 187 | if (!is.null(lambda)) { 188 | if (lambda == "auto") { 189 | lambda <- forecast::BoxCox.lambda(y, 190 | method = BoxCox_method, 191 | lower = BoxCox_lower, 192 | upper = BoxCox_upper) 193 | modified_y <- forecast::BoxCox(y, lambda) 194 | } 195 | 196 | if (is.numeric(lambda)) { 197 | modified_y <- forecast::BoxCox(y, lambda) 198 | } 199 | } 200 | 201 | modified_y_2 <- ts(modified_y[-seq_len(max_lag)], 202 | start = time(modified_y)[max_lag + 1], 203 | frequency = freq) 204 | 205 | if(length_y - max_lag < freq + 1) { 206 | seasonal <- FALSE 207 | } 208 | 209 | if (seasonal == TRUE & freq > 1) 210 | { 211 | if (K == freq / 2) { 212 | ncolx <- max_lag + K * 2 - 1 213 | } else { 214 | ncolx <- max_lag + K * 2 215 | } 216 | } 217 | if (seasonal == FALSE | freq == 1) 218 | { 219 | ncolx <- max_lag 220 | } 221 | 222 | x <- matrix(0, nrow = c(length_y - max_lag), ncol = ncolx) 223 | 224 | x[, seq_len(max_lag)] <- lag_maker(modified_y, max_lag) 225 | 226 | if (seasonal == TRUE & freq > 1) 227 | { 228 | fourier_s <- fourier(modified_y_2, K = K) 229 | x[, (max_lag + 1):ncolx] <- fourier_s 230 | colnames(x) <- c(paste0("lag", 1:max_lag), colnames(fourier_s)) 231 | } 232 | 233 | if (seasonal == FALSE | freq == 1) 234 | { 235 | colnames(x) <- c(paste0("lag", 1:max_lag)) 236 | } 237 | 238 | if (!is.null(xreg)) { 239 | col_xreg <- ncol(xreg) 240 | name_xreg <- colnames(xreg) 241 | xreg <- xreg[-seq_len(max_lag),] 242 | if (col_xreg == 1) { 243 | xreg <- as.matrix(matrix(xreg, ncol = 1)) 244 | colnames(xreg)[1] <- name_xreg[1] 245 | rm(name_xreg, col_xreg) 246 | } 247 | x <- cbind(x, xreg) 248 | } 249 | 250 | training_method <- "timeslice" 251 | 252 | if (!cv) { 253 | training_method <- "none" 254 | if (is.null(tune_grid)) { 255 | stop("Only one model should be specified in tune_grid with no resampling") 256 | } 257 | } 258 | 259 | initial_window_setted <- FALSE 260 | if(is.null(initial_window)){ 261 | initial_window <- length_y - max_lag - cv_horizon * 2 262 | message("initial_window = NULL. Setting initial_window = ", initial_window) 263 | initial_window_setted <- TRUE 264 | } 265 | if(initial_window<1 | initial_window >= nrow(x)){ 266 | initial_window <- length_y - max_lag - 1 267 | cv_horizon <- 1 268 | if(initial_window_setted){ 269 | warning("Resetting initial_window = ", initial_window, " cv_horizon = 1") 270 | } else { 271 | warning("Setting initial_window = ", initial_window, " cv_horizon = 1") 272 | } 273 | } 274 | 275 | model <- caret::train( 276 | x = x, 277 | y = as.numeric(modified_y_2), 278 | method = caret_method, 279 | preProcess = pre_process, 280 | weights = NULL, 281 | metric = metric, 282 | trControl = caret::trainControl( 283 | method = training_method, 284 | initialWindow = initial_window, 285 | horizon = cv_horizon, 286 | fixedWindow = fixed_window, 287 | verboseIter = verbose, 288 | allowParallel = allow_parallel, 289 | returnData = TRUE, 290 | returnResamp = "final", 291 | savePredictions = "final" 292 | ), 293 | tuneGrid = tune_grid 294 | ) 295 | 296 | fitted <- ts(c(rep(NA, max_lag), 297 | predict(model, newdata = x)), 298 | frequency = freq, 299 | start = min(time(modified_y))) 300 | 301 | if (!is.null(lambda)) { 302 | fitted <- forecast::InvBoxCox(fitted, 303 | lambda = lambda, 304 | biasadj = BoxCox_biasadj, 305 | fvar = BoxCox_fvar) 306 | } 307 | 308 | K_m <- 0 309 | 310 | if (seasonal == TRUE & freq > 1) 311 | { 312 | K_m <- K 313 | } 314 | 315 | method <- paste0("ARml(", max_lag, paste(", ", K_m), ")") 316 | 317 | output <- list( 318 | y = y, 319 | y_modified = modified_y_2, 320 | x = x, 321 | model = model, 322 | fitted = fitted, 323 | max_lag = max_lag, 324 | lambda = lambda, 325 | seasonal = seasonal, 326 | BoxCox_biasadj = BoxCox_biasadj, 327 | BoxCox_fvar = BoxCox_fvar, 328 | method = paste0("caret method ", caret_method, " with ", method) 329 | ) 330 | 331 | if (seasonal == TRUE & freq > 1) 332 | { 333 | output$fourier_s <- fourier_s 334 | output$K <- K 335 | } 336 | output$xreg_fit <- NULL 337 | if (!is.null(xreg)) { 338 | output$xreg_fit <- xreg 339 | } 340 | class(output) <- "ARml" 341 | return(output) 342 | } 343 | -------------------------------------------------------------------------------- /R/fit_conformal_reg.R: -------------------------------------------------------------------------------- 1 | #' Fit a conformal regressor. 2 | #' 3 | #' @param residuals Model residuals. 4 | #' @param sigmas A vector of difficulty estimates 5 | #' @author Resul Akay 6 | #' @return A conformalRegressor object 7 | #' 8 | #' @references 9 | #' Boström, H., 2022. crepes: a Python Package for Generating Conformal 10 | #' Regressors and Predictive Systems. In Conformal and Probabilistic Prediction 11 | #' and Applications. PMLR, 179. 12 | #' \url{https://copa-conference.com/papers/COPA2022_paper_11.pdf} 13 | #' 14 | #' @export 15 | conformalRegressor <- function(residuals, sigmas=NULL) { 16 | abs_residuals <- abs(residuals) 17 | if(is.null(sigmas)){ 18 | normalized <- FALSE 19 | alphas <- rev(sort(abs_residuals)) 20 | } else { 21 | normalized <- TRUE 22 | alphas = rev(sort(abs_residuals/sigmas)) 23 | } 24 | out <- list( 25 | alphas = alphas, 26 | normalized = normalized 27 | ) 28 | out <- structure(out, class = "conformalRegressor") 29 | return(out) 30 | } 31 | -------------------------------------------------------------------------------- /R/forecast.R: -------------------------------------------------------------------------------- 1 | #' @importFrom generics forecast 2 | #' @export 3 | generics::forecast 4 | 5 | #' @title Forecasting using ARml model 6 | #' 7 | #' @param object An object of class "ARml", the result of a call to ARml. 8 | #' @param h forecast horizon 9 | #' @param xreg Optionally, a numerical vector or matrix of future external 10 | #' regressors 11 | #' @param level Confidence level for prediction intervals. 12 | #' 13 | #' @param ... Ignored 14 | #' @return A list class of forecast containing the following elemets 15 | #' * x : The input time series 16 | #' * method : The name of the forecasting method as a character string 17 | #' * mean : Point forecasts as a time series 18 | #' * lower : Lower limits for prediction intervals 19 | #' * upper : Upper limits for prediction intervals 20 | #' * level : The confidence values associated with the prediction intervals 21 | #' * model : A list containing information about the fitted model 22 | #' * newxreg : A matrix containing regressors 23 | #' @author Resul Akay 24 | #' 25 | #' @examples 26 | #' 27 | #'library(caretForecast) 28 | #' 29 | #'train_data <- window(AirPassengers, end = c(1959, 12)) 30 | #' 31 | #'test <- window(AirPassengers, start = c(1960, 1)) 32 | #' 33 | #'ARml(train_data, caret_method = "lm", max_lag = 12) -> fit 34 | #' 35 | #'forecast(fit, h = length(test), level = c(80,95)) -> fc 36 | #' 37 | #'autoplot(fc)+ autolayer(test) 38 | #' 39 | #'accuracy(fc, test) 40 | #' @importFrom stats residuals tsp tsp<- 41 | #' @export 42 | forecast.ARml <- function(object, 43 | h = frequency(object$y), 44 | xreg = NULL, 45 | level = c(80, 95), 46 | ...) { 47 | 48 | if (!is.null(object$xreg_fit)) { 49 | ncolxreg <- ncol(object$xreg_fit) 50 | } 51 | 52 | if (is.null(xreg)) { 53 | if (!is.null(object$xreg_fit)) { 54 | stop("No regressors provided") 55 | } 56 | } 57 | 58 | if (!is.null(xreg)) { 59 | if (is.null(object$xreg_fit)) { 60 | stop("No regressors provided to fitted model") 61 | } 62 | 63 | if (ncol(xreg) != ncolxreg) { 64 | stop("Number of regressors does not match to fitted model") 65 | } 66 | 67 | h <- nrow(xreg) 68 | newxreg1 <- xreg 69 | } 70 | 71 | if (is.null(h)) { 72 | h <- ifelse(frequency(object$y) > 1, 2 * frequency(object$y), 10) 73 | } 74 | 75 | if (is.null(xreg)) { 76 | newxreg1 <- NULL 77 | } 78 | 79 | lambda <- object$lambda 80 | BoxCox_biasadj <- object$BoxCox_biasadj 81 | BoxCox_fvar <- object$BoxCox_fvar 82 | 83 | fc_x <- forecast_loop(object = object, xreg = newxreg1, h = h) 84 | x <- fc_x$x 85 | y <- fc_x$y 86 | 87 | if (!is.null(lambda)) { 88 | y <- forecast::InvBoxCox(y, lambda = lambda, biasadj = BoxCox_biasadj, 89 | fvar = BoxCox_fvar) 90 | } 91 | 92 | res <- tryCatch({ 93 | residuals(object) 94 | }, error = function(err){ 95 | out <- NULL 96 | return(out) 97 | }) 98 | 99 | if(is.null(res)){ 100 | lower <- NULL 101 | upper <- NULL 102 | } else { 103 | intervals <- tryCatch({ 104 | conformal_intervals(residuals = res, y_hat = y, level = level) 105 | }, error = function(err) { 106 | NULL 107 | }) 108 | if(is.null(intervals)){ 109 | lower <- NULL 110 | upper <- NULL 111 | warning("I could not derive conformal prediction intervals") 112 | } else { 113 | lower <- intervals[["lower"]] 114 | upper<- intervals[["upper"]] 115 | } 116 | } 117 | 118 | output <- list( 119 | x = object$y, 120 | mean = y, 121 | lower = lower, 122 | upper = upper, 123 | fitted = object$fitted, 124 | level = level, 125 | newxreg = x, 126 | method = object$method, 127 | model = object$model 128 | ) 129 | class(output) <- c("forecast", "forecastARml") 130 | return(output) 131 | } 132 | -------------------------------------------------------------------------------- /R/predict_conformal.R: -------------------------------------------------------------------------------- 1 | predict_default <- function(object, y_hat, sigmas, confidence, y_min, y_max){ 2 | 3 | if(length(confidence) >1){ 4 | confidence <- confidence[1] 5 | warning("Only fist element of confidence considered") 6 | } 7 | 8 | if(!all(c(confidence <=1 & confidence>=0))){ 9 | stop("confidence must be in the interval '0<=confidence<=1' ") 10 | } 11 | 12 | intervals <- matrix(nrow = length(y_hat), ncol = 2) 13 | alpha_index <- ceiling((1-confidence) * (length(object[["alphas"]]) + 1)) 14 | if(alpha_index >= 0) { 15 | alpha <- object[["alphas"]][alpha_index] 16 | if(object[["normalized"]]){ 17 | intervals[,1] <- y_hat-alpha*sigmas 18 | intervals[,2] <- y_hat+alpha*sigmas 19 | } else { 20 | intervals[,1] <- y_hat-alpha 21 | intervals[,2] <- y_hat+alpha 22 | } 23 | } else { 24 | intervals[,1] <- -Inf 25 | intervals[,2] <- Inf 26 | } 27 | if(y_min > - Inf) { 28 | intervals[intervalsy_max] = y_max 32 | } 33 | return(intervals) 34 | } 35 | 36 | #' Predict a conformalRegressor 37 | #' @param object A conformalRegressor object 38 | #' @param y_hat Predicted values 39 | #' @param sigmas Difficulty estimates 40 | #' @param confidence Confidence level 41 | #' @param y_min The minimum value to include in prediction intervals 42 | #' @param y_max The maximum value to include in prediction intervals 43 | #' @param ... Ignored 44 | #' @author Resul Akay 45 | #' @return Prediction intervals 46 | #' @importFrom stats predict 47 | #' @importFrom dplyr bind_cols 48 | #' @export 49 | predict.conformalRegressor <- function(object, y_hat = NULL, sigmas = NULL, 50 | confidence = 0.95, y_min = - Inf, 51 | y_max = Inf, ...){ 52 | if(!is.null(y_hat)){ 53 | if(!is.numeric(y_hat)){ 54 | stop("y_hat must be a numeric vector") 55 | } 56 | } 57 | 58 | if(!is.null(sigmas)){ 59 | if(!is.numeric(sigmas)){ 60 | stop("sigmas must be a numeric vector") 61 | } 62 | } 63 | 64 | if(length(y_min)>1){ 65 | warning("Only the first element of y_min considered") 66 | y_min <- y_min[1] 67 | } 68 | 69 | if(!is.numeric(y_min)){ 70 | stop("y_min must be a numeric vector") 71 | } 72 | 73 | if(length(y_max)>1){ 74 | warning("Only the first element of y_max considered") 75 | y_max <- y_max[1] 76 | } 77 | 78 | if(!is.numeric(y_max)){ 79 | stop("y_max must be a numeric vector") 80 | } 81 | 82 | intervals <- sapply(X = confidence, 83 | FUN = function(x, .object, .y_hat, .sigmas, .y_min, 84 | .y_max) { 85 | 86 | pred <- predict_default(object = .object, 87 | y_hat = .y_hat, 88 | sigmas = .sigmas, 89 | confidence = x, 90 | y_min = .y_min, 91 | y_max = .y_max) 92 | pred <- as.data.frame(pred) 93 | colnames(pred) <- paste0(c("lower_", "upper_"), x*100) 94 | return(pred) 95 | }, 96 | .object = object, 97 | .y_hat = y_hat, 98 | .sigmas = sigmas, 99 | .y_min = y_min, 100 | .y_max = y_max, 101 | simplify = FALSE 102 | ) 103 | intervals <- dplyr::bind_cols(intervals) 104 | return(intervals) 105 | } 106 | -------------------------------------------------------------------------------- /R/utils.R: -------------------------------------------------------------------------------- 1 | #' @importFrom forecast fourier 2 | #' @importFrom caret varImp 3 | pred_func <- function(i, x, y, newxreg, object, freq, fourier_h) { 4 | newxreg_in <- newxreg[i,] 5 | new_data <- c(y[length(y)], x[nrow(x), 1:(object$max_lag - 1)]) 6 | if (object$max_lag == 1) { 7 | new_data = new_data[-2] 8 | } 9 | if (object$seasonal == TRUE & freq > 1) 10 | { 11 | new_data <- c(new_data, fourier_h[i, ]) 12 | } 13 | if (!is.null(newxreg_in)) { 14 | new_data <- c(new_data, newxreg_in) 15 | } 16 | new_data <- matrix(new_data, nrow = 1) 17 | colnames(new_data) <- colnames(x) 18 | pred <- predict(object$model, newdata = new_data) 19 | return(list("x" = rbind(x, new_data), 20 | "y" = c(y, pred))) 21 | } 22 | 23 | forecast_loop <- function(object, xreg, h) { 24 | x <- object$x 25 | y <- object$y_modified 26 | freq <- stats::frequency(object$y_modified) 27 | if (object$seasonal == TRUE & freq > 1) 28 | { 29 | fourier_h <- 30 | forecast::fourier(object$y_modified, K = object$K, h = h) 31 | } 32 | for (i in 1:h) { 33 | fc_x <- pred_func( 34 | i, 35 | x = x, 36 | y = y, 37 | newxreg = xreg, 38 | object = object, 39 | freq = freq, 40 | fourier_h = fourier_h 41 | ) 42 | x <- fc_x$x 43 | y <- fc_x$y 44 | } 45 | y <- ts(y[-(1:length(object$y_modified))], 46 | frequency = freq, 47 | start = max(time(object$y)) + 1 / freq) 48 | x <- x[-(1:nrow(object$x)),] 49 | 50 | return(list("x" = x, 51 | "y" = y)) 52 | } 53 | 54 | #' @title Variable importance for forecasting model. 55 | #' 56 | #' @param object A list class of ARml or forecast object derived from ARml 57 | #' @param plot Boolean, if TRUE, variable importance will be ploted. 58 | #' @return A list class of "varImp.train". See \code{\link[caret]{varImp}} or a 59 | #' "trellis" plot. 60 | #' @author Resul Akay 61 | #' @examples 62 | #' 63 | #' train <- window(AirPassengers, end = c(1959, 12)) 64 | #' 65 | #' test <- window(AirPassengers, start = c(1960, 1)) 66 | #' 67 | #' ARml(train, caret_method = "lm", max_lag = 12, trend_method = "none", 68 | #' pre_process = "center") -> fit 69 | #' 70 | #' forecast(fit, h = length(test), level = c(80,95)) -> fc 71 | #' 72 | #' autoplot(fc)+ autolayer(test) 73 | #' 74 | #' accuracy(fc, test) 75 | #' 76 | #' get_var_imp(fc, plot = TRUE) 77 | #' 78 | #' 79 | #' @export 80 | 81 | get_var_imp <- function(object, plot = TRUE) { 82 | if ("forecastARml" %notin% class(object)) { 83 | stop("object must be an forecastARml or ARml object") 84 | } 85 | if (plot) { 86 | return(plot(varImp(object$model))) 87 | } 88 | if (!plot) { 89 | return(varImp(object$model)) 90 | } 91 | } 92 | 93 | lag_maker <- function(y, max_lag) { 94 | if ("ts" %notin% class(y)) { 95 | stop("y must be a 'ts' object") 96 | } 97 | 98 | max_lag1 <- round(max_lag) 99 | if (max_lag1 != max_lag) { 100 | message( 101 | paste( 102 | "'max_lag' should not be a fractional number.", 103 | "'max_lag' rounde to", 104 | max_lag1, 105 | sep = " " 106 | ) 107 | ) 108 | } 109 | length_y <- length(y) 110 | n_col <- max_lag1 + 1 111 | dta <- apply( 112 | array(seq( 113 | from = 1, to = n_col, by = 1 114 | )), 115 | 1, 116 | FUN = function(i) { 117 | y[(max_lag1 + 2 - i):(length_y + 1 - i)] 118 | } 119 | ) 120 | 121 | colnames(dta) <- 122 | c("y", paste0("y_lag", seq( 123 | from = 1, to = max_lag1, by = 1 124 | ))) 125 | 126 | dta <- dta[,-1] 127 | 128 | return(dta) 129 | } 130 | 131 | `%notin%` <- Negate(`%in%`) 132 | 133 | #' Sales data from an Australian Retailer in time series format 134 | #' 135 | #' A dataset containing 42 products' sales 136 | #' 137 | #' @format 138 | #' An object of class mts (inherits from ts, matrix) 139 | #' with 333 rows and 43 columns. 140 | #' \describe{ 141 | #' This data set is the wide format of \code{\link{retail}} data. 142 | #' } 143 | #' @source \url{https://robjhyndman.com/data/ausretail.csv} 144 | "retail_wide" 145 | 146 | #' Grouped sales data from an Australian Retailer 147 | #' 148 | #' A dataset containing 42 products' sales 149 | #' 150 | #' @format A data class of "tbl_df", "tbl", "data.frame" with 13986 rows and 3 columns: 151 | #' \describe{ 152 | #' \item{date}{date} 153 | #' \item{item}{products} 154 | #' \item{value}{sales} 155 | #' } 156 | #' @source \url{https://robjhyndman.com/data/ausretail.csv} 157 | "retail" 158 | 159 | #' @title Split a time series into training and testing sets 160 | #' @importFrom stats ts start frequency 161 | #' @param y A univariate time series 162 | #' @param test_size The number of observations to keep in the test set 163 | #' @return 164 | #' A list with train and test elements 165 | #' @author Resul Akay 166 | #' @examples 167 | #' 168 | #' dlist <- split_ts(retail_wide[,1], test_size = 12) 169 | #' 170 | #'@export 171 | split_ts <- function (y, test_size = 10) { 172 | if ("ts" %notin% class(y) | "mts" %in% class(y)) { 173 | stop("y must be a univariate time series class of 'ts'") 174 | } 175 | num_train <- length(y) - test_size 176 | train_start <- stats::start(y) 177 | freq <- stats::frequency(y) 178 | test_start <- min(time(y)) + num_train / freq 179 | train = stats::ts(y[1:num_train], start = train_start, frequency = freq) 180 | test = stats::ts(y[(num_train + 1):length(y)], start = test_start, 181 | frequency = freq) 182 | output <- list("train" = train, "test" = test) 183 | return(output) 184 | } 185 | 186 | #' @title Suggested methods for ARml 187 | #' @return A character vector of Suggested methods 188 | #' @author Resul Akay 189 | #' @examples 190 | #' 191 | #' suggested_methods() 192 | #' 193 | #' @export 194 | suggested_methods <- function() { 195 | message("In general user can train any method which supported by caret. 196 | \nThe following methods are suggested" 197 | ) 198 | caret_methods <- c("spikeslab", "bagEarth", "bagEarthGCV", "blasso", 199 | "cforest", "earth","extraTrees", "gbm_h2o", "glmStepAIC", 200 | "parRF", "qrf", "Rborist", "rf", "rqlasso", "rqnc", 201 | "spikeslab", "xgbDART", "xgbLinear", "ranger", "cubist", 202 | "svmLinear", "enet", "bridge", "glmboost", "ridge", 203 | "lasso", "relaxo", "M5Rules", "M5", "lm", "gaussprLinear", 204 | "glm", "glmnet", "pcr", "ppr", "foba", "gbm", "svmLinear2", 205 | "glm.nb", "gcvEarth", "lars2", "lars", "icr", "ctree2", 206 | "ctree", "bayesglm") 207 | 208 | return(caret_methods) 209 | } 210 | 211 | #' @export 212 | residuals.ARml <- function(object, ...){ 213 | res <- object$y - object$fitted 214 | return(res) 215 | } 216 | 217 | conformal_intervals <- function(residuals, y_hat, level){ 218 | level <- c(level/100) 219 | conf_reg <- conformalRegressor(residuals) 220 | conf_pred <- predict(conf_reg, y_hat = y_hat, confidence = level) 221 | upper <- ts(dplyr::select(conf_pred, dplyr::starts_with("upper_"))) 222 | tsp(upper) <- tsp(y_hat) 223 | lower <- ts(dplyr::select(conf_pred, dplyr::starts_with("lower_"))) 224 | tsp(lower) <- tsp(y_hat) 225 | out <- list(upper = upper, lower = lower) 226 | return(out) 227 | } 228 | 229 | #' @importFrom forecast autoplot 230 | #' @export 231 | forecast::autoplot 232 | 233 | #' @importFrom forecast autolayer 234 | #' @export 235 | forecast::autolayer 236 | 237 | #' @importFrom generics accuracy 238 | #' @export 239 | generics::accuracy 240 | 241 | #' @importFrom magrittr %>% 242 | #' @export 243 | magrittr::`%>%` 244 | 245 | #' @importFrom magrittr %<>% 246 | #' @export 247 | magrittr::`%<>%` 248 | -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | output: github_document 3 | --- 4 | 5 | 6 | 7 | ```{r, include = FALSE} 8 | knitr::opts_chunk$set( 9 | collapse = TRUE, 10 | comment = "#>", 11 | fig.path = "man/figures/README-", 12 | out.width = "100%" 13 | ) 14 | ``` 15 | 16 | # caretForecast 17 | 18 | 19 | 20 | 21 | 22 | 23 | caretForecast aspires to equip users with the means of using machine learning algorithms for time series data forecasting. 24 | 25 | ## Installation 26 | 27 | The CRAN version with: 28 | 29 | ``` r 30 | install.packages("caretForecast") 31 | 32 | ``` 33 | 34 | 35 | The development version from [GitHub](https://github.com/) with: 36 | 37 | ``` r 38 | # install.packages("devtools") 39 | devtools::install_github("Akai01/caretForecast") 40 | ``` 41 | ## Example 42 | 43 | By using caretForecast, users can train any regression model that is compatible with the caret package. This allows them to use any machine learning model they need in order to solve specific problems, as shown by the examples below. 44 | 45 | 46 | ### Load the library 47 | 48 | ```{r example1} 49 | library(caretForecast) 50 | 51 | data(retail_wide, package = "caretForecast") 52 | 53 | ``` 54 | 55 | ### Forecasting with glmboost 56 | ```{r, example2} 57 | i <- 8 58 | 59 | dtlist <- caretForecast::split_ts(retail_wide[,i], test_size = 12) 60 | 61 | training_data <- dtlist$train 62 | 63 | testing_data <- dtlist$test 64 | 65 | fit <- ARml(training_data, max_lag = 12, caret_method = "glmboost", 66 | verbose = FALSE) 67 | 68 | forecast(fit, h = length(testing_data), level = c(80,95))-> fc 69 | 70 | accuracy(fc, testing_data) 71 | 72 | 73 | autoplot(fc) + 74 | autolayer(testing_data, series = "testing_data") 75 | 76 | ``` 77 | 78 | ### Forecasting with cubist regression 79 | 80 | ```{r, example3} 81 | i <- 9 82 | 83 | dtlist <- caretForecast::split_ts(retail_wide[,i], test_size = 12) 84 | 85 | training_data <- dtlist$train 86 | 87 | testing_data <- dtlist$test 88 | 89 | fit <- ARml(training_data, max_lag = 12, caret_method = "cubist", 90 | verbose = FALSE) 91 | 92 | forecast(fit, h = length(testing_data), level = c(80,95), PI = TRUE)-> fc 93 | 94 | accuracy(fc, testing_data) 95 | 96 | autoplot(fc) + 97 | autolayer(testing_data, series = "testing_data") 98 | 99 | ``` 100 | 101 | ### Forecasting using Support Vector Machines with Linear Kernel 102 | 103 | ```{r, example4} 104 | 105 | i <- 9 106 | 107 | dtlist <- caretForecast::split_ts(retail_wide[,i], test_size = 12) 108 | 109 | training_data <- dtlist$train 110 | 111 | testing_data <- dtlist$test 112 | 113 | fit <- ARml(training_data, max_lag = 12, caret_method = "svmLinear2", 114 | verbose = FALSE, pre_process = c("scale", "center")) 115 | 116 | forecast(fit, h = length(testing_data), level = c(80,95), PI = TRUE)-> fc 117 | 118 | accuracy(fc, testing_data) 119 | 120 | autoplot(fc) + 121 | autolayer(testing_data, series = "testing_data") 122 | 123 | get_var_imp(fc) 124 | 125 | get_var_imp(fc, plot = F) 126 | 127 | ``` 128 | 129 | ### Forecasting using Ridge Regression 130 | 131 | ```{r, example5} 132 | 133 | i <- 8 134 | 135 | dtlist <- caretForecast::split_ts(retail_wide[,i], test_size = 12) 136 | 137 | training_data <- dtlist$train 138 | 139 | testing_data <- dtlist$test 140 | 141 | fit <- ARml(training_data, max_lag = 12, caret_method = "ridge", 142 | verbose = FALSE) 143 | 144 | forecast(fit, h = length(testing_data), level = c(80,95), PI = TRUE)-> fc 145 | 146 | accuracy(fc, testing_data) 147 | 148 | autoplot(fc) + 149 | autolayer(testing_data, series = "testing_data") 150 | 151 | get_var_imp(fc) 152 | 153 | get_var_imp(fc, plot = F) 154 | ``` 155 | 156 | ## Adding external variables 157 | 158 | The xreg argument can be used for adding promotions, holidays, and other external variables to the model. In the example below, we will add seasonal dummies to the model. We set the 'seasonal = FALSE' to avoid adding the Fourier series to the model together with seasonal dummies. 159 | 160 | ```{r, example6} 161 | 162 | xreg_train <- forecast::seasonaldummy(AirPassengers) 163 | 164 | newxreg <- forecast::seasonaldummy(AirPassengers, h = 21) 165 | 166 | fit <- ARml(AirPassengers, max_lag = 4, caret_method = "cubist", 167 | seasonal = FALSE, xreg = xreg_train, verbose = FALSE) 168 | 169 | fc <- forecast(fit, h = 12, level = c(80, 95, 99), xreg = newxreg) 170 | 171 | autoplot(fc) 172 | 173 | get_var_imp(fc) 174 | 175 | ``` 176 | 177 | # Forecasting Hierarchical or grouped time series 178 | 179 | 180 | ```{r, example7, warning=FALSE, message=FALSE} 181 | library(hts) 182 | 183 | data("htseg1", package = "hts") 184 | 185 | fc <- forecast(htseg1, h = 4, FUN = caretForecast::ARml, 186 | caret_method = "ridge", verbose = FALSE) 187 | 188 | plot(fc) 189 | 190 | ``` 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # caretForecast 5 | 6 | 7 | 8 | 9 | caretForecast aspires to equip users with the means of using machine 10 | learning algorithms for time series data forecasting. 11 | 12 | ## Installation 13 | 14 | The CRAN version with: 15 | 16 | ``` r 17 | install.packages("caretForecast") 18 | ``` 19 | 20 | The development version from [GitHub](https://github.com/) with: 21 | 22 | ``` r 23 | # install.packages("devtools") 24 | devtools::install_github("Akai01/caretForecast") 25 | ``` 26 | 27 | ## Example 28 | 29 | By using caretForecast, users can train any regression model that is 30 | compatible with the caret package. This allows them to use any machine 31 | learning model they need in order to solve specific problems, as shown 32 | by the examples below. 33 | 34 | ### Load the library 35 | 36 | ``` r 37 | library(caretForecast) 38 | #> Registered S3 method overwritten by 'quantmod': 39 | #> method from 40 | #> as.zoo.data.frame zoo 41 | 42 | data(retail_wide, package = "caretForecast") 43 | ``` 44 | 45 | ### Forecasting with glmboost 46 | 47 | ``` r 48 | i <- 8 49 | 50 | dtlist <- caretForecast::split_ts(retail_wide[,i], test_size = 12) 51 | 52 | training_data <- dtlist$train 53 | 54 | testing_data <- dtlist$test 55 | 56 | fit <- ARml(training_data, max_lag = 12, caret_method = "glmboost", 57 | verbose = FALSE) 58 | #> initial_window = NULL. Setting initial_window = 301 59 | #> Loading required package: ggplot2 60 | #> Loading required package: lattice 61 | 62 | forecast(fit, h = length(testing_data), level = c(80,95))-> fc 63 | 64 | accuracy(fc, testing_data) 65 | #> ME RMSE MAE MPE MAPE MASE 66 | #> Training set 1.899361e-14 16.55233 11.98019 -1.132477 6.137096 0.777379 67 | #> Test set 7.472114e+00 21.68302 18.33423 2.780723 5.876433 1.189685 68 | #> ACF1 Theil's U 69 | #> Training set 0.6181425 NA 70 | #> Test set 0.3849258 0.8078558 71 | 72 | 73 | autoplot(fc) + 74 | autolayer(testing_data, series = "testing_data") 75 | ``` 76 | 77 | 78 | 79 | ### Forecasting with cubist regression 80 | 81 | ``` r 82 | i <- 9 83 | 84 | dtlist <- caretForecast::split_ts(retail_wide[,i], test_size = 12) 85 | 86 | training_data <- dtlist$train 87 | 88 | testing_data <- dtlist$test 89 | 90 | fit <- ARml(training_data, max_lag = 12, caret_method = "cubist", 91 | verbose = FALSE) 92 | #> initial_window = NULL. Setting initial_window = 301 93 | 94 | forecast(fit, h = length(testing_data), level = c(80,95), PI = TRUE)-> fc 95 | 96 | accuracy(fc, testing_data) 97 | #> ME RMSE MAE MPE MAPE MASE 98 | #> Training set 0.5498926 13.33516 10.36501 0.0394589 2.223005 0.3454108 99 | #> Test set -17.9231242 47.13871 32.03537 -2.6737257 4.271373 1.0675691 100 | #> ACF1 Theil's U 101 | #> Training set 0.3979153 NA 102 | #> Test set 0.4934659 0.4736043 103 | 104 | autoplot(fc) + 105 | autolayer(testing_data, series = "testing_data") 106 | ``` 107 | 108 | 109 | 110 | ### Forecasting using Support Vector Machines with Linear Kernel 111 | 112 | ``` r 113 | 114 | i <- 9 115 | 116 | dtlist <- caretForecast::split_ts(retail_wide[,i], test_size = 12) 117 | 118 | training_data <- dtlist$train 119 | 120 | testing_data <- dtlist$test 121 | 122 | fit <- ARml(training_data, max_lag = 12, caret_method = "svmLinear2", 123 | verbose = FALSE, pre_process = c("scale", "center")) 124 | #> initial_window = NULL. Setting initial_window = 301 125 | 126 | forecast(fit, h = length(testing_data), level = c(80,95), PI = TRUE)-> fc 127 | 128 | accuracy(fc, testing_data) 129 | #> ME RMSE MAE MPE MAPE MASE 130 | #> Training set -0.2227708 22.66741 17.16009 -0.2476916 3.712496 0.5718548 131 | #> Test set -1.4732653 28.47932 22.92438 -0.4787467 2.883937 0.7639481 132 | #> ACF1 Theil's U 133 | #> Training set 0.3290937 NA 134 | #> Test set 0.3863955 0.3137822 135 | 136 | autoplot(fc) + 137 | autolayer(testing_data, series = "testing_data") 138 | ``` 139 | 140 | 141 | 142 | ``` r 143 | 144 | get_var_imp(fc) 145 | ``` 146 | 147 | 148 | 149 | ``` r 150 | 151 | get_var_imp(fc, plot = F) 152 | #> loess r-squared variable importance 153 | #> 154 | #> only 20 most important variables shown (out of 23) 155 | #> 156 | #> Overall 157 | #> lag12 100.0000 158 | #> lag1 83.9153 159 | #> lag11 80.4644 160 | #> lag2 79.9170 161 | #> lag3 79.5019 162 | #> lag4 78.3472 163 | #> lag9 78.1634 164 | #> lag5 78.0262 165 | #> lag7 77.9153 166 | #> lag8 76.7721 167 | #> lag10 76.4275 168 | #> lag6 75.7056 169 | #> S1-12 3.8169 170 | #> S3-12 2.4230 171 | #> C2-12 2.1863 172 | #> S5-12 2.1154 173 | #> C4-12 1.9426 174 | #> C1-12 0.5974 175 | #> C6-12 0.3883 176 | #> S2-12 0.2220 177 | ``` 178 | 179 | ### Forecasting using Ridge Regression 180 | 181 | ``` r 182 | 183 | i <- 8 184 | 185 | dtlist <- caretForecast::split_ts(retail_wide[,i], test_size = 12) 186 | 187 | training_data <- dtlist$train 188 | 189 | testing_data <- dtlist$test 190 | 191 | fit <- ARml(training_data, max_lag = 12, caret_method = "ridge", 192 | verbose = FALSE) 193 | #> initial_window = NULL. Setting initial_window = 301 194 | 195 | forecast(fit, h = length(testing_data), level = c(80,95), PI = TRUE)-> fc 196 | 197 | accuracy(fc, testing_data) 198 | #> ME RMSE MAE MPE MAPE MASE 199 | #> Training set 7.11464e-14 12.69082 9.53269 -0.1991292 5.212444 0.6185639 200 | #> Test set 1.52445e+00 14.45469 12.04357 0.6431543 3.880894 0.7814914 201 | #> ACF1 Theil's U 202 | #> Training set 0.2598784 NA 203 | #> Test set 0.3463574 0.5056792 204 | 205 | autoplot(fc) + 206 | autolayer(testing_data, series = "testing_data") 207 | ``` 208 | 209 | 210 | 211 | ``` r 212 | 213 | get_var_imp(fc) 214 | ``` 215 | 216 | 217 | 218 | ``` r 219 | 220 | get_var_imp(fc, plot = F) 221 | #> loess r-squared variable importance 222 | #> 223 | #> only 20 most important variables shown (out of 23) 224 | #> 225 | #> Overall 226 | #> lag12 100.0000 227 | #> lag1 84.2313 228 | #> lag2 78.9566 229 | #> lag11 78.5354 230 | #> lag3 76.3480 231 | #> lag10 74.4727 232 | #> lag4 74.1330 233 | #> lag7 74.0737 234 | #> lag9 73.9113 235 | #> lag5 73.2040 236 | #> lag8 72.7224 237 | #> lag6 71.5713 238 | #> S1-12 6.3658 239 | #> S3-12 2.7341 240 | #> C2-12 2.7125 241 | #> S5-12 2.4858 242 | #> C4-12 2.2137 243 | #> C6-12 0.6381 244 | #> C1-12 0.5176 245 | #> S2-12 0.4464 246 | ``` 247 | 248 | ## Adding external variables 249 | 250 | The xreg argument can be used for adding promotions, holidays, and other 251 | external variables to the model. In the example below, we will add 252 | seasonal dummies to the model. We set the ‘seasonal = FALSE’ to avoid 253 | adding the Fourier series to the model together with seasonal dummies. 254 | 255 | ``` r 256 | 257 | xreg_train <- forecast::seasonaldummy(AirPassengers) 258 | 259 | newxreg <- forecast::seasonaldummy(AirPassengers, h = 21) 260 | 261 | fit <- ARml(AirPassengers, max_lag = 4, caret_method = "cubist", 262 | seasonal = FALSE, xreg = xreg_train, verbose = FALSE) 263 | #> initial_window = NULL. Setting initial_window = 132 264 | 265 | fc <- forecast(fit, h = 12, level = c(80, 95, 99), xreg = newxreg) 266 | 267 | autoplot(fc) 268 | ``` 269 | 270 | 271 | 272 | ``` r 273 | 274 | get_var_imp(fc) 275 | ``` 276 | 277 | 278 | 279 | # Forecasting Hierarchical or grouped time series 280 | 281 | ``` r 282 | library(hts) 283 | 284 | data("htseg1", package = "hts") 285 | 286 | fc <- forecast(htseg1, h = 4, FUN = caretForecast::ARml, 287 | caret_method = "ridge", verbose = FALSE) 288 | 289 | plot(fc) 290 | ``` 291 | 292 | 293 | -------------------------------------------------------------------------------- /caretForecast.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: No 4 | SaveWorkspace: No 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | LineEndingConversion: Posix 18 | 19 | BuildType: Package 20 | PackageUseDevtools: Yes 21 | PackageInstallArgs: --no-multiarch --with-keep.source 22 | PackageRoxygenize: rd,collate,namespace 23 | -------------------------------------------------------------------------------- /cran-comments.md: -------------------------------------------------------------------------------- 1 | ## R CMD check results 2 | 3 | 0 errors | 0 warnings | 1 note 4 | 5 | * This is a new release. 6 | -------------------------------------------------------------------------------- /data/retail.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/data/retail.rda -------------------------------------------------------------------------------- /data/retail_wide.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/data/retail_wide.rda -------------------------------------------------------------------------------- /man/ARml.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/arml.R 3 | \name{ARml} 4 | \alias{ARml} 5 | \title{Autoregressive forecasting using various Machine Learning models.} 6 | \usage{ 7 | ARml( 8 | y, 9 | max_lag = 5, 10 | xreg = NULL, 11 | caret_method = "cubist", 12 | metric = "RMSE", 13 | pre_process = NULL, 14 | cv = TRUE, 15 | cv_horizon = 4, 16 | initial_window = NULL, 17 | fixed_window = FALSE, 18 | verbose = TRUE, 19 | seasonal = TRUE, 20 | K = frequency(y)/2, 21 | tune_grid = NULL, 22 | lambda = NULL, 23 | BoxCox_method = c("guerrero", "loglik"), 24 | BoxCox_lower = -1, 25 | BoxCox_upper = 2, 26 | BoxCox_biasadj = FALSE, 27 | BoxCox_fvar = NULL, 28 | allow_parallel = FALSE, 29 | ... 30 | ) 31 | } 32 | \arguments{ 33 | \item{y}{A univariate time series object.} 34 | 35 | \item{max_lag}{Maximum value of lag.} 36 | 37 | \item{xreg}{Optional. A numerical vector or matrix of external regressors, 38 | which must have the same number of rows as y. 39 | (It should not be a data frame.).} 40 | 41 | \item{caret_method}{A string specifying which classification or 42 | regression model to use. 43 | Possible values are found using names(getModelInfo()). 44 | A list of functions can also be passed for a custom model function. 45 | See \url{http://topepo.github.io/caret/} for details.} 46 | 47 | \item{metric}{A string that specifies what summary metric will be used to 48 | select the optimal model. See \code{?caret::train}.} 49 | 50 | \item{pre_process}{A string vector that defines a pre-processing of the 51 | predictor data. 52 | Current possibilities are "BoxCox", "YeoJohnson", "expoTrans", "center", 53 | "scale", "range", 54 | "knnImpute", "bagImpute", "medianImpute", "pca", "ica" and "spatialSign". 55 | The default is no pre-processing. 56 | See preProcess and trainControl on the procedures and how to adjust them. 57 | Pre-processing code is only designed to work when x is a simple matrix or 58 | data frame.} 59 | 60 | \item{cv}{Logical, if \code{cv = TRUE} model selection will be done via 61 | cross-validation. If \code{cv = FALSE} user need to provide a specific model 62 | via \code{tune_grid} argument.} 63 | 64 | \item{cv_horizon}{The number of consecutive values in test set sample.} 65 | 66 | \item{initial_window}{The initial number of consecutive values in each 67 | training set sample.} 68 | 69 | \item{fixed_window}{Logical, if FALSE, all training samples start at 1.} 70 | 71 | \item{verbose}{A logical for printing a training log.} 72 | 73 | \item{seasonal}{Boolean. If \code{seasonal = TRUE} the fourier terms will be 74 | used for modeling seasonality.} 75 | 76 | \item{K}{Maximum order(s) of Fourier terms} 77 | 78 | \item{tune_grid}{A data frame with possible tuning values. 79 | The columns are named the same as the tuning parameters. 80 | Use getModelInfo to get a list of tuning parameters for each model or 81 | see \url{http://topepo.github.io/caret/available-models.html}. 82 | (NOTE: If given, this argument must be named.)} 83 | 84 | \item{lambda}{BoxCox transformation parameter. If \code{lambda = NULL} 85 | If \code{lambda = "auto"}, then the transformation parameter lambda is chosen 86 | using \code{\link[forecast]{BoxCox.lambda}}.} 87 | 88 | \item{BoxCox_method}{\code{\link[forecast]{BoxCox.lambda}} argument. 89 | Choose method to be used in calculating lambda.} 90 | 91 | \item{BoxCox_lower}{\code{\link[forecast]{BoxCox.lambda}} argument. 92 | Lower limit for possible lambda values.} 93 | 94 | \item{BoxCox_upper}{\code{\link[forecast]{BoxCox.lambda}} argument. 95 | Upper limit for possible lambda values.} 96 | 97 | \item{BoxCox_biasadj}{\code{\link[forecast]{InvBoxCox}} argument. 98 | Use adjusted back-transformed mean for Box-Cox transformations. 99 | If transformed data is used to produce forecasts and fitted values, 100 | a regular back transformation will result in median forecasts. 101 | If biasadj is TRUE, an adjustment will be made to produce mean 102 | forecasts and fitted values.} 103 | 104 | \item{BoxCox_fvar}{\code{\link[forecast]{InvBoxCox}} argument. 105 | Optional parameter required if biasadj=TRUE. 106 | Can either be the forecast variance, or a list containing the interval level, 107 | and the corresponding upper and lower intervals.} 108 | 109 | \item{allow_parallel}{If a parallel backend is loaded and available, 110 | should the function use it?} 111 | 112 | \item{...}{Ignored.} 113 | } 114 | \value{ 115 | A list class of forecast containing the following elemets 116 | \itemize{ 117 | \item x : The input time series 118 | \item method : The name of the forecasting method as a character string 119 | \item mean : Point forecasts as a time series 120 | \item lower : Lower limits for prediction intervals 121 | \item upper : Upper limits for prediction intervals 122 | \item level : The confidence values associated with the prediction intervals 123 | \item model : A list containing information about the fitted model 124 | \item newx : A matrix containing regressors 125 | } 126 | } 127 | \description{ 128 | Autoregressive forecasting using various Machine Learning models. 129 | } 130 | \examples{ 131 | 132 | library(caretForecast) 133 | 134 | train_data <- window(AirPassengers, end = c(1959, 12)) 135 | 136 | test <- window(AirPassengers, start = c(1960, 1)) 137 | 138 | ARml(train_data, caret_method = "lm", max_lag = 12) -> fit 139 | 140 | forecast(fit, h = length(test)) -> fc 141 | 142 | autoplot(fc) + autolayer(test) 143 | 144 | accuracy(fc, test) 145 | 146 | } 147 | \author{ 148 | Resul Akay 149 | } 150 | -------------------------------------------------------------------------------- /man/conformalRegressor.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fit_conformal_reg.R 3 | \name{conformalRegressor} 4 | \alias{conformalRegressor} 5 | \title{Fit a conformal regressor.} 6 | \usage{ 7 | conformalRegressor(residuals, sigmas = NULL) 8 | } 9 | \arguments{ 10 | \item{residuals}{Model residuals.} 11 | 12 | \item{sigmas}{A vector of difficulty estimates} 13 | } 14 | \value{ 15 | A conformalRegressor object 16 | } 17 | \description{ 18 | Fit a conformal regressor. 19 | } 20 | \references{ 21 | Boström, H., 2022. crepes: a Python Package for Generating Conformal 22 | Regressors and Predictive Systems. In Conformal and Probabilistic Prediction 23 | and Applications. PMLR, 179. 24 | \url{https://copa-conference.com/papers/COPA2022_paper_11.pdf} 25 | } 26 | \author{ 27 | Resul Akay 28 | } 29 | -------------------------------------------------------------------------------- /man/figures/README-example-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example-1.png -------------------------------------------------------------------------------- /man/figures/README-example-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example-2.png -------------------------------------------------------------------------------- /man/figures/README-example-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example-3.png -------------------------------------------------------------------------------- /man/figures/README-example-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example-4.png -------------------------------------------------------------------------------- /man/figures/README-example-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example-5.png -------------------------------------------------------------------------------- /man/figures/README-example-6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example-6.png -------------------------------------------------------------------------------- /man/figures/README-example2-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example2-1.png -------------------------------------------------------------------------------- /man/figures/README-example3-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example3-1.png -------------------------------------------------------------------------------- /man/figures/README-example4-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example4-1.png -------------------------------------------------------------------------------- /man/figures/README-example4-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example4-2.png -------------------------------------------------------------------------------- /man/figures/README-example5-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example5-1.png -------------------------------------------------------------------------------- /man/figures/README-example5-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example5-2.png -------------------------------------------------------------------------------- /man/figures/README-example6-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example6-1.png -------------------------------------------------------------------------------- /man/figures/README-example6-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example6-2.png -------------------------------------------------------------------------------- /man/figures/README-example7-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Akai01/caretForecast/d3b11594639bbc5174ba40b44421218f8756618c/man/figures/README-example7-1.png -------------------------------------------------------------------------------- /man/forecast.ARml.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/forecast.R 3 | \name{forecast.ARml} 4 | \alias{forecast.ARml} 5 | \title{Forecasting using ARml model} 6 | \usage{ 7 | \method{forecast}{ARml}(object, h = frequency(object$y), xreg = NULL, level = c(80, 95), ...) 8 | } 9 | \arguments{ 10 | \item{object}{An object of class "ARml", the result of a call to ARml.} 11 | 12 | \item{h}{forecast horizon} 13 | 14 | \item{xreg}{Optionally, a numerical vector or matrix of future external 15 | regressors} 16 | 17 | \item{level}{Confidence level for prediction intervals.} 18 | 19 | \item{...}{Ignored} 20 | } 21 | \value{ 22 | A list class of forecast containing the following elemets 23 | \itemize{ 24 | \item x : The input time series 25 | \item method : The name of the forecasting method as a character string 26 | \item mean : Point forecasts as a time series 27 | \item lower : Lower limits for prediction intervals 28 | \item upper : Upper limits for prediction intervals 29 | \item level : The confidence values associated with the prediction intervals 30 | \item model : A list containing information about the fitted model 31 | \item newxreg : A matrix containing regressors 32 | } 33 | } 34 | \description{ 35 | Forecasting using ARml model 36 | } 37 | \examples{ 38 | 39 | library(caretForecast) 40 | 41 | train_data <- window(AirPassengers, end = c(1959, 12)) 42 | 43 | test <- window(AirPassengers, start = c(1960, 1)) 44 | 45 | ARml(train_data, caret_method = "lm", max_lag = 12) -> fit 46 | 47 | forecast(fit, h = length(test), level = c(80,95)) -> fc 48 | 49 | autoplot(fc)+ autolayer(test) 50 | 51 | accuracy(fc, test) 52 | } 53 | \author{ 54 | Resul Akay 55 | } 56 | -------------------------------------------------------------------------------- /man/get_var_imp.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{get_var_imp} 4 | \alias{get_var_imp} 5 | \title{Variable importance for forecasting model.} 6 | \usage{ 7 | get_var_imp(object, plot = TRUE) 8 | } 9 | \arguments{ 10 | \item{object}{A list class of ARml or forecast object derived from ARml} 11 | 12 | \item{plot}{Boolean, if TRUE, variable importance will be ploted.} 13 | } 14 | \value{ 15 | A list class of "varImp.train". See \code{\link[caret]{varImp}} or a 16 | "trellis" plot. 17 | } 18 | \description{ 19 | Variable importance for forecasting model. 20 | } 21 | \examples{ 22 | 23 | train <- window(AirPassengers, end = c(1959, 12)) 24 | 25 | test <- window(AirPassengers, start = c(1960, 1)) 26 | 27 | ARml(train, caret_method = "lm", max_lag = 12, trend_method = "none", 28 | pre_process = "center") -> fit 29 | 30 | forecast(fit, h = length(test), level = c(80,95)) -> fc 31 | 32 | autoplot(fc)+ autolayer(test) 33 | 34 | accuracy(fc, test) 35 | 36 | get_var_imp(fc, plot = TRUE) 37 | 38 | 39 | } 40 | \author{ 41 | Resul Akay 42 | } 43 | -------------------------------------------------------------------------------- /man/predict.conformalRegressor.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/predict_conformal.R 3 | \name{predict.conformalRegressor} 4 | \alias{predict.conformalRegressor} 5 | \title{Predict a conformalRegressor} 6 | \usage{ 7 | \method{predict}{conformalRegressor}( 8 | object, 9 | y_hat = NULL, 10 | sigmas = NULL, 11 | confidence = 0.95, 12 | y_min = -Inf, 13 | y_max = Inf, 14 | ... 15 | ) 16 | } 17 | \arguments{ 18 | \item{object}{A conformalRegressor object} 19 | 20 | \item{y_hat}{Predicted values} 21 | 22 | \item{sigmas}{Difficulty estimates} 23 | 24 | \item{confidence}{Confidence level} 25 | 26 | \item{y_min}{The minimum value to include in prediction intervals} 27 | 28 | \item{y_max}{The maximum value to include in prediction intervals} 29 | 30 | \item{...}{Ignored} 31 | } 32 | \value{ 33 | Prediction intervals 34 | } 35 | \description{ 36 | Predict a conformalRegressor 37 | } 38 | \author{ 39 | Resul Akay 40 | } 41 | -------------------------------------------------------------------------------- /man/reexports.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/forecast.R, R/utils.R 3 | \docType{import} 4 | \name{reexports} 5 | \alias{reexports} 6 | \alias{forecast} 7 | \alias{autoplot} 8 | \alias{autolayer} 9 | \alias{accuracy} 10 | \alias{\%>\%} 11 | \alias{\%<>\%} 12 | \title{Objects exported from other packages} 13 | \keyword{internal} 14 | \description{ 15 | These objects are imported from other packages. Follow the links 16 | below to see their documentation. 17 | 18 | \describe{ 19 | \item{forecast}{\code{\link[forecast]{autolayer}}, \code{\link[forecast:reexports]{autoplot}}} 20 | 21 | \item{generics}{\code{\link[generics]{accuracy}}, \code{\link[generics]{forecast}}} 22 | 23 | \item{magrittr}{\code{\link[magrittr:compound]{\%<>\%}}, \code{\link[magrittr:pipe]{\%>\%}}} 24 | }} 25 | 26 | -------------------------------------------------------------------------------- /man/retail.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \docType{data} 4 | \name{retail} 5 | \alias{retail} 6 | \title{Grouped sales data from an Australian Retailer} 7 | \format{ 8 | A data class of "tbl_df", "tbl", "data.frame" with 13986 rows and 3 columns: 9 | \describe{ 10 | \item{date}{date} 11 | \item{item}{products} 12 | \item{value}{sales} 13 | } 14 | } 15 | \source{ 16 | \url{https://robjhyndman.com/data/ausretail.csv} 17 | } 18 | \usage{ 19 | retail 20 | } 21 | \description{ 22 | A dataset containing 42 products' sales 23 | } 24 | \keyword{datasets} 25 | -------------------------------------------------------------------------------- /man/retail_wide.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \docType{data} 4 | \name{retail_wide} 5 | \alias{retail_wide} 6 | \title{Sales data from an Australian Retailer in time series format} 7 | \format{ 8 | An object of class mts (inherits from ts, matrix) 9 | with 333 rows and 43 columns. 10 | \describe{ 11 | This data set is the wide format of \code{\link{retail}} data. 12 | } 13 | } 14 | \source{ 15 | \url{https://robjhyndman.com/data/ausretail.csv} 16 | } 17 | \usage{ 18 | retail_wide 19 | } 20 | \description{ 21 | A dataset containing 42 products' sales 22 | } 23 | \keyword{datasets} 24 | -------------------------------------------------------------------------------- /man/split_ts.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{split_ts} 4 | \alias{split_ts} 5 | \title{Split a time series into training and testing sets} 6 | \usage{ 7 | split_ts(y, test_size = 10) 8 | } 9 | \arguments{ 10 | \item{y}{A univariate time series} 11 | 12 | \item{test_size}{The number of observations to keep in the test set} 13 | } 14 | \value{ 15 | A list with train and test elements 16 | } 17 | \description{ 18 | Split a time series into training and testing sets 19 | } 20 | \examples{ 21 | 22 | dlist <- split_ts(retail_wide[,1], test_size = 12) 23 | 24 | } 25 | \author{ 26 | Resul Akay 27 | } 28 | -------------------------------------------------------------------------------- /man/suggested_methods.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{suggested_methods} 4 | \alias{suggested_methods} 5 | \title{Suggested methods for ARml} 6 | \usage{ 7 | suggested_methods() 8 | } 9 | \value{ 10 | A character vector of Suggested methods 11 | } 12 | \description{ 13 | Suggested methods for ARml 14 | } 15 | \examples{ 16 | 17 | suggested_methods() 18 | 19 | } 20 | \author{ 21 | Resul Akay 22 | } 23 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(caretForecast) 3 | 4 | test_check("caretForecast") 5 | -------------------------------------------------------------------------------- /tests/testthat/test-ARml.R: -------------------------------------------------------------------------------- 1 | # A unit test for ARml function 2 | if(require(testthat)){ 3 | test_that("tests for some arguments in ARml", { 4 | ARml(AirPassengers, caret_method = "lm", max_lag = 12, K = 5) -> fit 5 | 6 | class_fit <- class(fit) 7 | 8 | expect_that(class_fit, equals("ARml")) 9 | 10 | }) 11 | } 12 | 13 | if(require(testthat)){ 14 | test_that("tests for some arguments in ARml", { 15 | ARml(AirPassengers, caret_method = "lm", max_lag = 12, lambda = NULL, 16 | K= 5) -> fit 17 | 18 | class_fit <- class(fit) 19 | 20 | expect_that(class_fit, equals("ARml")) 21 | 22 | }) 23 | } 24 | 25 | if(require(testthat)){ 26 | test_that("tests for some arguments in ARml", { 27 | ARml(AirPassengers, caret_method = "lm", max_lag = 12, lambda = "auto", 28 | BoxCox_method = "loglik", K = 5) -> fit 29 | 30 | class_fit <- class(fit) 31 | 32 | expect_that(class_fit, equals("ARml")) 33 | 34 | }) 35 | } 36 | 37 | 38 | if(require(testthat)){ 39 | test_that("tests for some arguments in ARml", { 40 | ARml(AirPassengers, caret_method = "lm", max_lag = 10, 41 | xreg = forecast::seasonaldummy(AirPassengers), seasonal = F) -> fit 42 | 43 | class_fit <- class(fit) 44 | 45 | expect_that(class_fit, equals("ARml")) 46 | 47 | }) 48 | } 49 | -------------------------------------------------------------------------------- /tests/testthat/test-conformal_pred.R: -------------------------------------------------------------------------------- 1 | if(require(testthat)){ 2 | test_that("tests for some arguments in ARml", { 3 | 4 | fit <- ARml(AirPassengers, caret_method = "lm", max_lag = 10) 5 | 6 | fc <- forecast(fit, h = 1) 7 | 8 | res <- residuals(fit) 9 | conf_reg <- conformalRegressor(res) 10 | conf_pred <- predict(conf_reg, y_hat = fc$mean, confidence = 0.9) 11 | conf_pred <- mean(unlist(conf_pred)) 12 | 13 | expect_equal(conf_pred, 446.7539, tolerance = 5) 14 | 15 | }) 16 | } 17 | -------------------------------------------------------------------------------- /tests/testthat/test-forecast.ARml.R: -------------------------------------------------------------------------------- 1 | # A unit test for forecast function 2 | if(require(testthat)){ 3 | 4 | test_that("tests for some arguments in forecast 1", { 5 | 6 | forecast(ARml(AirPassengers, caret_method = "lm", max_lag = 12, K=5), 7 | h = 2) -> fc 8 | values <- as.numeric(ceiling(c(fc$mean))) 9 | expect_equal(values, c(459, 429), tolerance = 1) 10 | 11 | }) 12 | } 13 | 14 | 15 | 16 | if(require(testthat)){ 17 | 18 | test_that("tests for some arguments in forecast 2", { 19 | 20 | ARml(AirPassengers, caret_method = "lm", max_lag = 10, 21 | xreg = forecast::seasonaldummy(AirPassengers), seasonal = F) -> fit 22 | forecast(fit, h = 2, xreg = forecast::seasonaldummy(AirPassengers, h = 2)) -> fc 23 | values <- as.numeric(ceiling(c(fc$mean))) 24 | expect_equal(values, c(446, 445), tolerance = 1) 25 | 26 | }) 27 | } 28 | 29 | 30 | if(require(testthat)){ 31 | 32 | test_that("tests for some arguments in forecast 3", { 33 | 34 | forecast(ARml(AirPassengers, caret_method = "lm", max_lag = 12, 35 | seasonal = F), h = 2) -> fc 36 | values <- as.numeric(ceiling(c(fc$mean))) 37 | expect_equal(values, c(465, 429), tolerance = 1) 38 | 39 | }) 40 | } 41 | -------------------------------------------------------------------------------- /tests/testthat/test-get_var_imp.R: -------------------------------------------------------------------------------- 1 | # A unit test for get_var_imp function 2 | if(require(testthat)){ 3 | test_that("tests for some arguments in get_var_imp", { 4 | library(caretForecast) 5 | fit <- ARml(AirPassengers, caret_method = "lm", max_lag = 12, 6 | trend_method = "none",pre_process = "center") 7 | forecast(fit, h = 12) -> fc 8 | a <- get_var_imp(fc, plot = FALSE) 9 | class_a <- class(a) 10 | expect_that(class_a, equals("varImp.train")) 11 | 12 | }) 13 | } 14 | 15 | 16 | get_var_imp# A unit test for get_var_imp function 17 | if(require(testthat)){ 18 | 19 | test_that("tests for some arguments in get_var_imp2", { 20 | library(caretForecast) 21 | fit <- ARml(AirPassengers, caret_method = "lm", max_lag = 12, 22 | trend_method = "none",pre_process = "center") 23 | forecast(fit, h = 12) -> fc 24 | a <- get_var_imp(fc, plot = TRUE) 25 | class_a <- class(a) 26 | expect_that(class_a, equals("trellis")) 27 | 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /tests/testthat/test-split_ts.R: -------------------------------------------------------------------------------- 1 | 2 | # A unit test for split_ts function 3 | if(require(testthat)){ 4 | 5 | test_that("tests for some arguments in split_ts", { 6 | result <- split_ts(retail_wide[,1], test_size = 2) 7 | 8 | result <- as.numeric(result$test) 9 | 10 | expect_that(result, equals(c(409.4, 583.6))) 11 | 12 | }) 13 | } 14 | -------------------------------------------------------------------------------- /tests/testthat/test-suggested_method.R: -------------------------------------------------------------------------------- 1 | # A unit test for suggested_methods function 2 | if(require(testthat)){ 3 | 4 | test_that("tests for some arguments in suggested_methods", { 5 | result <- suggested_methods() 6 | 7 | expect_that(result, equals(c("spikeslab", "bagEarth", "bagEarthGCV", "blasso", 8 | "cforest", "earth","extraTrees", "gbm_h2o", "glmStepAIC", 9 | "parRF", "qrf", "Rborist", "rf", "rqlasso", "rqnc", 10 | "spikeslab", "xgbDART", "xgbLinear", "ranger", "cubist", 11 | "svmLinear", "enet", "bridge", "glmboost", "ridge", 12 | "lasso", "relaxo", "M5Rules", "M5", "lm", "gaussprLinear", 13 | "glm", "glmnet", "pcr", "ppr", "foba", "gbm", "svmLinear2", 14 | "glm.nb", "gcvEarth", "lars2", "lars", "icr", "ctree2", 15 | "ctree", "bayesglm"))) 16 | 17 | }) 18 | } 19 | --------------------------------------------------------------------------------