Saturday, 25 November 2017

Moving Media Grande Lag


Ritardo tra Marte e la Terra ora dell'evento Spacecraft contro la Terra riceve tempo Una foto del display ritardo Mars Express sul sistema di controllo, che ci mostra i numeri critici di senso unico tempo di luce, a due vie tempo di luce e la distanza dalla Terra. Una delle cose più difficili circa la gestione di un veicolo spaziale attorno a Marte (per non parlare dei diversi fusi orari), rispetto alla Terra, è che la sua così lontano Marte è così lontano, infatti, che ci vogliono segnali radio molto tempo a ottenere dal veicolo spaziale sulla Terra. Durante Curiosità EDL, questo ritardo sarà di 13 minuti, 48 secondi, circa a metà strada tra il minimo ritardo di circa 4 minuti e un massimo di circa 24 minuti. Questo lo rende una sfida per operare Mars Express perché è difficile avere una conversazione con la sonda, o reagire se succede qualcosa a bordo. Se c'è un problema e il veicolo spaziale ci dice, che non sapranno per 13 minuti, e poi anche se reagiamo subito itll essere altri 13 minuti prima che le nostre istruzioni tornare su Marte C'è un sacco che può accadere in mezz'ora a Mars (per esempio un intero atterraggio Curiosity) per mantenere Mars Express volare in modo sicuro, carichiamo tutti i comandi per la missione in anticipo e costruito in un sacco di autonomia di lasciare il veicolo spaziale prendersi cura di se stesso si potrebbe dire che per l'atterraggio Curiosity era in esecuzione completamente il pilota automatico il ritardo è nulla a che fare con la navicella o l'hardware sul terreno cant essere migliorato da un computer più veloce o un più potente radio. Infatti è obbedire il limite di velocità fondamentale dell'universo alla velocità della luce. A 1079 milioni kmhour, la luce è piuttosto veloce si potrebbe ottenere da qui alla Luna in poco più di un secondo, ma che sottolinea quanto sia lontano Marte è. Tutta la luce (o radiazione elettromagnetica, che comprende i segnali radio) viaggia fino a questa velocità, e le onde radio dalla Terra a Marte Express e indietro non fanno eccezione. Date un'occhiata alle voci di Wikipedia alla velocità della luce e youll vedere come, nel 1905, Einstein è venuto sul concetto di questo limite di velocità cosmica. Soprattutto, per la copertura domani della curiosità atterraggio rende difficile per noi di lavorare fuori quando a dirti quello che accade (come avete visto nella nostra linea temporale a tre colonne) presso l'ESOC, si parla di due momenti diversi Spacecraft Time Event (SCET) e la Terra tempo ricevuto (ERT). Il primo è che cosa realmente sta accadendo a Marte in questo momento, anche se ci dispiacerebbe sentiamo su di esso fino a oltre 13 minuti più tardi, una volta che noi chiamiamo ERT. Il ritardo tra i due è di solito chiamato One-Way Light Time (OWLT) e il tempo per un messaggio di andare su Marte e tornare è il bidirezionale luce Time (TWLT), o il tempo di andata e ritorno. Durante tutta la nostra copertura e seguire NASAs piombo e in generale comunicare gli eventi qui e su Twitter a voi in ERT perché questo è quando in realtà ben sapere che cosa è accaduto. Se noi comunichiamo qualcosa in SCET ben consente di sapere in modo (e anche noi) non ottenete confuso il suo tutto parte del divertimento di esplorare il Sistema Solare 80 pensieri sul ritardo ldquo di tempo tra Marte e la Terra rdquo No, tutte le onde viaggiano alla stessa velocità. Ci vogliono luce otto minuti su un viaggio di sola andata, 16 minuti su un viaggio di due vie. Si prega di imparare a nella fisica Un fotone è la particella vettore per entrambe le onde di luce visibile e radio, che sono entrambi forme di energia elettromagnetica, proprio a diverse frequenze. energia fotonica (che non ho mai sentito parlare di) sarebbe sinonimo di energia elettromagnetica. Luce, calore, gamma, radio, microonde, raggi ultravioletti - tutti sono mediate da particelle fotoniche, ma possiedono proprietà delle onde e, quindi la frequenza caratteristica. Più facile pensare a loro come le onde mentre sono in viaggio, ma le particelle quando colpiscono qualcosa. E questi numeri si applicano solo a viaggiare luce nel vuoto. La luce che passa attraverso la materia viaggia misurabile più lento. Credo che un po 'di laboratorio ha recentemente effettuato un esperimento in cui hanno smesso di luce all'interno di una sostanza rallentando lo waaaaaay giù in qualche modo. Non so come abbiano fatto, non ho letto il tutto. sarebbe stare alla ragione, allora, che certe frequenze di viaggio energia elettromagnetica più velocemente mentre interagiscono meno con la maggior parte delle forme di materia e quindi hanno meno interferenze quando si viaggia grandi distanze rispetto alle altre lunghezze d'onda viaggiano lo stesso percorso e la distanza, per esempio, la luce dedotto rispetto alla gamma - radiation, luce dedotto avrebbe avuto una maggiore probabilità di interagire con un mezzo rispetto al gammarays ritardare la lunghezza d'onda che passa attraverso minuscole quantità di materia. Si potrebbe dire che questo si tradurrebbe in gammarays avere una velocità di rete più veloce in media non corretto. Permettetemi di citare direttamente l'articolo che hai appena letto da quando ti sembra di aver perso. A 1079 milioni kmhour, la luce è piuttosto veloce si potrebbe ottenere da qui alla Luna in poco più di un secondo, ma che sottolinea quanto sia lontano Marte è. Tutta la luce (o radiazione elettromagnetica, che comprende i segnali radio) viaggia fino a questa velocità, e le onde radio dalla Terra a Marte Express e indietro non fanno eccezione. Il tempo dalla Terra a Marte varia tra i 4 e 24 minuti perché la terra (e Marte) sono entrambi in orbita intorno al sole, non l'un l'altro. La distanza tra loro, pertanto può cambiare drammaticamente a seconda di dove ci troviamo nelle nostre rispettive orbite. Quando Marte è direttamente dietro la Terra nel punto più vicino possibile, è a soli quattro minuti di distanza. Quando è al farthes punto opposto a noi dietro il Sole, è di 24 minuti. Il Sole nel frattempo, che orbita, rimane a circa 8 minuti di distanza dal nostro orbita intorno al Sole è molto quasi circolare. Un'altra nota, assumendo Marte è anche un'orbita circolare (che non è) si potrebbe supporre che la distanza da Marte al sole è di circa 12 minuti e che implica che la distanza massima sarebbe 8 12, che sarebbe solo 20 minuti. Tuttavia questo non è il caso, poiché Mars orbita è leggermente ellittica e in un piano leggermente diverso da terre orbita così rendendo possibile per loro di essere distanti come 24 minuti. Proprio sono imbattuto in questo: i segnali radio sono onde elettromagnetiche, come la luce o X-ray. La velocità delle onde elettromagnetiche nel vuoto, è 300000kmsec (circa). Al fine di calcolare il tempo di viaggio con questa velocità dalla Terra a Marte, abbiamo bisogno di conoscere la distanza. Quando il Marte e la Terra sono ai lati opposti del Sole, la distanza è il più grande: circa: 378 milioni di km. Il tempo necessario per un'onda elettromagnetica per coprire questa distanza è di circa: 21 minuti. La distanza minima tra Marte e la Terra è di 78 milioni di km, il tempo in questo caso è: 4.3 min. Quindi il tempo di viaggio tra Terra e Marte è compreso tra 4,3 minuti e 21 minuti, a seconda della distanza effettiva fra le due pianeti. Shab, si calcola come se fosse piano 2D, mentre DoctorZuber già menzionato la Terra e Marte sono ellissi di piano diverso. Se la terra è su un lato del sole e mars è dall'altro lato, allora la distanza tra la terra e marte è maggiore dalla terra al sole. Sembra piuttosto semplice. Tutti radiazione elettromagnetica viaggia alla velocità della luce. Gladson è sbagliato. Sia la Terra e Marte sono in orbita intorno al sole. Facciamo il viaggio in 265 giorni terrestri. Marte richiede 669 giorni terrestri. Mars raggio medio orbitale al sole è 1,6 volte quella della Terra. Possiamo essere molto più vicino a Marte, del sole, o 2,6 volte più lontano, a seconda delle nostre posizioni orbitali relativi. Andata e Time Radio viaggio dipende da dove la Terra e Marte sono relative al sole. Se siamo al nostro punto più vicino a Marte, RT tempo di transito è di 4 minuti. Se siamo a lati opposti del sole, time RT è di 24 minuti. Esso varia, perché la Terra e Marte orbitano intorno al sole a velocità diverse. A volte sono sullo stesso lato del sole e, al massimo avvicinamento, la luce richiede solo circa 3 minuti per viaggiare tra i due. A volte sono sui lati opposti del sole e ci vogliono fino a circa 22 minuti. Per quanto riguarda le altre risposte, la differenza tra la velocità di onde luminose radio è trascurabile su queste brevi distanze. Dipende dalla positionsame di Terra e Marte. Se siamo sullo stesso lato del sole siamo più vicini. Se i pianeti sono su lati opposti del sole. Il sole è più vicino. La distanza del sole dalla Terra è relativamente costante. Marte non è. Varges, non siamo necessariamente dalla stessa parte del sole, allo stesso tempo - quindi il tempo più lungo è per quando la Terra e Marte sono 180 gradi di fronte all'altro ed entrambi all'afelio, e la più breve sarebbe quando siamo entrambi dalla stessa parte , con Marte al perielio e la Terra all'afelio .: Ora si stanno facendo senso, ma a quel punto quanto tempo ci vorrà i soli luce di raggiungere marsDigital otturatore della fotocamera Lag amp Tempo di avvio Shutter Lag - che cosa è Uno dei più frustrante problemi di alcune persone corrono in con le fotocamere digitali è la caratteristica nota come ritardo allo scatto. Quante volte avete aspettato il momento giusto per prendere un colpo, solo per trascorrere il prossimo secondo di attesa per la macchina fotografica per scattare la foto, se non del tutto Nel frattempo, il vostro colpo perfetto è scomparso dalla vista. Si tratta di ritardo di scatto. Il tempo da quando si preme il pulsante di scatto (es. Il grilletto) fino a quando la fotocamera scatta in realtà la foto è conosciuto come totale ritardo allo scatto. Totale shutter lag è la combinazione di due processi in atto: il ritardo autofocus e il ritardo di scatto. Autofocus Lag - Non appena si preme il pulsante di scatto, la fotocamera tenta in generale per la ricerca di un punto di messa a fuoco appropriata. Questo meccanismo di messa a fuoco automatica è spesso molto lento, e contribuisce maggiormente al ritardo complessivo. In fotocamera compatta, l'obiettivo fisico è focalizzato avanti e indietro con un motore fino a quando la fotocamera determina che il focus è corretta. Ovviamente dal momento che dobbiamo aspettare per un motore a muoversi in entrambe le direzioni, il ritardo sta per essere considerevole. Con le fotocamere reflex digitali, un circuito di controllo ad anello chiuso avanzata permette una stima rapida di adeguata distanza di messa a fuoco, senza dover spostare lentamente la lente avanti e indietro. Si noti che tutte le telecamere vorrà più tempo per messa a fuoco automatica se l'ambiente è scuro o dell'oggetto fotografato mostra scarso contrasto (che rende più difficile per la macchina fotografica di lock-on a). Shutter Lag Release - Una volta che la fotocamera ha rilevato la distanza di messa a fuoco appropriata, la fotocamera fa scattare il meccanismo di otturatore elettronico o fisico. Su alcune fotocamere più economiche questo processo può richiedere una moderata quantità di tempo, ma di solito non è così significativo come il lag autofocus. Il ritardo di scatto è il tempo necessario per scattare la foto se uno ha quotpre-focusedquot (es. Premuto il pulsante di scatto a metà strada) o la modalità di messa a fuoco manuale utilizzato. Lag Totale - La somma di Autofocus Lag e ritardo rilascio otturatore. Questo è il ritardo più spesso visto quando quotpre-focusingquot non viene fatto, o in momenti in cui si sta cercando di prendere rapidamente una foto (es. Senza impostarla). Ovviamente, maggiore è il tempo totale di ritardo per una macchina fotografica, il più evidente e frustrante il ritardo diventa. Per l'acquisto di una nuova macchina fotografica, si dovrebbe confrontare attentamente le differenze di ritardo totale tra i diversi modelli, come alcune fotocamere sono molto più veloci di altri in questo senso. Assicurarsi che si sta confrontando il tempo necessario per girare lo stesso oggetto (come oggetti differenti porteranno a diversi ritardi messa a fuoco automatica di ritardo). Confronto di Shutter Lag amp valori di avvio ritardo nella tabella seguente sono in pochi secondi. La colonna riferimenti conterrà i link alle fonti per ogni punto di dati. Quando più riferimenti sono utilizzati per i dati, la media è mostrata, insieme con la gamma (min-max) in parentesi. È molto importante notare che le differenze negli approcci di misurazione e precisione conseguenza fare confronti diretti difficile. Pertanto, il confronto tra i modelli eseguite dalla stessa fonte dovrebbero teoricamente essere giusto, mentre il confronto tra fonti diverse possono essere meno precisi. Più telecamere saranno aggiunti nel corso del tempo. Si noti che è spesso difficile da testare per ritardo dell'otturatore, e che vi sia un certo grado di variabilità delle letture che varie fonti potrebbe indicare. Questo è specialmente il caso con ritardo totale, come è altamente dipendente dalla configurazione della lente. Pertanto, dove mutliple Totale prove dei GAL sono stati effettuati per una fotocamera con lo stesso tester, la misura più veloce è incluso. NOTA: Tutti gli orari indicati nella tabella di seguito sono in secondi (S). Moltiplicare per 1000 per convertire in millisecondi (ms). Sony Point 9 ms amp Spara shutter lag Sì, tanto sorprendente quanto lo è, Sony ha apparentemente ritardi ritardo di scatto di appena 9 ms Questo valore è stato pubblicato sul sito di Sony con alcuni dei loro punto e sparare modelli in Specifiche. Si dovrebbe sempre prendere i produttori di occhiali di prestazioni con un grano di sale, ma ci può essere qualche verità a questo come un altro tester (Imaging-Resource) si avvicinò con la stessa cifra. È importante notare, tuttavia, che questo è senza auto-focus. Portare messa a fuoco automatica in scena diminuisce il tempo totale di ritardo più in linea con un PAMPs tipiche fotocamere digitali. Fonti per fotocamera digitale Testing I seguenti siti web offrono test dettagliato delle macchine fotografiche digitali, tra cui ritardo allo scatto. La qualità dei test variano, ma le configurazioni di prova utilizzati in ciascuno dei seguenti siti sono ragionevoli per un punto di partenza: lettori Commenti: Si prega di lasciare i vostri commenti o suggerimenti di seguito Johnny V. quotHep Catquot Brennan Good Day Spero che tutti stanno godendo una piacevole uno. Come da Commenter Liliken: Che cosa circa il ritardo tra scattare foto questo è quello frustrante per me ora. Ho prendere una foto e aspettare fino a quando la fotocamera si prepara a prendere il prossimo. Come è che il ritardo chiamato Grazie. Sì Che può essere un GAL molto inquietante pure. Per un esempio estremo, prendere un Sony Mavica 2003 con il mini-CD-RW interno per la registrazione di foto. Si scatta una foto e l'unità deve elaborare i dati e poi scrivere in un mini-CD-RW. Sono sicuro che tutti possono immaginare quanto tempo e frustrante quel momento potrebbe essere. Mi capita di avere un vecchio Mavica, prende ancora grandi foto, ma ora la sua relegato in casi di emergenza, e di conversazione, perché il vero Lag totale è omicidio. Vorrei chiamare il numero citato qui: Lag processo. E credo che il numero di processo Lag dovrebbe essere incluso con Lag totale. Perché questo è theee Numero i thats davvero causando tutta la frustrazione Premere il pulsante - attendere Focus - Rilascio di otturatore - attendere Processing - Ripeti. Nel frattempo, i momenti e colpi scompaiono nella storia per l'eternità. per non essere mai più visto. Io non ritengono che i produttori stanno andando a fare questi numeri facilmente disponibili. Sembra che il suo fino a uno per fare ricerche approfondite, e sfogliare numerosi siti e forum per i dati. ma come si vede qui. è difficile trovare un elenco completo. Ho trovato un po 'di dati su SnapSort e (che ci crediate o no) BestBuy. BestBuy ha uno dei migliori grafici di confronto fotocamera digitale Ive ha trovato ancora. Ha lista di buone dimensioni di filtri per la ricerca di un gruppo di telecamere da confrontare. Poi, spuntare le telecamere che si desidera confrontare, fino a 4 o 5, e quindi fare clic su Confronta e youll ottenere le specifiche per ogni telecamera, fianco a fianco per un facile confronto. Per esempio: Ho filtrato Samsung, sensibilità alla luce bassa, Burst Mode, fino a 200, Wi-Fi. ottenuto un elenco di telecamere. rispetto 2. scelto un Samsung WB350F. Boom Ease-as-piselli Buona fortuna Felice PhotoBugging godere di tutti Buon lista. Tutti i dettagli sono disponibili sul D7000 Nikon ha chiunque fatto alcun lavoro in ritardo associato con l'attivazione diretta di unità flash Ciao ti ringrazio molto per questo eccellente informazioni molto utili e ben scritto. Siamo alla ricerca di una nuova macchina fotografica. Abbiamo alrarsi due Sony Cybershot fino a kwow (non che buono per quanto riguarda pre-messa a fuoco e ritardo di scatto). Stiamo considerando di acquistare un Sony HX 300 o una NIKON P520. Che dire di loro per quanto riguarda totale lag Grazie in anticipo per qualsiasi informazione o opinione si può avere. Ho guardato il grafico ed i numeri non sono d'accordo con il lato con l'esperienza del mondo reale lato. Ad esempio, il grafico indica la Canon 10D, 20D e Rebel XT hanno ritardo di scatto totale più veloce di un ID Mark II. Ho una Canon 10D, 20D e 1D Mark II e vi posso assicurare che c'è un mondo di differenza, con la 1D Mark II di essere straordinariamente veloce di qualsiasi di queste telecamere. Ho guardato i riferimenti su alcune fotocamere, e vedo che hai utilizzato i dati da immagini di risorse, e guardando i dati che la descrizione sembra ragionevole, i dati in fatto deve essere in errore. Una possibilità è che l'obiettivo utilizzato nelle prove (non un obiettivo L) è un fattore limitante, non la fotocamera. Esempio: la 1D Mark II è incredibilmente veloce rispetto alla 10D utilizzando le stesse lenti sullo stesso argomento, (confrontando più lenti). Attualmente, lo faccio fotografia naturalistica con una 1D Mark II con una 10D come backup, spesso commutazione lenti (ad esempio 500 millimetri f A L su un treppiede a 300 mm f4 L è tenuto a mano). Per valutare la 10D ritardo totale a 0,189 secondi e la 1D Mark II a 0,235 secondi è semplicemente sbagliato, a meno che non si mette la lente messa a fuoco automatica più veloce sulla 10D e la più lenta della lente possibile sulla 1D Mark II. Io sparo un sacco di azione della fauna selvatica, e il tempo di risposta sulla 1D Mark II è ben al di sotto 0,1 secondi (tempo totale di ritardo nella mia esperienza in molteplici condizioni di ripresa). La 10D si sente come un punto lento e sparare in confronto. In condizioni di azione del mondo reale, avrei due problemi con la 10D: 1) l'azione irregolare (ad esempio, uccelli in volo) con uno sfondo complesso (ad esempio alberi lontani) ha difficoltà a bloccare sul soggetto e non lo sfondo, e 2) mentre il monitoraggio un soggetto, se il punto di messa a fuoco viene spostata fuori tema (ad esempio a causa della mia incapacità di seguire il movimento irregolare), la fotocamera non sarebbe mai riconquistare attenzione fino a quando il soggetto fermato. Sul 1D Mark II, non ho questi problemi. Rapporti da persone nel campo dire la 20D ha gli stessi problemi come la 10D. Ma con la 1D Mark II, posso perdere e riacquistare il punto di messa a fuoco su un soggetto in movimento in quello che sembra ben sotto 0,1 secondi. La precisione di messa a fuoco è molto meglio sul 1DII anche (avendo avuto più di 50 di scene d'azione fuoco su un 10D, quasi tutti in buona messa a fuoco con il 1DII) con grandi uccelli tipici in volo (ad esempio aquile, gru, aironi). Così, il vostro tavolo impulseadventurephotoshutter-lag. html è altamente sospetto, a prescindere dalla fonte dei dati. Roger (foto a: clarkvision) Ciao Roger - Grazie per l'ottimo controllo sulle prestazioni al di fuori di ciò che i numeri sembrerebbe implicare. Credo che l'unica misura equa per scopi di confronto può essere il ritardo di scatto. Non ritardo totale come derivato da una media dei risultati dei test. Questa è la ragione per cui elenco i limiti inferiore e superiore risultanti insieme con la media per mostrare la deviazione. Compresa la messa a fuoco automatica nel tempo totale di ritardo è fortemente dipendente della modalità AF, la selezione dell'obiettivo e contrasto della scena come giustamente sottolineato Youll nota che i siti di recensioni (3 di loro, non solo l'imaging di risorse) tutte le misure previste nella gamma 230 a 240 ms per la Canon 1D Mk II. Tuttavia, si può vedere che i risultati riportati per la 10D e 20D hanno una diffusione molto più ampia, da 146 fino a 240 ms elencati per la Canon 1D mk II. Così, mentre la media potrebbe mostrare come 189, il valore di confronto equo potrebbe essere i 240 ms (identici con la Canon 1D mkII). I dont necessariamente d'accordo che i numeri sono corretti. Prendendo le maggiori tempi totali di ritardo nel confronto produrrebbe risultati simili, ma sono probabilmente catturato in un ambiente molto sintetico (target statico ad alto contrasto in un ambiente ben illuminato). Naturalmente la tua esperienza nel mondo reale potrebbe evidenziare la debolezza nei tempi autofocus 10D e 20D, dove servo motion tracking e condizioni di basso contrasto possono davvero degradare la 10D o 20DS migliori prestazioni nel caso. Detto questo, il ritardo di scatto è infatti segnalato come significativamente più veloce sulla 1D Mark II rispetto alle altre fotocamere prosumer. Idealmente, avremmo un obiettivo, confronto riproducibile di otturatore totale ritardi con la stessa messa a punto e l'obiettivo, ma con scenari tipici del mondo reale, ma questo è fuori dal campo di applicazione della messa a punto per la maggior parte dei revisori della fotocamera. Avrebbero bisogno di un impianto meccanizzato in grado di riprodurre il movimento, con un po 'contatore digitale nella scena dell'immagine (per valutare il vero ritardo con precisione) e un innesco a distanza di rilascio. Se qualcuno impostare questa funzione per la maggior parte delle DSLR e con lenti comparabili (ad esempio L su Canon), questo sarebbe fantastico. Purtroppo, penso bene accontentarsi di un campione di risultati provenienti da diversi revisori, tutti con configurazioni leggermente diverse. La speranza è che con abbastanza recensioni e risultati, le medie saranno utili come punto di partenza approssimativa di confronto. Ancora una volta, la ringrazio molto per la fornitura di una certa comprensione del mondo reale nella prestazione youve osservato tra le telecamere. Questo feedback è spesso molto più utile di un altro punto di dati grande galleria sintetico, BTW Un Mans professionali benefici duro lavoro di milioni di uomini e donne. Grazie anche qualcuno potrebbe gentilmente quale è il veloce all'interno di una fascia di prezzo di U300. Ho bisogno di una telecamera veloce per filmare i miei due bambini iperattivi. Il grafico potrebbe essere perfetto se ha un'altra colonna che mostra prezzi. Grazie, Robin Purtroppo, non posso aggiungere i prezzi, come non sarei mai stato in grado di mantenere la tabella di up-to-date con tutte le variazioni dei prezzi di strada oltre time. Using R per Time Series Analysis Time Series Analysis Questo libretto si itells come utilizzare il software statistico R per effettuare alcune semplici analisi che sono comuni per l'analisi dei dati di serie temporali. Questo libretto presuppone che il lettore abbia una conoscenza di base delle analisi di serie temporali, e il focus principale del libretto non è quello di spiegare l'analisi di serie temporali, ma piuttosto di spiegare come effettuare queste analisi utilizzando R. Se siete nuovi alla serie temporali analisi, e vogliono saperne di più su uno qualsiasi dei concetti presentati qui, vi consiglio vivamente il libro Open University 8220Time series8221 (codice prodotto M24902), disponibile presso dalla Open University shop. In questo opuscolo, userò insiemi di dati di serie temporali che sono stati gentilmente messi a disposizione da Rob Hyndman nella sua biblioteca dati di serie temporali a robjhyndmanTSDL. Se vi piace questo opuscolo, come si può anche controllare il mio libretto di utilizzare R per le statistiche biomediche, a-little-book-of-r-for-biomedical-statistics. readthedocs. org. e il mio libretto di utilizzare R per l'analisi multivariata, little-book-of-r-for-multivariate-analysis. readthedocs. org. Lettura dati di serie storiche La prima cosa che si vuole fare per analizzare i dati di serie storiche sarà di leggerlo in R, e per tracciare le serie storiche. È possibile leggere i dati in R utilizzando la funzione di scansione (), che presuppone che i dati per i punti di tempo successivi è in un semplice file di testo con una colonna. Ad esempio, il file robjhyndmantsdldatamisckings. dat contiene i dati relativi all'età della morte dei re successivi di Inghilterra, a partire Guglielmo il Conquistatore (fonte originale: Hipel e Mcleod, 1994). Il set di dati è simile al seguente: sono stati mostrati solo le prime righe del file. Le prime tre righe contengono qualche commento sui dati, e noi vogliamo ignorare questo quando leggiamo i dati in R. Possiamo usare questo utilizzando il parametro 8220skip8221 della funzione di scansione (), che specifica il numero di righe in cima il file di ignorare. Per leggere il file in R, ignorando le prime tre righe, digitiamo: in questo caso l'età della morte di 42 re successivi di Inghilterra è stato letto nella variabile 8216kings8217. Dopo aver letto i dati di serie temporali in R, il passo successivo è quello di memorizzare i dati in un oggetto serie temporale in R, in modo da poter usare R8217s molte funzioni per l'analisi dei dati di serie temporali. Per memorizzare i dati in un oggetto serie temporale, si usa la funzione ts () in R. Ad esempio, per memorizzare i dati nella variabile 8216kings8217 come oggetto serie temporale in R, digitiamo: a volte i dati di serie temporali set che si sono possono essere stati raccolti ad intervalli regolari, che sono state meno di un anno, per esempio, mensile o trimestrale. In questo caso, è possibile specificare il numero di volte in cui i dati sono stati raccolti per anno utilizzando il parametro 8216frequency8217 nei ts funzione (). Per i dati mensili di serie temporali, è possibile impostare frequency12, mentre per i dati di serie temporali trimestrali, si imposta frequency4. È inoltre possibile specificare il primo anno che i dati sono stati raccolti, e il primo intervallo in quell'anno utilizzando il parametro 8216start8217 nei ts funzione (). Ad esempio, se il primo punto di dati corrisponde al secondo trimestre del 1986, è necessario impostare startc (1986,2). Un esempio è un insieme di dati del numero di nascite al mese in città di New York, da gennaio 1946 al dicembre 1959 (originariamente raccolti da Newton). Questi dati sono disponibili nel file robjhyndmantsdldatadatanybirths. dat Possiamo leggere i dati in R, e conservarla come un oggetto serie temporale, digitando: Allo stesso modo, il file contiene robjhyndmantsdldatadatafancy. dat vendite mensili per un negozio di souvenir in una città balneare in Queensland, in Australia, per il gennaio 1987-dicembre 1993 (dati originali da Wheelwright e Hyndman, 1998). Siamo in grado di leggere i dati in R digitando: Tracciato Time Series Dopo aver letto una serie storica in R, il passo successivo è di solito per fare un grafico dei dati di serie temporali, che si può fare con il plot. ts () funzione in R. ad esempio, per tracciare le serie storiche dell'età della morte di 42 re successivi di Inghilterra, digitiamo: possiamo vedere dalla trama momento che questa serie di tempo potrebbe probabilmente essere descritta utilizzando un modello additivo, dal momento che le fluttuazioni casuali i dati sono più o meno costante in termini di dimensioni nel tempo. Allo stesso modo, per tracciare la serie storica del numero delle nascite al mese in città di New York, digitiamo: Possiamo vedere da questa serie storica che ci sembra essere variazione stagionale nel numero delle nascite al mese: c'è un picco di ogni estate , e un trogolo ogni inverno. Ancora una volta, sembra che questa serie temporale potrebbe probabilmente essere descritta utilizzando un modello additivo, come le variazioni stagionali sono pressoché costante di dimensioni nel tempo e non sembrano dipendere dal livello della serie temporale, e le fluttuazioni casuali sembrano anche essere più o meno costante in termini di dimensioni nel tempo. Allo stesso modo, per tracciare la serie storica delle vendite mensili per il negozio di souvenir in una città balneare nel Queensland, in Australia, digitiamo: in questo caso, sembra che un modello additivo non è appropriato per descrivere questa serie di tempo, dal momento che la dimensione delle fluttuazioni stagionali e le fluttuazioni casuali sembrano aumentare con il livello della serie temporale. Pertanto, potrebbe essere necessario trasformare la serie temporale al fine di ottenere una serie temporale trasformato che può essere descritta utilizzando un modello additivo. Per esempio, possiamo trasformare la serie temporale calcolando il logaritmo naturale dei dati originali: Qui possiamo vedere che la dimensione delle fluttuazioni stagionali e le fluttuazioni casuali nella serie temporale log-trasformata sembrano essere abbastanza costante nel tempo, e fare non dipende dal livello di serie temporale. Così, le serie storiche di log-trasformati probabilmente può essere descritto utilizzando un modello additivo. Decomposizione Serie Time decomposizione una serie temporale significa separa nei suoi componenti costitutivi, che sono di solito un componente tendenza e una componente irregolare, e se si tratta di una serie temporale stagionale, una componente stagionale. Scomponendo i dati non stagionale Una serie temporali non stagionali è costituito da una componente di trend e una componente irregolare. Decomposizione serie temporali comporta cercando di separare la serie temporale in queste componenti, cioè, la stima del componente tendenza e il componente irregolare. Per stimare la componente andamento di una serie temporale non stagionale che può essere descritta utilizzando un modello additivo, è comune utilizzare un metodo di smoothing, come ad esempio il calcolo della media mobile semplice della serie temporale. La funzione SMA () nel pacchetto 8220TTR8221 R può essere utilizzato per lisciare dati di serie temporali utilizzando una media mobile semplice. Per utilizzare questa funzione, abbiamo prima bisogno di installare il pacchetto 8220TTR8221 R (per le istruzioni su come installare un pacchetto R, vedere Come installare un pacchetto R). Una volta installato il pacchetto 8220TTR8221 R, è possibile caricare il pacchetto 8220TTR8221 R digitando: È quindi possibile utilizzare il () 8221 Funzione 8220SMA per lisciare dati di serie temporali. Per utilizzare la funzione SMA (), è necessario specificare l'ordine (arco) della media mobile semplice, utilizzando il parametro 8220n8221. Ad esempio, per calcolare una media mobile semplice di ordine 5, abbiamo impostato n5 nella funzione SMA (). Ad esempio, come discusso in precedenza, la serie storica dell'età della morte di 42 re successivi di Inghilterra sembra è non stagionale, e probabilmente può essere descritto utilizzando un modello additivo, dal momento che le fluttuazioni casuali nei dati sono pressoché costante in termini di dimensioni over tempo: Quindi, possiamo cercare di stimare la componente di trend di questa serie tempo lisciando utilizzando una media mobile semplice. Per smussare le serie storiche con una semplice media mobile di ordine 3, e tracciare i dati di serie temporali levigati, digitiamo: Sembra essere ancora un bel po 'di fluttuazioni casuali nella serie storica lisciato con una semplice media mobile di ordine 3. Così, per stimare la componente di trend, più precisamente, potremmo provare a lisciare i dati con una semplice media mobile di ordine superiore. Questo richiede un po 'di tentativi ed errori, per trovare la giusta quantità di levigatura. Ad esempio, possiamo provare a utilizzare un semplice media mobile di ordine 8: I dati lisciato con una media mobile semplice di ordine 8 fornisce un quadro più chiaro della componente di trend, e possiamo vedere che l'età della morte dei re inglesi sembra sono diminuiti da circa 55 anni per circa 38 anni durante il regno dei primi 20 re, per poi aumentare dopo che per circa 73 anni dalla fine del regno del re 40 ° in serie storica. Scomponendo i dati stagionali Una serie temporale di stagione è costituito da una componente di trend, una componente stagionale e una componente irregolare. Decomposizione serie tempo significa che separa la serie temporale in queste tre componenti: ovvero stimando questi tre componenti. Per stimare la componente di trend e la componente stagionale di una serie storica di stagione che può essere descritto utilizzando un modello additivo, si può utilizzare il () 8221 funzione 8220decompose in R. Questa funzione calcola il trend, stagionalità, e fattori erratici di una serie storica che può essere descritto mediante un modello additivo. La 8220decompose function () 8221 restituisce un oggetto lista come risultato, dove le stime della componente stagionale, componente di trend e componente irregolare sono memorizzati in elementi di nome di che gli oggetti della lista, denominata 8220seasonal8221, 8220trend8221, e 8220random8221 rispettivamente. Ad esempio, come discusso in precedenza, la serie storica del numero delle nascite al mese in città di New York è stagionale, con un picco ogni estate e trogolo ogni inverno, e probabilmente può essere descritto utilizzando un modello additivo in quanto le fluttuazioni stagionali e casuali sembrano essere più o meno costante in termini di dimensioni nel tempo: Per stimare la tendenza, componenti stagionali e irregolari di questa serie tempo, tipo: I valori stimati della stagione, tendenza e componenti irregolari vengono ora memorizzati nelle variabili birthstimeseriescomponentsseasonal, birthstimeseriescomponentstrend e birthstimeseriescomponentsrandom. For example, we can print out the estimated values of the seasonal component by typing: The estimated seasonal factors are given for the months January-December, and are the same for each year. The largest seasonal factor is for July (about 1.46), and the lowest is for February (about -2.08), indicating that there seems to be a peak in births in July and a trough in births in February each year. We can plot the estimated trend, seasonal, and irregular components of the time series by using the 8220plot()8221 function, for example: The plot above shows the original time series (top), the estimated trend component (second from top), the estimated seasonal component (third from top), and the estimated irregular component (bottom). We see that the estimated trend component shows a small decrease from about 24 in 1947 to about 22 in 1948, followed by a steady increase from then on to about 27 in 1959. Seasonally Adjusting If you have a seasonal time series that can be described using an additive model, you can seasonally adjust the time series by estimating the seasonal component, and subtracting the estimated seasonal component from the original time series. We can do this using the estimate of the seasonal component calculated by the 8220decompose()8221 function. For example, to seasonally adjust the time series of the number of births per month in New York city, we can estimate the seasonal component using 8220decompose()8221, and then subtract the seasonal component from the original time series: We can then plot the seasonally adjusted time series using the 8220plot()8221 function, by typing: You can see that the seasonal variation has been removed from the seasonally adjusted time series. The seasonally adjusted time series now just contains the trend component and an irregular component. Forecasts using Exponential Smoothing Exponential smoothing can be used to make short-term forecasts for time series data. Simple Exponential Smoothing If you have a time series that can be described using an additive model with constant level and no seasonality, you can use simple exponential smoothing to make short-term forecasts. The simple exponential smoothing method provides a way of estimating the level at the current time point. Smoothing is controlled by the parameter alpha for the estimate of the level at the current time point. The value of alpha lies between 0 and 1. Values of alpha that are close to 0 mean that little weight is placed on the most recent observations when making forecasts of future values. For example, the file robjhyndmantsdldatahurstprecip1.dat contains total annual rainfall in inches for London, from 1813-1912 (original data from Hipel and McLeod, 1994). We can read the data into R and plot it by typing: You can see from the plot that there is roughly constant level (the mean stays constant at about 25 inches). The random fluctuations in the time series seem to be roughly constant in size over time, so it is probably appropriate to describe the data using an additive model. Thus, we can make forecasts using simple exponential smoothing. To make forecasts using simple exponential smoothing in R, we can fit a simple exponential smoothing predictive model using the 8220HoltWinters()8221 function in R. To use HoltWinters() for simple exponential smoothing, we need to set the parameters betaFALSE and gammaFALSE in the HoltWinters() function (the beta and gamma parameters are used for Holt8217s exponential smoothing, or Holt-Winters exponential smoothing, as described below). The HoltWinters() function returns a list variable, that contains several named elements. For example, to use simple exponential smoothing to make forecasts for the time series of annual rainfall in London, we type: The output of HoltWinters() tells us that the estimated value of the alpha parameter is about 0.024. This is very close to zero, telling us that the forecasts are based on both recent and less recent observations (although somewhat more weight is placed on recent observations). By default, HoltWinters() just makes forecasts for the same time period covered by our original time series. In this case, our original time series included rainfall for London from 1813-1912, so the forecasts are also for 1813-1912. In the example above, we have stored the output of the HoltWinters() function in the list variable 8220rainseriesforecasts8221. The forecasts made by HoltWinters() are stored in a named element of this list variable called 8220fitted8221, so we can get their values by typing: We can plot the original time series against the forecasts by typing: The plot shows the original time series in black, and the forecasts as a red line. The time series of forecasts is much smoother than the time series of the original data here. As a measure of the accuracy of the forecasts, we can calculate the sum of squared errors for the in-sample forecast errors, that is, the forecast errors for the time period covered by our original time series. The sum-of-squared-errors is stored in a named element of the list variable 8220rainseriesforecasts8221 called 8220SSE8221, so we can get its value by typing: That is, here the sum-of-squared-errors is 1828.855. It is common in simple exponential smoothing to use the first value in the time series as the initial value for the level. For example, in the time series for rainfall in London, the first value is 23.56 (inches) for rainfall in 1813. You can specify the initial value for the level in the HoltWinters() function by using the 8220l. start8221 parameter. For example, to make forecasts with the initial value of the level set to 23.56, we type: As explained above, by default HoltWinters() just makes forecasts for the time period covered by the original data, which is 1813-1912 for the rainfall time series. We can make forecasts for further time points by using the 8220forecast. HoltWinters()8221 function in the R 8220forecast8221 package. To use the forecast. HoltWinters() function, we first need to install the 8220forecast8221 R package (for instructions on how to install an R package, see How to install an R package ). Once you have installed the 8220forecast8221 R package, you can load the 8220forecast8221 R package by typing: When using the forecast. HoltWinters() function, as its first argument (input), you pass it the predictive model that you have already fitted using the HoltWinters() function. For example, in the case of the rainfall time series, we stored the predictive model made using HoltWinters() in the variable 8220rainseriesforecasts8221. You specify how many further time points you want to make forecasts for by using the 8220h8221 parameter in forecast. HoltWinters(). For example, to make a forecast of rainfall for the years 1814-1820 (8 more years) using forecast. HoltWinters(), we type: The forecast. HoltWinters() function gives you the forecast for a year, a 80 prediction interval for the forecast, and a 95 prediction interval for the forecast. For example, the forecasted rainfall for 1920 is about 24.68 inches, with a 95 prediction interval of (16.24, 33.11). To plot the predictions made by forecast. HoltWinters(), we can use the 8220plot. forecast()8221 function: Here the forecasts for 1913-1920 are plotted as a blue line, the 80 prediction interval as an orange shaded area, and the 95 prediction interval as a yellow shaded area. The 8216forecast errors8217 are calculated as the observed values minus predicted values, for each time point. We can only calculate the forecast errors for the time period covered by our original time series, which is 1813-1912 for the rainfall data. As mentioned above, one measure of the accuracy of the predictive model is the sum-of-squared-errors (SSE) for the in-sample forecast errors. The in-sample forecast errors are stored in the named element 8220residuals8221 of the list variable returned by forecast. HoltWinters(). If the predictive model cannot be improved upon, there should be no correlations between forecast errors for successive predictions. In other words, if there are correlations between forecast errors for successive predictions, it is likely that the simple exponential smoothing forecasts could be improved upon by another forecasting technique. To figure out whether this is the case, we can obtain a correlogram of the in-sample forecast errors for lags 1-20. We can calculate a correlogram of the forecast errors using the 8220acf()8221 function in R. To specify the maximum lag that we want to look at, we use the 8220lag. max8221 parameter in acf(). For example, to calculate a correlogram of the in-sample forecast errors for the London rainfall data for lags 1-20, we type: You can see from the sample correlogram that the autocorrelation at lag 3 is just touching the significance bounds. To test whether there is significant evidence for non-zero correlations at lags 1-20, we can carry out a Ljung-Box test. This can be done in R using the 8220Box. test()8221, function. The maximum lag that we want to look at is specified using the 8220lag8221 parameter in the Box. test() function. For example, to test whether there are non-zero autocorrelations at lags 1-20, for the in-sample forecast errors for London rainfall data, we type: Here the Ljung-Box test statistic is 17.4, and the p-value is 0.6, so there is little evidence of non-zero autocorrelations in the in-sample forecast errors at lags 1-20. To be sure that the predictive model cannot be improved upon, it is also a good idea to check whether the forecast errors are normally distributed with mean zero and constant variance. To check whether the forecast errors have constant variance, we can make a time plot of the in-sample forecast errors: The plot shows that the in-sample forecast errors seem to have roughly constant variance over time, although the size of the fluctuations in the start of the time series (1820-1830) may be slightly less than that at later dates (eg. 1840-1850). To check whether the forecast errors are normally distributed with mean zero, we can plot a histogram of the forecast errors, with an overlaid normal curve that has mean zero and the same standard deviation as the distribution of forecast errors. To do this, we can define an R function 8220plotForecastErrors()8221, below: You will have to copy the function above into R in order to use it. You can then use plotForecastErrors() to plot a histogram (with overlaid normal curve) of the forecast errors for the rainfall predictions: The plot shows that the distribution of forecast errors is roughly centred on zero, and is more or less normally distributed, although it seems to be slightly skewed to the right compared to a normal curve. However, the right skew is relatively small, and so it is plausible that the forecast errors are normally distributed with mean zero. The Ljung-Box test showed that there is little evidence of non-zero autocorrelations in the in-sample forecast errors, and the distribution of forecast errors seems to be normally distributed with mean zero. This suggests that the simple exponential smoothing method provides an adequate predictive model for London rainfall, which probably cannot be improved upon. Furthermore, the assumptions that the 80 and 95 predictions intervals were based upon (that there are no autocorrelations in the forecast errors, and the forecast errors are normally distributed with mean zero and constant variance) are probably valid. Holt8217s Exponential Smoothing If you have a time series that can be described using an additive model with increasing or decreasing trend and no seasonality, you can use Holt8217s exponential smoothing to make short-term forecasts. Holt8217s exponential smoothing estimates the level and slope at the current time point. Smoothing is controlled by two parameters, alpha, for the estimate of the level at the current time point, and beta for the estimate of the slope b of the trend component at the current time point. As with simple exponential smoothing, the paramters alpha and beta have values between 0 and 1, and values that are close to 0 mean that little weight is placed on the most recent observations when making forecasts of future values. An example of a time series that can probably be described using an additive model with a trend and no seasonality is the time series of the annual diameter of women8217s skirts at the hem, from 1866 to 1911. The data is available in the file robjhyndmantsdldatarobertsskirts. dat (original data from Hipel and McLeod, 1994). We can read in and plot the data in R by typing: We can see from the plot that there was an increase in hem diameter from about 600 in 1866 to about 1050 in 1880, and that afterwards the hem diameter decreased to about 520 in 1911. To make forecasts, we can fit a predictive model using the HoltWinters() function in R. To use HoltWinters() for Holt8217s exponential smoothing, we need to set the parameter gammaFALSE (the gamma parameter is used for Holt-Winters exponential smoothing, as described below). For example, to use Holt8217s exponential smoothing to fit a predictive model for skirt hem diameter, we type: The estimated value of alpha is 0.84, and of beta is 1.00. These are both high, telling us that both the estimate of the current value of the level, and of the slope b of the trend component, are based mostly upon very recent observations in the time series. This makes good intuitive sense, since the level and the slope of the time series both change quite a lot over time. The value of the sum-of-squared-errors for the in-sample forecast errors is 16954. We can plot the original time series as a black line, with the forecasted values as a red line on top of that, by typing: We can see from the picture that the in-sample forecasts agree pretty well with the observed values, although they tend to lag behind the observed values a little bit. If you wish, you can specify the initial values of the level and the slope b of the trend component by using the 8220l. start8221 and 8220b. start8221 arguments for the HoltWinters() function. It is common to set the initial value of the level to the first value in the time series (608 for the skirts data), and the initial value of the slope to the second value minus the first value (9 for the skirts data). For example, to fit a predictive model to the skirt hem data using Holt8217s exponential smoothing, with initial values of 608 for the level and 9 for the slope b of the trend component, we type: As for simple exponential smoothing, we can make forecasts for future times not covered by the original time series by using the forecast. HoltWinters() function in the 8220forecast8221 package. For example, our time series data for skirt hems was for 1866 to 1911, so we can make predictions for 1912 to 1930 (19 more data points), and plot them, by typing: The forecasts are shown as a blue line, with the 80 prediction intervals as an orange shaded area, and the 95 prediction intervals as a yellow shaded area. As for simple exponential smoothing, we can check whether the predictive model could be improved upon by checking whether the in-sample forecast errors show non-zero autocorrelations at lags 1-20. For example, for the skirt hem data, we can make a correlogram, and carry out the Ljung-Box test, by typing: Here the correlogram shows that the sample autocorrelation for the in-sample forecast errors at lag 5 exceeds the significance bounds. However, we would expect one in 20 of the autocorrelations for the first twenty lags to exceed the 95 significance bounds by chance alone. Indeed, when we carry out the Ljung-Box test, the p-value is 0.47, indicating that there is little evidence of non-zero autocorrelations in the in-sample forecast errors at lags 1-20. As for simple exponential smoothing, we should also check that the forecast errors have constant variance over time, and are normally distributed with mean zero. We can do this by making a time plot of forecast errors, and a histogram of the distribution of forecast errors with an overlaid normal curve: The time plot of forecast errors shows that the forecast errors have roughly constant variance over time. The histogram of forecast errors show that it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Thus, the Ljung-Box test shows that there is little evidence of autocorrelations in the forecast errors, while the time plot and histogram of forecast errors show that it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Therefore, we can conclude that Holt8217s exponential smoothing provides an adequate predictive model for skirt hem diameters, which probably cannot be improved upon. In addition, it means that the assumptions that the 80 and 95 predictions intervals were based upon are probably valid. Holt-Winters Exponential Smoothing If you have a time series that can be described using an additive model with increasing or decreasing trend and seasonality, you can use Holt-Winters exponential smoothing to make short-term forecasts. Holt-Winters exponential smoothing estimates the level, slope and seasonal component at the current time point. Smoothing is controlled by three parameters: alpha, beta, and gamma, for the estimates of the level, slope b of the trend component, and the seasonal component, respectively, at the current time point. The parameters alpha, beta and gamma all have values between 0 and 1, and values that are close to 0 mean that relatively little weight is placed on the most recent observations when making forecasts of future values. An example of a time series that can probably be described using an additive model with a trend and seasonality is the time series of the log of monthly sales for the souvenir shop at a beach resort town in Queensland, Australia (discussed above): To make forecasts, we can fit a predictive model using the HoltWinters() function. For example, to fit a predictive model for the log of the monthly sales in the souvenir shop, we type: The estimated values of alpha, beta and gamma are 0.41, 0.00, and 0.96, respectively. The value of alpha (0.41) is relatively low, indicating that the estimate of the level at the current time point is based upon both recent observations and some observations in the more distant past. The value of beta is 0.00, indicating that the estimate of the slope b of the trend component is not updated over the time series, and instead is set equal to its initial value. This makes good intuitive sense, as the level changes quite a bit over the time series, but the slope b of the trend component remains roughly the same. In contrast, the value of gamma (0.96) is high, indicating that the estimate of the seasonal component at the current time point is just based upon very recent observations. As for simple exponential smoothing and Holt8217s exponential smoothing, we can plot the original time series as a black line, with the forecasted values as a red line on top of that: We see from the plot that the Holt-Winters exponential method is very successful in predicting the seasonal peaks, which occur roughly in November every year. To make forecasts for future times not included in the original time series, we use the 8220forecast. HoltWinters()8221 function in the 8220forecast8221 package. For example, the original data for the souvenir sales is from January 1987 to December 1993. If we wanted to make forecasts for January 1994 to December 1998 (48 more months), and plot the forecasts, we would type: The forecasts are shown as a blue line, and the orange and yellow shaded areas show 80 and 95 prediction intervals, respectively. We can investigate whether the predictive model can be improved upon by checking whether the in-sample forecast errors show non-zero autocorrelations at lags 1-20, by making a correlogram and carrying out the Ljung-Box test: The correlogram shows that the autocorrelations for the in-sample forecast errors do not exceed the significance bounds for lags 1-20. Furthermore, the p-value for Ljung-Box test is 0.6, indicating that there is little evidence of non-zero autocorrelations at lags 1-20. We can check whether the forecast errors have constant variance over time, and are normally distributed with mean zero, by making a time plot of the forecast errors and a histogram (with overlaid normal curve): From the time plot, it appears plausible that the forecast errors have constant variance over time. From the histogram of forecast errors, it seems plausible that the forecast errors are normally distributed with mean zero. Thus, there is little evidence of autocorrelation at lags 1-20 for the forecast errors, and the forecast errors appear to be normally distributed with mean zero and constant variance over time. This suggests that Holt-Winters exponential smoothing provides an adequate predictive model of the log of sales at the souvenir shop, which probably cannot be improved upon. Furthermore, the assumptions upon which the prediction intervals were based are probably valid. ARIMA Models Exponential smoothing methods are useful for making forecasts, and make no assumptions about the correlations between successive values of the time series. However, if you want to make prediction intervals for forecasts made using exponential smoothing methods, the prediction intervals require that the forecast errors are uncorrelated and are normally distributed with mean zero and constant variance. While exponential smoothing methods do not make any assumptions about correlations between successive values of the time series, in some cases you can make a better predictive model by taking correlations in the data into account. Autoregressive Integrated Moving Average (ARIMA) models include an explicit statistical model for the irregular component of a time series, that allows for non-zero autocorrelations in the irregular component. Differencing a Time Series ARIMA models are defined for stationary time series. Therefore, if you start off with a non-stationary time series, you will first need to 8216difference8217 the time series until you obtain a stationary time series. If you have to difference the time series d times to obtain a stationary series, then you have an ARIMA(p, d,q) model, where d is the order of differencing used. You can difference a time series using the 8220diff()8221 function in R. For example, the time series of the annual diameter of women8217s skirts at the hem, from 1866 to 1911 is not stationary in mean, as the level changes a lot over time: We can difference the time series (which we stored in 8220skirtsseries8221, see above) once, and plot the differenced series, by typing: The resulting time series of first differences (above) does not appear to be stationary in mean. Therefore, we can difference the time series twice, to see if that gives us a stationary time series: Formal tests for stationarity Formal tests for stationarity called 8220unit root tests8221 are available in the fUnitRoots package, available on CRAN, but will not be discussed here. The time series of second differences (above) does appear to be stationary in mean and variance, as the level of the series stays roughly constant over time, and the variance of the series appears roughly constant over time. Thus, it appears that we need to difference the time series of the diameter of skirts twice in order to achieve a stationary series. If you need to difference your original time series data d times in order to obtain a stationary time series, this means that you can use an ARIMA(p, d,q) model for your time series, where d is the order of differencing used. For example, for the time series of the diameter of women8217s skirts, we had to difference the time series twice, and so the order of differencing (d) is 2. This means that you can use an ARIMA(p,2,q) model for your time series. The next step is to figure out the values of p and q for the ARIMA model. Another example is the time series of the age of death of the successive kings of England (see above): From the time plot (above), we can see that the time series is not stationary in mean. To calculate the time series of first differences, and plot it, we type: The time series of first differences appears to be stationary in mean and variance, and so an ARIMA(p,1,q) model is probably appropriate for the time series of the age of death of the kings of England. By taking the time series of first differences, we have removed the trend component of the time series of the ages at death of the kings, and are left with an irregular component. We can now examine whether there are correlations between successive terms of this irregular component if so, this could help us to make a predictive model for the ages at death of the kings. Selecting a Candidate ARIMA Model If your time series is stationary, or if you have transformed it to a stationary time series by differencing d times, the next step is to select the appropriate ARIMA model, which means finding the values of most appropriate values of p and q for an ARIMA(p, d,q) model. To do this, you usually need to examine the correlogram and partial correlogram of the stationary time series. To plot a correlogram and partial correlogram, we can use the 8220acf()8221 and 8220pacf()8221 functions in R, respectively. To get the actual values of the autocorrelations and partial autocorrelations, we set 8220plotFALSE8221 in the 8220acf()8221 and 8220pacf()8221 functions. Example of the Ages at Death of the Kings of England For example, to plot the correlogram for lags 1-20 of the once differenced time series of the ages at death of the kings of England, and to get the values of the autocorrelations, we type: We see from the correlogram that the autocorrelation at lag 1 (-0.360) exceeds the significance bounds, but all other autocorrelations between lags 1-20 do not exceed the significance bounds. To plot the partial correlogram for lags 1-20 for the once differenced time series of the ages at death of the English kings, and get the values of the partial autocorrelations, we use the 8220pacf()8221 function, by typing: The partial correlogram shows that the partial autocorrelations at lags 1, 2 and 3 exceed the significance bounds, are negative, and are slowly decreasing in magnitude with increasing lag (lag 1: -0.360, lag 2: -0.335, lag 3:-0.321). The partial autocorrelations tail off to zero after lag 3. Since the correlogram is zero after lag 1, and the partial correlogram tails off to zero after lag 3, this means that the following ARMA (autoregressive moving average) models are possible for the time series of first differences: an ARMA(3,0) model, that is, an autoregressive model of order p3, since the partial autocorrelogram is zero after lag 3, and the autocorrelogram tails off to zero (although perhaps too abruptly for this model to be appropriate) an ARMA(0,1) model, that is, a moving average model of order q1, since the autocorrelogram is zero after lag 1 and the partial autocorrelogram tails off to zero an ARMA(p, q) model, that is, a mixed model with p and q greater than 0, since the autocorrelogram and partial correlogram tail off to zero (although the correlogram probably tails off to zero too abruptly for this model to be appropriate) We use the principle of parsimony to decide which model is best: that is, we assume that the model with the fewest parameters is best. The ARMA(3,0) model has 3 parameters, the ARMA(0,1) model has 1 parameter, and the ARMA(p, q) model has at least 2 parameters. Therefore, the ARMA(0,1) model is taken as the best model. An ARMA(0,1) model is a moving average model of order 1, or MA(1) model. This model can be written as: Xt - mu Zt - (theta Zt-1), where Xt is the stationary time series we are studying (the first differenced series of ages at death of English kings), mu is the mean of time series Xt, Zt is white noise with mean zero and constant variance, and theta is a parameter that can be estimated. A MA (moving average) model is usually used to model a time series that shows short-term dependencies between successive observations. Intuitively, it makes good sense that a MA model can be used to describe the irregular component in the time series of ages at death of English kings, as we might expect the age at death of a particular English king to have some effect on the ages at death of the next king or two, but not much effect on the ages at death of kings that reign much longer after that. Shortcut: the auto. arima() function The auto. arima() function can be used to find the appropriate ARIMA model, eg. type 8220library(forecast)8221, then 8220auto. arima(kings)8221. The output says an appropriate model is ARIMA(0,1,1). Since an ARMA(0,1) model (with p0, q1) is taken to be the best candidate model for the time series of first differences of the ages at death of English kings, then the original time series of the ages of death can be modelled using an ARIMA(0,1,1) model (with p0, d1, q1, where d is the order of differencing required). Example of the Volcanic Dust Veil in the Northern Hemisphere Let8217s take another example of selecting an appropriate ARIMA model. The file file robjhyndmantsdldataannualdvi. dat contains data on the volcanic dust veil index in the northern hemisphere, from 1500-1969 (original data from Hipel and Mcleod, 1994). This is a measure of the impact of volcanic eruptions8217 release of dust and aerosols into the environment. We can read it into R and make a time plot by typing: From the time plot, it appears that the random fluctuations in the time series are roughly constant in size over time, so an additive model is probably appropriate for describing this time series. Furthermore, the time series appears to be stationary in mean and variance, as its level and variance appear to be roughly constant over time. Therefore, we do not need to difference this series in order to fit an ARIMA model, but can fit an ARIMA model to the original series (the order of differencing required, d, is zero here). We can now plot a correlogram and partial correlogram for lags 1-20 to investigate what ARIMA model to use: We see from the correlogram that the autocorrelations for lags 1, 2 and 3 exceed the significance bounds, and that the autocorrelations tail off to zero after lag 3. The autocorrelations for lags 1, 2, 3 are positive, and decrease in magnitude with increasing lag (lag 1: 0.666, lag 2: 0.374, lag 3: 0.162). The autocorrelation for lags 19 and 20 exceed the significance bounds too, but it is likely that this is due to chance, since they just exceed the significance bounds (especially for lag 19), the autocorrelations for lags 4-18 do not exceed the signifiance bounds, and we would expect 1 in 20 lags to exceed the 95 significance bounds by chance alone. From the partial autocorrelogram, we see that the partial autocorrelation at lag 1 is positive and exceeds the significance bounds (0.666), while the partial autocorrelation at lag 2 is negative and also exceeds the significance bounds (-0.126). The partial autocorrelations tail off to zero after lag 2. Since the correlogram tails off to zero after lag 3, and the partial correlogram is zero after lag 2, the following ARMA models are possible for the time series: an ARMA(2,0) model, since the partial autocorrelogram is zero after lag 2, and the correlogram tails off to zero after lag 3, and the partial correlogram is zero after lag 2 an ARMA(0,3) model, since the autocorrelogram is zero after lag 3, and the partial correlogram tails off to zero (although perhaps too abruptly for this model to be appropriate) an ARMA(p, q) mixed model, since the correlogram and partial correlogram tail off to zero (although the partial correlogram perhaps tails off too abruptly for this model to be appropriate) Shortcut: the auto. arima() function Again, we can use auto. arima() to find an appropriate model, by typing 8220auto. arima(volcanodust)8221, which gives us ARIMA(1,0,2), which has 3 parameters. However, different criteria can be used to select a model (see auto. arima() help page). If we use the 8220bic8221 criterion, which penalises the number of parameters, we get ARIMA(2,0,0), which is ARMA(2,0): 8220auto. arima(volcanodust, ic8221bic8221)8221. The ARMA(2,0) model has 2 parameters, the ARMA(0,3) model has 3 parameters, and the ARMA(p, q) model has at least 2 parameters. Therefore, using the principle of parsimony, the ARMA(2,0) model and ARMA(p, q) model are equally good candidate models. An ARMA(2,0) model is an autoregressive model of order 2, or AR(2) model. This model can be written as: Xt - mu (Beta1 (Xt-1 - mu)) (Beta2 (Xt-2 - mu)) Zt, where Xt is the stationary time series we are studying (the time series of volcanic dust veil index), mu is the mean of time series Xt, Beta1 and Beta2 are parameters to be estimated, and Zt is white noise with mean zero and constant variance. An AR (autoregressive) model is usually used to model a time series which shows longer term dependencies between successive observations. Intuitively, it makes sense that an AR model could be used to describe the time series of volcanic dust veil index, as we would expect volcanic dust and aerosol levels in one year to affect those in much later years, since the dust and aerosols are unlikely to disappear quickly. If an ARMA(2,0) model (with p2, q0) is used to model the time series of volcanic dust veil index, it would mean that an ARIMA(2,0,0) model can be used (with p2, d0, q0, where d is the order of differencing required). Similarly, if an ARMA(p, q) mixed model is used, where p and q are both greater than zero, than an ARIMA(p,0,q) model can be used. Forecasting Using an ARIMA Model Once you have selected the best candidate ARIMA(p, d,q) model for your time series data, you can estimate the parameters of that ARIMA model, and use that as a predictive model for making forecasts for future values of your time series. You can estimate the parameters of an ARIMA(p, d,q) model using the 8220arima()8221 function in R. Example of the Ages at Death of the Kings of England For example, we discussed above that an ARIMA(0,1,1) model seems a plausible model for the ages at deaths of the kings of England. You can specify the values of p, d and q in the ARIMA model by using the 8220order8221 argument of the 8220arima()8221 function in R. To fit an ARIMA(p, d,q) model to this time series (which we stored in the variable 8220kingstimeseries8221, see above), we type: As mentioned above, if we are fitting an ARIMA(0,1,1) model to our time series, it means we are fitting an an ARMA(0,1) model to the time series of first differences. An ARMA(0,1) model can be written Xt - mu Zt - (theta Zt-1), where theta is a parameter to be estimated. From the output of the 8220arima()8221 R function (above), the estimated value of theta (given as 8216ma18217 in the R output) is -0.7218 in the case of the ARIMA(0,1,1) model fitted to the time series of ages at death of kings. Specifying the confidence level for prediction intervals You can specify the confidence level for prediction intervals in forecast. Arima() by using the 8220level8221 argument. For example, to get a 99.5 prediction interval, we would type 8220forecast. Arima(kingstimeseriesarima, h5, levelc(99.5))8221. We can then use the ARIMA model to make forecasts for future values of the time series, using the 8220forecast. Arima()8221 function in the 8220forecast8221 R package. For example, to forecast the ages at death of the next five English kings, we type: The original time series for the English kings includes the ages at death of 42 English kings. The forecast. Arima() function gives us a forecast of the age of death of the next five English kings (kings 43-47), as well as 80 and 95 prediction intervals for those predictions. The age of death of the 42nd English king was 56 years (the last observed value in our time series), and the ARIMA model gives the forecasted age at death of the next five kings as 67.8 years. We can plot the observed ages of death for the first 42 kings, as well as the ages that would be predicted for these 42 kings and for the next 5 kings using our ARIMA(0,1,1) model, by typing: As in the case of exponential smoothing models, it is a good idea to investigate whether the forecast errors of an ARIMA model are normally distributed with mean zero and constant variance, and whether the are correlations between successive forecast errors. For example, we can make a correlogram of the forecast errors for our ARIMA(0,1,1) model for the ages at death of kings, and perform the Ljung-Box test for lags 1-20, by typing: Since the correlogram shows that none of the sample autocorrelations for lags 1-20 exceed the significance bounds, and the p-value for the Ljung-Box test is 0.9, we can conclude that there is very little evidence for non-zero autocorrelations in the forecast errors at lags 1-20. To investigate whether the forecast errors are normally distributed with mean zero and constant variance, we can make a time plot and histogram (with overlaid normal curve) of the forecast errors: The time plot of the in-sample forecast errors shows that the variance of the forecast errors seems to be roughly constant over time (though perhaps there is slightly higher variance for the second half of the time series). The histogram of the time series shows that the forecast errors are roughly normally distributed and the mean seems to be close to zero. Therefore, it is plausible that the forecast errors are normally distributed with mean zero and constant variance. Since successive forecast errors do not seem to be correlated, and the forecast errors seem to be normally distributed with mean zero and constant variance, the ARIMA(0,1,1) does seem to provide an adequate predictive model for the ages at death of English kings. Example of the Volcanic Dust Veil in the Northern Hemisphere We discussed above that an appropriate ARIMA model for the time series of volcanic dust veil index may be an ARIMA(2,0,0) model. To fit an ARIMA(2,0,0) model to this time series, we can type: As mentioned above, an ARIMA(2,0,0) model can be written as: written as: Xt - mu (Beta1 (Xt-1 - mu)) (Beta2 (Xt-2 - mu)) Zt, where Beta1 and Beta2 are parameters to be estimated. The output of the arima() function tells us that Beta1 and Beta2 are estimated as 0.7533 and -0.1268 here (given as ar1 and ar2 in the output of arima()). Now we have fitted the ARIMA(2,0,0) model, we can use the 8220forecast. ARIMA()8221 model to predict future values of the volcanic dust veil index. The original data includes the years 1500-1969. To make predictions for the years 1970-2000 (31 more years), we type: We can plot the original time series, and the forecasted values, by typing: One worrying thing is that the model has predicted negative values for the volcanic dust veil index, but this variable can only have positive values The reason is that the arima() and forecast. Arima() functions don8217t know that the variable can only take positive values. Clearly, this is not a very desirable feature of our current predictive model. Again, we should investigate whether the forecast errors seem to be correlated, and whether they are normally distributed with mean zero and constant variance. To check for correlations between successive forecast errors, we can make a correlogram and use the Ljung-Box test: The correlogram shows that the sample autocorrelation at lag 20 exceeds the significance bounds. However, this is probably due to chance, since we would expect one out of 20 sample autocorrelations to exceed the 95 significance bounds. Furthermore, the p-value for the Ljung-Box test is 0.2, indicating that there is little evidence for non-zero autocorrelations in the forecast errors for lags 1-20. To check whether the forecast errors are normally distributed with mean zero and constant variance, we make a time plot of the forecast errors, and a histogram: The time plot of forecast errors shows that the forecast errors seem to have roughly constant variance over time. However, the time series of forecast errors seems to have a negative mean, rather than a zero mean. We can confirm this by calculating the mean forecast error, which turns out to be about -0.22: The histogram of forecast errors (above) shows that although the mean value of the forecast errors is negative, the distribution of forecast errors is skewed to the right compared to a normal curve. Therefore, it seems that we cannot comfortably conclude that the forecast errors are normally distributed with mean zero and constant variance Thus, it is likely that our ARIMA(2,0,0) model for the time series of volcanic dust veil index is not the best model that we could make, and could almost definitely be improved upon Links and Further Reading Here are some links for further reading. For a more in-depth introduction to R, a good online tutorial is available on the 8220Kickstarting R8221 website, cran. r-project. orgdoccontribLemon-kickstart . There is another nice (slightly more in-depth) tutorial to R available on the 8220Introduction to R8221 website, cran. r-project. orgdocmanualsR-intro. html . You can find a list of R packages for analysing time series data on the CRAN Time Series Task View webpage . To learn about time series analysis, I would highly recommend the book 8220Time series8221 (product code M24902) by the Open University, available from the Open University Shop . There are two books available in the 8220Use R8221 series on using R for time series analyses, the first is Introductory Time Series with R by Cowpertwait and Metcalfe, and the second is Analysis of Integrated and Cointegrated Time Series with R by Pfaff. Acknowledgements I am grateful to Professor Rob Hyndman. for kindly allowing me to use the time series data sets from his Time Series Data Library (TSDL) in the examples in this booklet. Many of the examples in this booklet are inspired by examples in the excellent Open University book, 8220Time series8221 (product code M24902), available from the Open University Shop . Thank you to Ravi Aranke for bringing auto. arima() to my attention, and Maurice Omane-Adjepong for bringing unit root tests to my attention, and Christian Seubert for noticing a small bug in plotForecastErrors(). Thank you for other comments to Antoine Binard and Bill Johnston. I will be grateful if you will send me (Avril Coghlan) corrections or suggestions for improvements to my email address alc 64 sanger 46 ac 46 uk

No comments:

Post a Comment