Thursday, 5 October 2017

Eksponensiell Bevegelig Gjennomsnitt Uregelmessig Tidsrekke


Fremgangsmåte ved å velge en prognosemodell Din prognosemodell skal inneholde funksjoner som fanger opp alle viktige kvalitative egenskapene til dataene: variasjonsmønstre i nivå og trend, effekter av inflasjon og sesongmessighet, korrelasjoner mellom variabler, osv. Videre er antagelsene som ligger til grunn for din valgt modell bør være enig med din intuisjon om hvordan serien ser ut til å oppføre seg i fremtiden. Når du bruker en prognosemodell, har du noen av følgende valg: Disse alternativene er kort beskrevet nedenfor. Se det medfølgende prognostiseringsdiagrammet for en bildevisning av modellspesifikasjonsprosessen, og referer tilbake til Statgraphics Model Specification-panelet for å se hvordan modellegenskapene er valgt i programvaren. Deflation Hvis serien viser inflasjonær vekst, vil deflasjon bidra til å regne for vekstmønsteret og redusere heteroscedasticitet i residualene. Du kan enten (i) deflater de forrige dataene og gjenopplate de langsiktige prognosene med en konstant antatt hastighet, eller (ii) deflater de siste dataene med en prisindeks som KPI, og deretter kvittere med å reinflate de langsiktige prognosene ved å bruke en prognose av prisindeksen. Alternativ (i) er det enkleste. I Excel kan du bare opprette en kolonne med formler for å dele de opprinnelige verdiene med de relevante faktorene. For eksempel, hvis dataene er månedlige og du vil deflate med en hastighet på 5 per 12 måneder, vil du dele med en faktor (1.05) (k12) hvor k er radindeksen (observasjonsnummer). RegressIt og Statgraphics har innebygde verktøy som gjør dette automatisk for deg. Hvis du går denne ruten, er det vanligvis best å angi antatt inflasjonsrate som det beste estimatet av dagens rente, spesielt hvis du skal prognose mer enn en periode framover. Hvis du i stedet velger valgmulighet (ii), må du først lagre deflaterte prognosene og konfidensgrensene i dataregnearket ditt, og deretter generere og lagre en prognose for prisindeksen, og til slutt multiplisere de tilhørende kolonnene sammen. (Tilbake til toppen av siden.) Logaritme transformasjon Hvis serien viser sammensatt vekst og et multipliserende sesongmønster, kan en logaritme transformasjon være nyttig i tillegg til eller i stedet for deflasjon. Logging av dataene vil ikke flate et inflasjonsvækstmønster, men det vil rette det ut slik at det kan monteres av en lineær modell (for eksempel en tilfeldig tur eller ARIMA-modell med konstant vekst eller en lineær eksponensiell utjevningsmodell). Logging vil også konvertere multiplikative sesongmønstre til additivmønstre, slik at hvis du utfører sesongjustering etter logging, bør du bruke additiv typen. Logging handler om inflasjon på en implisitt måte hvis du vil at inflasjonen skal modelleres eksplisitt - dvs. Hvis du vil at inflasjonsraten skal være en synlig parameter for modellen, eller hvis du vil se plott av deflaterte data - så skal du deflate i stedet for å logge. En annen viktig bruk for logtransformasjonen er linearisering av relasjoner mellom variabler i en regresjonsmodus l. For eksempel, hvis den avhengige variabelen er en multiplikativ snarere enn additiv funksjon av de uavhengige variablene, eller hvis forholdet mellom avhengige og uavhengige variabler er lineært i forhold til prosentvise endringer i stedet for absolutte endringer, så bruker man en logtransformasjon til en eller flere variabler kan være hensiktsmessig, som i ølsalgseksemplet. (Tilbake til toppen av siden.) Sesongjustering Hvis serien har et sterkt sesongmessig mønster som antas å være konstant fra år til år, kan sesongjustering være en passende måte å estimere og ekstrapolere mønsteret på. Fordelen med sesongjustering er at den eksplisitt modellerer sesongmønsteret, og gir deg muligheten til å studere sesongindeksene og de sesongjusterte dataene. Ulempen er at det krever estimering av et stort antall tilleggsparametere (spesielt for månedlige data), og det gir ingen teoretisk begrunnelse for beregningen av kvotekvoterte konfidensintervaller. Validering utenfor prøven er spesielt viktig for å redusere risikoen for overpassing av tidligere data gjennom sesongjustering. Hvis dataene er sterkt sesongmessige, men du ikke velger sesongjustering, er alternativene å enten (i) bruke en sesongbasert ARIMA-modell. som implisitt prognoser sesongmønsteret ved hjelp av sesongmessige lag og forskjeller, eller (ii) bruker Winters sesongmessige eksponensielle utjevningsmodell, som anslår tidsvarierende sesongindekser. (Gå tilbake til toppen av siden.) QuotIndependentquot variabler Hvis det finnes andre tidsserier som du mener har forklarende kraft i forhold til din serie av interesser (f. eks. Ledende økonomiske indikatorer eller policyvariabler som pris, reklame, kampanjer, etc.) kan ønske å vurdere regresjon som modelltype. Uansett om du velger regresjon, må du likevel vurdere mulighetene som er nevnt ovenfor for å omdanne variablene dine (deflasjon, logg, sesongjustering - og kanskje også differensiering) for å utnytte tidsdimensjonen og / eller linearisere relasjonene. Selv om du ikke velger regresjon på dette tidspunktet, kan du kanskje vurdere å legge til regressorer senere til en tidsseriemodell (for eksempel en ARIMA-modell) hvis residualene viser seg å ha signifikante krysskorrelasjoner med andre variabler. (Tilbake til toppen av siden.) Utjevning, gjennomsnitt eller tilfeldig spasertur Hvis du har valgt å justere dataene sesongmessig - eller hvis dataene ikke er sesongmessige til å begynne med - kan du kanskje bruke en gjennomsnittlig eller utjevningsmodell til passe det ikke-soneformede mønsteret som forblir i dataene på dette punktet. En enkel glidende gjennomsnitt eller enkel eksponensiell utjevningsmodell beregner bare et lokalt gjennomsnitt av data på slutten av serien, under forutsetning av at dette er det beste estimatet av gjeldende middelverdien rundt hvilken dataene varierer. (Disse modellene antar at gjennomsnittet av serien varierer langsomt og tilfeldig uten vedvarende trender.) Enkel eksponensiell utjevning er normalt foretrukket for et enkelt bevegelige gjennomsnitt, fordi dets eksponentielt vektede gjennomsnitt gjør en mer fornuftig jobb med å diskontere de eldre dataene, fordi dens utjevningsparameter (alfa) er kontinuerlig og kan lett optimaliseres, og fordi den har et underliggende teoretisk grunnlag for beregning av konfidensintervall. Hvis utjevning eller gjennomsnitt ikke ser ut til å være nyttig - det vil si. hvis den beste prediktoren for den neste verdien av tidsseriene bare er dens tidligere verdi - så er en tilfeldig gangmodell angitt. Dette er tilfellet for eksempel hvis det optimale antall vilkår i det enkle glidende gjennomsnittet viser seg å være 1, eller hvis den optimale verdien av alfa i enkel eksponensiell utjevning viser seg å være 0.9999. Browns lineær eksponensiell utjevning kan brukes til å passe en serie med sakte tidsvarierende lineære trender, men vær forsiktig med å ekstrapolere slike trender veldig langt inn i fremtiden. (De raskt utvidede konfidensintervaller for denne modellen vitner for usikkerheten om den fjerne fremtid.) Huller lineær utjevning anslår også tidsvarierende trender, men bruker separate parametere for å jevne ut nivå og trend, som vanligvis gir bedre passform til dataene enn Brown8217s modell. Q uadratisk eksponensiell utjevning forsøker å estimere tidsvarierende kvadratiske trender, og bør nesten aldri brukes. (Dette vil korrespondere med en ARIMA-modell med tre ordrer av ikke-soneforskjeller.) Linjær eksponensiell utjevning med en dempet trend (det vil si en trend som flater ut i fjerne horisonter) anbefales ofte i situasjoner der fremtiden er svært usikker. De ulike eksponensielle utjevningsmodellene er spesielle tilfeller av ARIMA-modeller (beskrevet nedenfor) og kan utstyres med ARIMA-programvare. Spesielt er den enkle eksponensielle utjevningsmodellen en ARIMA (0,1,1) modell. Holt8217s lineær utjevningsmodell er en ARIMA (0,2,2) modell, og den dempede trendmodellen er en ARIMA (1,1,2 ) modell. Et godt sammendrag av ligningene i de ulike eksponentielle utjevningsmodeller finnes på denne siden på SAS nettside. (SAS-menyene for å spesifisere tidsseriemodeller vises også der de er lik de som er i Statgraphics.) Lineære, kvadratiske eller eksponentielle trendlinjemodeller er andre alternativer for ekstrapolering av en desesasonalisert serie, men de går sjelden utover tilfeldig gange, utjevning eller ARIMA modeller på forretningsdata. (Tilbake til toppen av siden.) Vinter Sesongmessig eksponensiell utjevning Vinter Sesonglig utjevning er en utvidelse av eksponensiell utjevning som samtidig estimerer tidsvarierende nivå, trend og sesongfaktorer ved bruk av rekursive ligninger. (Hvis du bruker denne modellen, vil du ikke først justere dataene sesongmessig.) Winters sesongfaktorer kan enten være multiplikativ eller additiv: normalt bør du velge multiplikasjonsalternativet med mindre du har logget inn dataene. Selv om Winters-modellen er smart og rimelig intuitiv, kan det være vanskelig å bruke i praksis: det har tre utjevningsparametere - alfa, beta og gamma - for å utjevne nivå, trend og sesongfaktorer separat, som må estimeres samtidig. Bestemmelse av startverdier for sesongindeksene kan gjøres ved å bruke forholdsmessige gjennomsnittlige metode for sesongjustering til deler eller hele serien andor ved tilbakekalling. Estimeringsalgoritmen som Statgraphics bruker for disse parametrene, feiler noen ganger ikke sammen, og gir verdier som gir bizarre prognoser og konfidensintervaller, så jeg vil anbefale forsiktighet når du bruker denne modellen. (Tilbake til toppen av siden.) ARIMA Hvis du ikke velger sesongjustering (eller hvis dataene ikke er sesongbaserte), kan du ønske å bruke ARIMA-modellrammen. ARIMA-modeller er en svært generell klasse av modeller som inkluderer tilfeldig gange, tilfeldig trend, eksponensiell utjevning og autoregressive modeller som spesielle tilfeller. Den konvensjonelle visdommen er at en serie er en god kandidat til en ARIMA-modell hvis (i) den kan stasjonæriseres ved en kombinasjon av differensiering og andre matematiske transformasjoner som logging, og (ii) du har en betydelig mengde data for å jobbe med : minst 4 fulle årstider når det gjelder sesongdata. (Hvis serien ikke kan stasjoneres på riktig måte ved differensiering - f. eks. Hvis den er svært uregelmessig eller synes å kvalitativt endre sin oppførsel over tid - eller hvis du har færre enn 4 årstider, kan du bli bedre med en modell som bruker sesongjustering og noen form for enkel gjennomsnitt eller utjevning.) ARIMA-modeller har en spesiell navngivningskonvensjon innført av Box og Jenkins. En ikke-sasonlig ARIMA-modell er klassifisert som en ARIMA-modell (p, d, q), hvor d er antall ikke-soneforskjeller, p er antall autoregressive termer (lag av differensierte serier) og q er antall flyttbare - gjennomsnittlige termer (lags av prognosefeilene) i prediksjonsligningen. En sesongbasert ARIMA-modell er klassifisert som en ARIMA (p, d, q) x (P, D, Q). hvor D, P og Q er henholdsvis antall sesongmessige forskjeller, sesongbaserte autoregressive termer (lags av differensierte serier ved multiplene av sesongperioden) og sesongmessige glidende gjennomsnittlige termer (lags av prognosefeilene ved flere ganger av sesongens periode). Det første trinnet i å montere en ARIMA-modell er å bestemme riktig rekkefølge for differensiering som trengs for å stasjonere serien og fjerne bruttoegenskapene til sesongmessigheten. Dette tilsvarer å avgjøre hvilken kvotestilling som tilfeldigvis eller tilfeldig trendmodell gir det beste utgangspunktet. Ikke forsøk å bruke mer enn 2 forskjellige ordrer av differensiering (sesongbasert og sesongbasert kombinert), og bruk ikke mer enn 1 sesongmessig forskjell. Det andre trinnet er å avgjøre om det skal inkluderes en konstant term i modellen: Vanligvis inkluderer du en konstant term hvis total rekkefølgen av differensiering er 1 eller mindre, ellers gjør du det ikke. I en modell med en ordre av differensiering representerer den konstante sikt den gjennomsnittlige trenden i prognosene. I en modell med to differensordrer, er trenden i prognosene bestemt av lokal trenden observert i slutten av tidsserien, og den konstante sikt representerer trend-i-trenden, dvs. krumningen av langvarig langsiktige prognoser. Normalt er det farlig å ekstrapolere trender i trender, slik at du undertrykker kontantperioden i dette tilfellet. Det tredje trinnet er å velge antall autoregressive og bevegelige gjennomsnittsparametere (p, d, q, P, D, Q) som er nødvendige for å eliminere autokorrelasjon som forblir i gjenstander av naivmodellen (dvs. enhver korrelasjon som gjenstår etter bare differensiering). Disse tallene bestemmer antall lags av differenced series andor lags av prognosefeilene som inngår i prognosekvasjonen. Hvis det ikke er noen signifikant autokorrelasjon i residualene på dette punktet, så STOP, du er ferdig: Den beste modellen er en naiv modell Hvis det er betydelig autokorrelasjon ved lags 1 eller 2, bør du prøve å sette q1 hvis ett av følgende gjelder: ( i) det er en sesongmessig forskjell i modellen, (ii) lag 1-autokorrelasjonen er negativ. andor (iii) gjenværende autokorrelasjonsplott er renere utseende (færre, mer isolerte pigger) enn den gjenværende partielle autokorrelasjonsplottet. Hvis det ikke er noen sesongmessig forskjell i modellen, og er lag 1-autokorrelasjonen positiv, og den resterende partielle autokorrelasjonsplottet ser renere ut, så prøv p1. (Noen ganger er disse reglene for å velge mellom p1 og q1 konflikt med hverandre, i så fall gjør det sannsynligvis ikke stor forskjell som du bruker. Prøv dem begge og sammenlign.) Hvis det er autokorrelasjon ved lag 2 som ikke fjernes ved å sette p1 eller q1, kan du prøve p2 eller q2, eller noen ganger p1 og q1. Mer sjelden kan du oppleve situasjoner der p2 eller 3 og q1, eller omvendt, gir de beste resultatene. Det anbefales sterkt at du ikke bruker pgt1 og qgt1 i samme modell. Generelt, når du monterer ARIMA-modeller, bør du unngå å øke modellkompleksiteten for å oppnå bare små ytterligere forbedringer i feilstatistikken eller utseendet til ACF - og PACF-plottene. I en modell med både pgt1 og qgt1 finnes det også en god mulighet for redundans og ikke-unikhet mellom AR - og MA-siden av modellen, som forklart i notatene om den matematiske strukturen til ARIMA-modellen s. Det er vanligvis bedre å fortsette i en fremad trinnvis snarere enn bakover trinnvis måte når du tilpasser modellspesifikasjonene: Start med enklere modeller og legg bare til flere vilkår hvis det er et klart behov. De samme regler gjelder for antall sesongbaserte autoregressive termer (P) og antall sesongmessige glidende gjennomsnittlige betingelser (Q) med hensyn til autokorrelasjon i sesongperioden (for eksempel lag 12 for månedlige data). Prøv Q1 dersom det allerede er en sesongmessig forskjell i modellen, og hvis sesongens autokorrelasjon er negativ, og hvis gjenværende autokorrelasjonsplott ser renere ut i nærheten av sesongslaget, ellers kan du prøve P1. (Hvis det er logisk for serien å vise sterk sesongmessighet, må du bruke en sesongmessig forskjell, ellers vil sesongmønsteret fade ut når du gjør langsiktige prognoser.) Noen ganger kan du prøve å P2 og Q0 eller vice v ersa, eller PQ1. Det anbefales imidlertid sterkt at PQ aldri burde være større enn 2. Sesongmønstre har sjelden den typen perfekt regelmessighet over et stort antall årstider som vil gjøre det mulig å pålitelig identifisere og anslå at mange parametere. Også tilbakekallingsalgoritmen som brukes i parameterestimering, vil trolig gi upålitelige (eller til og med galte) resultater når antall sesonger av data ikke er vesentlig større enn PDQ. Jeg vil anbefale ikke mindre enn PDQ2 hele årstider, og mer er bedre. Igjen, når du monterer ARIMA-modeller, bør du være forsiktig med å unngå overpassing av dataene, til tross for at det kan være mye moro når du får tak i det. Viktige spesielle tilfeller: Som angitt ovenfor er en ARIMA (0,1,1) modell uten konstant identisk med en enkel eksponensiell utjevningsmodell, og det antar et flytende nivå (det vil si ingen vesentlig reversering), men med null langsiktig trend. En ARIMA (0,1,1) modell med konstant er en enkel eksponensiell utjevningsmodell med en ikke-lineær trendkategori inkludert. En ARIMA (0,2,1) eller (0,2,2) modell uten konstant er en lineær eksponensiell utjevningsmodell som muliggjør en tidsvarierende trend. En ARIMA (1,1,2) modell uten konstant er en lineær eksponensiell utjevningsmodell med fuktet trend, det vil si en trend som til slutt flater ut i langsiktige prognoser. De vanligste sesongbaserte ARIMA-modellene er ARIMA-modellen (0,1,1) x (0,1,1) uten konstant og ARIMA-modellen (1,0,1) x (0,1,1) med konstant. Den tidligere av disse modellene bruker i utgangspunktet eksponensiell utjevning til både de ikke-sesongmessige og sesongmessige komponentene i mønsteret i dataene, samtidig som det tillates en tidsvarierende trend, og sistnevnte modell er noe lik, men antar en konstant lineær trend og derfor litt mer lang tidsforutsigbarhet. Du bør alltid inkludere disse to modellene blant ditt utvalg av mistenkte når du monterer data med konsekvent sesongmessige mønstre. En av dem (kanskje med en mindre variasjon som øker p eller q med 1 ogor setting P1 så vel som Q1) er ganske ofte det beste. (Gå tilbake til toppen av siden.) Jeg jobber med en stor mengde tidsserier. Disse tidsseriene er i utgangspunktet nettverksmålinger som kommer hvert 10. minutt, og noen av dem er periodiske (dvs. båndbredden), mens noen andre arent (dvs. mengden rutingstrafikk). Jeg vil gjerne ha en enkel algoritme for å gjøre en online utleder deteksjon. I utgangspunktet vil jeg beholde alle historiske data for hver tidsserie i minnet (eller på disken), og jeg vil oppdage en hvilken som helst utvider i et levende scenario (hver gang en ny prøve blir tatt). Hva er den beste måten å oppnå disse resultatene Jeg bruker for øyeblikket et glidende gjennomsnitt for å fjerne litt støy, men hva er de neste enkle ting som standardavvik, sint. mot hele datasettet virker det ikke bra (jeg kan ikke anta at tidsseriene er stasjonære), og jeg vil gjerne ha noe mer nøyaktig, helst en svart boks som: dobbelt outlierdetection (dobbel vektor, dobbel verdi) der vektoren er en rekke dobbeltholdige de historiske dataene, og returverdien er anomalitetspoeng for den nye samplingsverdien. spurte Aug 2 10 kl 20:37 Ja, jeg har antatt at frekvensen er kjent og spesifisert. Det er metoder for å estimere frekvensen automatisk, men det vil komplisere funksjonen betydelig. Hvis du må estimere frekvensen, kan du prøve å stille et eget spørsmål om det - og jeg vil nok gi svar. Men det trenger mer plass enn jeg har tilgjengelig i en kommentar. ndash Rob Hyndman Aug 3 10 kl 23:40 En god løsning vil ha flere ingredienser, blant annet: Bruk et motstandsdyktig, bevegelige vindu glatt for å fjerne ikke-stabilitet. Gi uttrykk for de opprinnelige dataene slik at residualene med hensyn til glatt er omtrent symmetrisk fordelt. Gitt dataene dine, er det sannsynlig at deres firkantede røtter eller logaritmer vil gi symmetriske gjenstander. Bruk kontroll diagrammet metoder, eller i det minste kontroll diagram tenkning, til residualene. Så langt som det siste går, viser kontrolldiagramtanken at konvensjonelle terskler som 2 SD eller 1,5 ganger IQR utover kvartilene virker dårlig, fordi de utløser for mange falske out-of-control signaler. Folk bruker vanligvis 3 SD i kontrolldiagramarbeid, hvorav 2,5 (eller til og med 3) ganger IQR utover kvartilene ville være et godt utgangspunkt. Jeg har mer eller mindre skissert naturen til Rob Hyndmans løsning mens jeg legger til to hovedpunkter: Det potensielle behovet for å gi uttrykk for dataene og visdommen om å være mer konservativ når det gjelder å signalere en outlier. Jeg er ikke sikker på at Loess er bra for en elektronisk detektor, men fordi det ikke fungerer bra på sluttpunktene. Du kan i stedet bruke noe så enkelt som et bevegelig medianfilter (som i Tukeys resistente utjevning). Hvis utjevnene ikke kommer i utbrudd, kan du bruke et smalt vindu (5 datapunkter, kanskje, som bare vil bryte ned med en utbrudd på 3 eller flere avvikere innenfor en gruppe på 5). Når du har utført analysen for å bestemme et godt re-uttrykk for dataene, vil du sannsynligvis ikke endre re-uttrykket. Derfor trenger nettleseren din bare å referere til de nyeste verdiene (det siste vinduet) fordi det ikke vil bruke de tidligere dataene i det hele tatt. Hvis du har veldig lange tidsserier, kan du gå videre for å analysere autokorrelasjon og sesongmessighet (som gjentatte daglige eller ukentlige svingninger) for å forbedre prosedyren. besvart aug 26 10 kl 18:02 John, 1,5 IQR er Tukey39s opprinnelige anbefaling for de lengste whiskers på en boksplott og 3 IQR er hans anbefaling for markeringspoeng som kvoter outliersquot (en riff på en populær 6039-setning). Dette er bygget inn i mange boxplot-algoritmer. Anbefalingen er teoretisk analysert i Hoaglin, Mosteller, Amp Tukey, Understanding Robust og Exploratory Data Analysis. ndash w huber 9830 okt 9 12 kl 21:38 Dette bekrefter tidsseriedata jeg har prøvd å analysere. Vinduet gjennomsnitt og også en standard standardavvik. ((x - avg) sd) gt 3 ser ut til å være poengene jeg vil flagge som outliers. Vel, vær så snill som advarsler, flagg jeg noe høyere enn 10 sd som ekstreme feilutviklere. Problemet jeg løper inn er det som er en ideell vinduslengde 395m med noe mellom 4-8 datapunkter. ndash NeoZenith Jun 29 16 at 8:00 Neo Din beste innsats kan være å eksperimentere med en delmengde av dataene dine og bekrefte konklusjonene dine med tester på resten. Du kan også gjennomføre en mer formell kryssvalidering (men det er nødvendig med forsiktighet med tidsseriedata på grunn av gjensidig avhengighet av alle verdiene). ndash w huber 9830 Jun 29 16 kl 12:10 (Dette svaret reagerte på et duplikat (nå lukket) spørsmål ved å oppdage utestående hendelser. Som presentert noen data i grafisk form.) Utleder detektering avhenger av dataens natur og hva du er villige til å anta om dem. Generelle metoder bygger på robust statistikk. Ånden i denne tilnærmingen er å karakterisere størstedelen av dataene på en måte som ikke påvirkes av noen avvikere og deretter peke på noen individuelle verdier som ikke passer inn i den karakteriseringen. Fordi dette er en tidsserie, legger det til komplikasjonen av å måtte (gjenoppdage) avvikere på en kontinuerlig basis. Hvis dette skal gjøres når serien utfolder seg, kan vi bare bruke eldre data for deteksjonen, ikke fremtidige data. For å beskytte mot de mange gjentatte tester vil vi gjerne bruke en metode som har svært lite falsk positiv rente. Disse overvejingene antyder at du kjører en enkel, robust flyttevinduutgangstest over dataene. Det er mange muligheter, men en enkel, lett forståelig og lett implementert en er basert på en løpende MAD: median absolutt avvik fra medianen. Dette er et sterkt robust mål for variasjon i dataene, i likhet med en standardavvik. En ekstern topp ville være flere MAD eller mer større enn medianen. Det er fortsatt noen tuning som skal gjøres. hvor mye av avvik fra hovedparten av dataene bør betraktes som eksternt og hvor langt tilbake i tid bør man se. La oss forlate disse som parametere for eksperimentering. Heres en R-implementering brukes på data x (1,2, ldots, n) (med n1150 å emulere dataene) med tilsvarende verdier y: Brukes til et datasett som den røde kurven illustrert i spørsmålet, produserer dette resultatet: Dataene vises i rødt, 30-dagers vinduet med median5MAD-terskler i grått, og utjevningene - som bare er de dataværdiene over den grå kurven - i svart. (Terskelen kan bare beregnes fra begynnelsen av innledningsvinduet. For alle data i dette innledende vinduet brukes den første terskelen: derfor er den grå kurven flat mellom x0 og x30.) Effektene ved å endre parametrene er (a) øker verdien av vinduet en tendens til å glatte ut den grå kurven og (b) økende terskel vil øke den grå kurven. Å vite dette kan man ta et innledende segment av dataene og raskt identifisere verdier av parametrene som best adskiller de ytre toppene fra resten av dataene. Bruk disse parameterverdiene for å sjekke resten av dataene. Hvis et diagram viser at metoden er forverret over tid, betyr det at dataenes natur endrer seg og parametrene kan trenge å justeres. Legg merke til hvor lite denne metoden antar om dataene: De trenger ikke å bli distribuert normalt, de trenger ikke å vise noen periodicitet de ikke engang må være ikke-negative. Alt det antas, er at dataene oppfører seg på rimelig lignende måter over tid, og at de ytre toppene er synlig høyere enn resten av dataene. Hvis noen vil gjerne eksperimentere (eller sammenligne noen annen løsning med den som tilbys her), her er koden jeg brukte til å produsere data som de som er vist i spørsmålet. Jeg gjetter sofistikert tidsseriemodell vil ikke fungere for deg på grunn av den tiden det tar å oppdage avvikere ved hjelp av denne metoden. Derfor er det her en løsning: Først opprett en normal trafikkmønster i et år basert på manuell analyse av historiske data som står for tidspunkt på dagen, ukedag vs helg, måned på året etc. Bruk denne grunnlinjen sammen med en enkel mekanisme (for eksempel bevegelige gjennomsnitt foreslått av Carlos) for å oppdage avvikere. Du vil kanskje også vurdere den statistiske prosesskontrolllitteraturen for noen ideer. Ja, dette er akkurat det jeg gjør: til nå deler jeg signalet manuelt i perioder, slik at jeg for hver av dem kan definere et konfidensintervall der signalet skal være stasjonært, og derfor kan jeg bruke standardmetoder som som standardavvik. Det virkelige problemet er at jeg ikke kan bestemme det forventede mønsteret for alle signalene jeg må analysere, og derfor søker jeg etter noe mer intelligent. ndash gianluca Aug 2 10 kl 21:37 Her er en ide: Trinn 1: Implementer og estimer en generisk tidsseriemodell på en gang basert på historiske data. Dette kan gjøres offline. Trinn 2: Bruk den resulterende modellen til å oppdage avvikere. Trinn 3: Omkalibrere tidsseriemodellen (dette kan gjøres frakoblet), med en eller annen frekvens (kanskje hver måned), slik at trinn 2-deteksjon av utjevningsmidler ikke går for mye ut av dagens trafikkmønstre. Ville det fungere for konteksten din ndash user28 Aug 2 10 kl 22:24 Ja, dette kan fungere. Jeg tenkte på en lignende tilnærming (omdanner grunnlinjen hver uke, som kan være CPU-intensiv hvis du har hundrevis av univariate tidsserier for å analysere). BTW Det virkelige vanskelige spørsmålet er hva er den beste blackbox-stilalgoritmen for modellering av et helt generisk signal, vurderer støy, trendestimering og seasonalityquot. AFAIK, hver tilnærming i litteraturen krever en veldig hard quotparameter tuningquot-fase, og den eneste automatiske metoden jeg fant er en ARIMA-modell av Hyndman (robjhyndmansoftwareforecast). Jeg savner noe ndash gianluca Aug 2 10 kl 22:38 Igjen, dette virker ganske bra hvis signalet skal ha en sesongmessig sånn, men hvis jeg bruker en helt annen tidsserie (dvs. gjennomsnittlig TCP rundtur tid over tid ), vil denne metoden ikke fungere (siden det ville være bedre å håndtere det med en enkel global gjennomsnittlig og standardavvik ved å bruke et skyvevindu som inneholder historiske data). ndash gianluca Aug 2 10 kl 22:02 Med mindre du er villig til å implementere en generell tidsserie modell (som bringer inn sine ulemper med hensyn til latens osv.) er jeg pessimistisk at du vil finne en generell gjennomføring som samtidig er enkel nok å jobbe for alle slags tidsserier. ndash user28 Aug 2 10 kl 22:06 En annen kommentar: Jeg vet at et godt svar kan være quotso du kan estimere signalets periodicitet og bestemme algoritmen for å bruke i henhold til itquot, men jeg fant ikke en virkelig god løsning på denne andre problem (jeg spilte litt med spektralanalyse ved hjelp av DFT og tidsanalyse ved hjelp av autokorrelasjonsfunksjonen, men min tidsserie inneholder mye støy og slike metoder gir noen vanlige resultater mesteparten av tiden) ndash gianluca Aug 2 10 kl 22:06 A kommentere din siste kommentar: det er derfor jeg leter etter en mer generisk tilnærming, men jeg trenger en slags quotblack boxquot fordi jeg ikke kan gjøre noen antagelse om det analyserte signalet, og derfor kan jeg ikke opprette kvoteparameteren for læringalgoritmoten. ndash gianluca Aug 2 10 kl 22:09 Siden det er en tidsserie data, vil et enkelt eksponensielt filter en. wikipedia. orgwikiExponentialsmoothing glatte dataene. Det er et veldig godt filter siden du ikke trenger å samle gamle datapunkter. Sammenlign alle nyliggjorte dataverdier med sin ujevne verdi. Når avviket overskrider en bestemt forhåndsdefinert terskel (avhengig av hva du mener er en utjevneren i dataene dine), kan din utleder lett oppdages. besvart 30 april 15 kl. 8:50 Du kan bruke standardavviket fra de siste N-målingene (du må velge en egnet N). En god anomalie score ville være hvor mange standardavvik en måling er fra det bevegelige gjennomsnittet. svarte aug 2 10 kl 20:48 Takk for svaret ditt, men hva hvis signalet viser høy sesongmessighet (dvs. mange nettmålinger er preget av et daglig og ukentlig mønster på samme tid, for eksempel natt vs dag eller helg mot arbeidsdager) En tilnærming basert på standardavvik vil ikke fungere i det tilfellet. ndash gianluca Aug 2 10 kl 20:57 Hvis jeg for eksempel får en ny prøve hvert 10. minutt, og jeg gjør en ekstern oppdagelse av nettverksbåndbreddebruken av et selskap, i utgangspunktet klokka 18.00, vil dette tiltaket falle ned (dette er en forventet et totalt normalt mønster), og et standardavvik beregnet over et skyvevindu vil mislykkes (fordi det vil utløse et varsel sikkert). Samtidig, hvis målet faller ned klokka 16:00 (avviker fra vanlig utgangspunkt), er dette en ekte utvider. ndash gianluca aug 2 10 kl 20:58 hva jeg gjør er å gruppere målingene etter klokkeslett og ukedag, og sammenlign standardavvik av det. Fortsatt korrigerer ikke for ting som ferie og sommervinters sesongmessighet, men det er riktig det meste av tiden. Ulempen er at du virkelig trenger å samle et år med data for å få nok slik at stddev begynner å gi mening. Spektralanalyse registrerer periodicitet i stasjonære tidsserier. Frekvensdomene tilnærming basert på spektral tetthets estimering er en tilnærming jeg vil anbefale som ditt første skritt. Hvis uregelmessigheter i visse perioder betyr en mye høyere topp enn det som er typisk for den perioden, ville serien med slike uregelmessigheter ikke være stasjonær og spektral anslisning ikke ville være hensiktsmessig. Men hvis du antar at du har identifisert perioden som har uregelmessighetene, bør du kunne bestemme omtrent hva den normale topphøyden ville være, og da kan du sette en terskel på noe nivå over det gjennomsnittet for å utpeke de uregelmessige tilfellene. answered Sep 3 12 at 14:59 I suggest the scheme below, which should be implementable in a day or so: Collect as many samples as you can hold in memory Remove obvious outliers using the standard deviation for each attribute Calculate and store the correlation matrix and also the mean of each attribute Calculate and store the Mahalanobis distances of all your samples Calculating outlierness: For the single sample of which you want to know its outlierness: Retrieve the means, covariance matrix and Mahalanobis distance s from training Calculate the Mahalanobis distance d for your sample Return the percentile in which d falls (using the Mahalanobis distances from training) That will be your outlier score: 100 is an extreme outlier. PS. In calculating the Mahalanobis distance. use the correlation matrix, not the covariance matrix. This is more robust if the sample measurements vary in unit and number. Using R for Time Series Analysis Time Series Analysis This booklet itells you how to use the R statistical software to carry out some simple analyses that are common in analysing time series data. This booklet assumes that the reader has some basic knowledge of time series analysis, and the principal focus of the booklet is not to explain time series analysis, but rather to explain how to carry out these analyses using R. If you are new to time series analysis, and want to learn more about any of the concepts presented here, I would highly recommend the Open University book 8220Time series8221 (product code M24902), available from from the Open University Shop . In this booklet, I will be using time series data sets that have been kindly made available by Rob Hyndman in his Time Series Data Library at robjhyndmanTSDL . If you like this booklet, you may also like to check out my booklet on using R for biomedical statistics, a-little-book-of-r-for-biomedical-statistics. readthedocs. org. and my booklet on using R for multivariate analysis, little-book-of-r-for-multivariate-analysis. readthedocs. org . Reading Time Series Data The first thing that you will want to do to analyse your time series data will be to read it into R, and to plot the time series. You can read data into R using the scan() function, which assumes that your data for successive time points is in a simple text file with one column. For example, the file robjhyndmantsdldatamisckings. dat contains data on the age of death of successive kings of England, starting with William the Conqueror (original source: Hipel and Mcleod, 1994). The data set looks like this: Only the first few lines of the file have been shown. The first three lines contain some comment on the data, and we want to ignore this when we read the data into R. We can use this by using the 8220skip8221 parameter of the scan() function, which specifies how many lines at the top of the file to ignore. To read the file into R, ignoring the first three lines, we type: In this case the age of death of 42 successive kings of England has been read into the variable 8216kings8217. Once you have read the time series data into R, the next step is to store the data in a time series object in R, so that you can use R8217s many functions for analysing time series data. To store the data in a time series object, we use the ts() function in R. For example, to store the data in the variable 8216kings8217 as a time series object in R, we type: Sometimes the time series data set that you have may have been collected at regular intervals that were less than one year, for example, monthly or quarterly. In this case, you can specify the number of times that data was collected per year by using the 8216frequency8217 parameter in the ts() function. For monthly time series data, you set frequency12, while for quarterly time series data, you set frequency4. You can also specify the first year that the data was collected, and the first interval in that year by using the 8216start8217 parameter in the ts() function. For example, if the first data point corresponds to the second quarter of 1986, you would set startc(1986,2). An example is a data set of the number of births per month in New York city, from January 1946 to December 1959 (originally collected by Newton). This data is available in the file robjhyndmantsdldatadatanybirths. dat We can read the data into R, and store it as a time series object, by typing: Similarly, the file robjhyndmantsdldatadatafancy. dat contains monthly sales for a souvenir shop at a beach resort town in Queensland, Australia, for January 1987-December 1993 (original data from Wheelwright and Hyndman, 1998). We can read the data into R by typing: Plotting Time Series Once you have read a time series into R, the next step is usually to make a plot of the time series data, which you can do with the plot. ts() function in R. For example, to plot the time series of the age of death of 42 successive kings of England, we type: We can see from the time plot that this time series could probably be described using an additive model, since the random fluctuations in the data are roughly constant in size over time. Likewise, to plot the time series of the number of births per month in New York city, we type: We can see from this time series that there seems to be seasonal variation in the number of births per month: there is a peak every summer, and a trough every winter. Again, it seems that this time series could probably be described using an additive model, as the seasonal fluctuations are roughly constant in size over time and do not seem to depend on the level of the time series, and the random fluctuations also seem to be roughly constant in size over time. Similarly, to plot the time series of the monthly sales for the souvenir shop at a beach resort town in Queensland, Australia, we type: In this case, it appears that an additive model is not appropriate for describing this time series, since the size of the seasonal fluctuations and random fluctuations seem to increase with the level of the time series. Thus, we may need to transform the time series in order to get a transformed time series that can be described using an additive model. For example, we can transform the time series by calculating the natural log of the original data: Here we can see that the size of the seasonal fluctuations and random fluctuations in the log-transformed time series seem to be roughly constant over time, and do not depend on the level of the time series. Thus, the log-transformed time series can probably be described using an additive model. Decomposing Time Series Decomposing a time series means separating it into its constituent components, which are usually a trend component and an irregular component, and if it is a seasonal time series, a seasonal component. Decomposing Non-Seasonal Data A non-seasonal time series consists of a trend component and an irregular component. Decomposing the time series involves trying to separate the time series into these components, that is, estimating the the trend component and the irregular component. To estimate the trend component of a non-seasonal time series that can be described using an additive model, it is common to use a smoothing method, such as calculating the simple moving average of the time series. The SMA() function in the 8220TTR8221 R package can be used to smooth time series data using a simple moving average. To use this function, we first need to install the 8220TTR8221 R package (for instructions on how to install an R package, see How to install an R package ). Once you have installed the 8220TTR8221 R package, you can load the 8220TTR8221 R package by typing: You can then use the 8220SMA()8221 function to smooth time series data. To use the SMA() function, you need to specify the order (span) of the simple moving average, using the parameter 8220n8221. For example, to calculate a simple moving average of order 5, we set n5 in the SMA() function. For example, as discussed above, the time series of the age of death of 42 successive kings of England appears is non-seasonal, and can probably be described using an additive model, since the random fluctuations in the data are roughly constant in size over time: Thus, we can try to estimate the trend component of this time series by smoothing using a simple moving average. To smooth the time series using a simple moving average of order 3, and plot the smoothed time series data, we type: There still appears to be quite a lot of random fluctuations in the time series smoothed using a simple moving average of order 3. Thus, to estimate the trend component more accurately, we might want to try smoothing the data with a simple moving average of a higher order. This takes a little bit of trial-and-error, to find the right amount of smoothing. For example, we can try using a simple moving average of order 8: The data smoothed with a simple moving average of order 8 gives a clearer picture of the trend component, and we can see that the age of death of the English kings seems to have decreased from about 55 years old to about 38 years old during the reign of the first 20 kings, and then increased after that to about 73 years old by the end of the reign of the 40th king in the time series. Decomposing Seasonal Data A seasonal time series consists of a trend component, a seasonal component and an irregular component. Decomposing the time series means separating the time series into these three components: that is, estimating these three components. To estimate the trend component and seasonal component of a seasonal time series that can be described using an additive model, we can use the 8220decompose()8221 function in R. This function estimates the trend, seasonal, and irregular components of a time series that can be described using an additive model. The function 8220decompose()8221 returns a list object as its result, where the estimates of the seasonal component, trend component and irregular component are stored in named elements of that list objects, called 8220seasonal8221, 8220trend8221, and 8220random8221 respectively. For example, as discussed above, the time series of the number of births per month in New York city is seasonal with a peak every summer and trough every winter, and can probably be described using an additive model since the seasonal and random fluctuations seem to be roughly constant in size over time: To estimate the trend, seasonal and irregular components of this time series, we type: The estimated values of the seasonal, trend and irregular components are now stored in variables birthstimeseriescomponentsseasonal, birthstimeseriescomponentstrend and 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 assum e 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