Home
%3CLINGO-SUB%20id%3D%22lingo-sub-560598%22%20slang%3D%22en-US%22%3EVideo%20Anomaly%20Detection%20with%20Deep%20Predictive%20Coding%20Networks%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-560598%22%20slang%3D%22en-US%22%3E%3CH1%20id%3D%22toc-hId-1932529000%22%20id%3D%22toc-hId-1932529000%22%3EVideo%20Anomaly%20Detection%20with%20Deep%20Predictive%20Coding%20Networks%3C%2FH1%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CBLOCKQUOTE%3E%0A%3CP%3EThe%20code%20to%20reproduce%20this%20approach%20can%20be%20found%20on%20github%3A%20%3CA%20href%3D%22https%3A%2F%2Fgithub.com%2FMicros%2Foft%2FMLOps_VideoAnomalyDetection%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehttps%3A%2F%2Fgithub.com%2FMicrosoft%2FMLOps_VideoAnomalyDetection%3C%2FA%3E.%3C%2FP%3E%0A%3C%2FBLOCKQUOTE%3E%0A%3CH2%20id%3D%22toc-hId--816141466%22%20id%3D%22toc-hId--816141466%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId-926668869%22%20id%3D%22toc-hId-926668869%22%3EBackground%3C%2FH2%3E%0A%3CP%3EThe%20automation%20of%20detecting%20anomalous%20events%20in%20videos%20is%20a%20challenging%20problem%20that%20currently%20attracts%20a%20lot%20of%20attention%20by%20researchers%2C%20but%20also%20has%20broad%20applications%20across%20industry%20verticals.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EOne%20popular%20approach%20involves%20training%20deep%20recurrent%20neural%20networks%20to%20develop%20an%20in-depth%20understanding%20of%20the%20physical%20and%20causal%20rules%20in%20the%20observed%20scenes%2C%20to%20predict%20future%20frames%20in%20a%20video.%20It%20is%20then%20possible%20to%20detect%20if%20something%20unusual%20occurred%20in%20the%20video%2C%20because%20the%20model%20is%20unable%20to%20predict%20pixel%20values%20in%20the%20next%20frame%20of%20the%20video%2C%20resulting%20in%20a%20large%20error%20in%20the%20models%20prediction.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20approach%20can%20be%20used%20both%20in%20a%20supervised%20and%20unsupervised%20fashion%2C%20thus%20enabling%20the%20detection%20of%20predefined%20anomalies%2C%20but%20also%20of%20anomalous%20events%20that%20have%20never%20been%20experienced%20in%20the%20past.%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId--1625488092%22%20id%3D%22toc-hId--1625488092%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId-117322243%22%20id%3D%22toc-hId-117322243%22%3EScenario%3C%2FH2%3E%0A%3CP%3ETo%20demonstrate%20how%20to%20implement%20this%20approach%2C%20we%20will%20use%20a%20publicly%20available%20dataset%20from%20the%20University%20of%20California%2C%20San%20Diego%2C%20which%20uses%20stationary%20cameras%20to%20monitor%20walkways%20around%20campus.%20The%20goal%20is%20to%20use%20AI%20to%20detect%20anomalies%20in%20the%20pedestrian%20traffic%20on%20these%20walkways.%20Commonly%20occurring%20anomalies%20include%20bikers%2C%20skaters%2C%20small%20carts%2C%20and%20people%20walking%20across%20a%20walkway%20or%20in%20the%20grass%20that%20surrounds%20it.%20The%20goal%20is%20of%20course%20not%20to%20prosecute%20the%20people%20behind%20these%20anomalies%2C%20it's%20just%20a%20benchmark%20dataset%20for%20testing%20this%20approach.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20approach%20introduced%20here%20is%20applicable%20to%20various%20other%20scenarios.%20In%20manufacturing%2C%20the%20model%20can%20detect%20accidents%20on%20the%20factory%20floor%20(e.g.%20explosions%2C%20disregard%20of%20safety%20guidelines%2C%20injuries).%20In%20healthcare%2C%20it%20can%20be%20used%20for%20any%20kind%20of%20visual%20monitoring%20(e.g.%20hallways%20in%20hospitals%2C%20patients%20in%20bed%2C%20ultrasound).%20In%20financial%20services%2C%20it%20can%20be%20used%20to%20detect%20suspicious%20behavior%20(e.g.%20bank%20robbery%2C%20theft%20at%20ATM).%20In%20the%20agricultural%20industry%2C%20it%20can%20be%20used%20to%20detect%20anomalies%20in%20the%20behavior%20of%20ranch%20animals%20(e.g.%20limping%2C%20predators%2C%20thieves).%20In%20the%20education%20sector%2C%20it%20can%20be%20used%20to%20detect%20bullying%20or%20other%20violence%20in%20schools%20or%20universities.%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId-1860132578%22%20id%3D%22toc-hId-1860132578%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId--692024383%22%20id%3D%22toc-hId--692024383%22%3EOutline%3C%2FH2%3E%0A%3CP%3EIn%20this%20blog%20post%2C%20I%20will%20first%20provide%20an%20overview%20of%20the%20approach.%20Then%20I%20will%20talk%20about%20how%20to%20train%20your%20model%20using%20AML%20services.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIn%20future%20blog%20posts%2C%20I%20will%20cover%20these%20topics%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3ETuning%20hyperparameters%20with%20HyperDrive%3C%2FLI%3E%0A%3CLI%3EDeploying%20a%20real-time%20webservice%20for%20anomaly%20detection%20to%20AKS.%3C%2FLI%3E%0A%3CLI%3EDefining%20an%20AML%20pipeline%20that%20combines%20all%20steps%20from%20data%20ingestion%20and%20preparation%2C%20model%20training%20and%20hyperparameter%20tuning%2C%20model%20registration%2C%20and%20deployment.%3C%2FLI%3E%0A%3CLI%3EPerforming%20transfer%20learning%2C%20to%20quickly%20scale%20your%20solution%20to%20new%20videos.%3C%2FLI%3E%0A%3CLI%3ESetting%20up%20a%20DevOps%20build%20pipeline%20for%20retraining%20your%20model.%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CH2%20id%3D%22toc-hId-1050785952%22%20id%3D%22toc-hId-1050785952%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId--1501371009%22%20id%3D%22toc-hId--1501371009%22%3EOverview%3C%2FH2%3E%0A%3CH3%20id%3D%22toc-hId-44925821%22%20id%3D%22toc-hId-44925821%22%3ENeural%20Network%20Architecture%3C%2FH3%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CBLOCKQUOTE%3E%0A%3CP%3EOur%20solution%20relies%20an%20existing%20architecture%20(Lotter%2C%20W.%2C%20Kreiman%2C%20G.%20and%20Cox%2C%20D.%2C%202016.%20Deep%20predictive%20coding%20networks%20for%20video%20prediction%20and%20unsupervised%20learning.%20arXiv%20preprint%20arXiv%3A1605.08104.).%20The%20source%20code%20of%20the%20original%20architecture%20is%20available%20on%20%3CA%20href%3D%22https%3A%2F%2Fcoxlab.github.io%2Fprednet%2F%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3Egithub%3C%2FA%3E.%3C%2FP%3E%0A%3C%2FBLOCKQUOTE%3E%0A%3CP%3EThe%20model%20learns%20to%20maintain%20a%20temporally%20evolving%20representation%20of%20what%20is%20going%20on%20in%20the%20video%2C%20because%20it%20has%20recurrent%20elements.%20The%20recurrent%20elements%20exist%20at%20each%20depth%20of%20the%20model%2C%20so%20that%20deeper%20layers%20form%20more%20abstract%20and%20complex%20representations%20of%20the%20videos.%20The%20following%20figure%20from%20the%20github%20repository%20for%20Prednet%20describes%20the%20basic%20architecture%20of%20the%20model.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20style%3D%22width%3A%20612px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Fgxcuf89792.i.lithium.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F113032i43B3552350F21F93%2Fimage-size%2Flarge%3Fv%3D1.0%26amp%3Bpx%3D999%22%20alt%3D%22prednet_model.png%22%20title%3D%22prednet_model.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3EAt%20each%20depth%3CCODE%3El%3C%2FCODE%3E%2C%20the%20model%20has%20four%20types%20of%20convolutional%20layers%3A%20a%20recurrent%20layer%20(%3CA%20href%3D%22https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FLong_short-term_memory%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3ELSTM%3C%2FA%3E)%20%3CCODE%3ER_l%3C%2FCODE%3E%2C%20and%20regular%20convolutional%20layers%20%3CCODE%3EA%5Ehat_l%3C%2FCODE%3E%2C%20%3CCODE%3EA_l%3C%2FCODE%3E%2C%20and%20%3CCODE%3EE_l%3C%2FCODE%3E.%20%3CCODE%3EA%3C%2FCODE%3E%20represents%20the%20input%20at%20depth%20%3CCODE%3El%3C%2FCODE%3E.%20This%20is%20the%20current%20video%20frame%20for%20the%20most%20shallow%20layer%20of%20the%20model.%20For%20deeper%20layers%2C%20this%20is%20the%20output%20of%20layer%20%3CCODE%3EE%3C%2FCODE%3E%20from%20the%20previous%20depth%20(%3CCODE%3El%20-%201%3C%2FCODE%3E).%20Layer%20%3CCODE%3EE%3C%2FCODE%3E%20represents%20the%20error%20in%20the%20prediction%20of%20the%20model%2C%20that%20is%20the%20difference%20between%20%3CCODE%3EA%3C%2FCODE%3E%20and%20the%20prediction%20of%20the%20model%20%3CCODE%3EAhat%3C%2FCODE%3E.%20The%20prediction%20%3CCODE%3EAhat%3C%2FCODE%3E%20is%20based%20on%20an%20internal%20state%20representation%2C%20which%20is%20provided%20by%20the%20recurrent%20layer%20%3CCODE%3ER%3C%2FCODE%3E.%3C%2FP%3E%0A%3CP%3EBy%20passing%20the%20error%20%3CCODE%3EE%3C%2FCODE%3E%20to%20next%20%3CCODE%3EA%3C%2FCODE%3E%2C%20deeper%20layers%20are%20required%20to%20learn%20increasingly%20abstract%20representations%20of%20the%20task%20to%20reduce%20the%20overall%20performance%20of%20the%20model.%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId--1425441070%22%20id%3D%22toc-hId--1425441070%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId-317369265%22%20id%3D%22toc-hId-317369265%22%3EAnomaly%20Detection%20-%20Supervised%20and%20Unsupervised%3C%2FH2%3E%0A%3CP%3EOnce%20the%20model%20was%20successfully%20trained%20with%20a%20dataset%20that%20does%20%3CEM%3Enot%3C%2FEM%3E%20contain%20(m)any%20anomalies%2C%20the%20model%20can%20then%20be%20used%20to%20detect%20anomalies.%20This%20can%20be%20done%20in%20a%20supervised%20fashion%2C%20but%20you%20can%20also%20perform%20unsupervised%20anomaly%20detection.%20You%20can%20also%20combine%20the%20two%20approaches%2C%20using%20the%20output%20of%20your%20neural%20network%20for%20supervised%20and%20unsupervised%20anomaly%20detection%20at%20the%20same%20time.%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId-263228241%22%20id%3D%22toc-hId-263228241%22%3E%26nbsp%3B%3C%2FH3%3E%0A%3CH3%20id%3D%22toc-hId-2006038576%22%20id%3D%22toc-hId-2006038576%22%3EUnsupervised%20Anomaly%20Detection%3C%2FH3%3E%0A%3CP%3EThere%20are%20several%20scenarios%20under%20which%20you%20would%20perform%20unsupervised%20anomaly%20detection%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3EYou%20don't%20have%20a%20labeled%20dataset.%20Any%20supervised%20approach%20requires%20a%20dataset%20in%20which%20video%20frames%20are%20labeled%20for%20whether%20they%20contain%20anomalies.%3C%2FLI%3E%0A%3CLI%3EYou%20want%20to%20be%20able%20to%20detect%20novel%20anomalies.%20If%20you%20use%20a%20supervised%20anomaly%20detection%20approach%2C%20you%20are%20limited%20to%20detecting%20anomalies%20that%20have%20occurred%20in%20the%20past.%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CP%3EFor%20these%20reasons%2C%20unsupervised%20anomaly%20detection%20solutions%20are%20often%20preferred.%20Anomalies%20are%20rare%20(hopefully)%2C%20so%20it%20is%20often%20difficult%20to%20find%20a%20dataset%20with%20enough%20anomalies%20for%20training.%20You%20also%20want%20to%20be%20able%20to%20detect%20anomalies%20that%20you%20have%20never%20experienced%20before%20or%20that%20are%20unique.%20Imagine%20an%20UFO%20landing%20on%20UCSD%20campus.%20Would%20you%20want%20be%20able%20to%20detect%20that%20UFO%20the%20very%20first%20time%20it%20shows%20up%3F%20Or%20do%20you%20want%20to%20rely%20on%20an%20approach%20where%20you%20need%20to%20wait%20until%20you%20have%20enough%20labeled%20data%20to%20use%20a%20supervised%20approach%20for%20UFO%20detection%3F%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EUsing%20unsupervised%20anomaly%20detection%20is%20as%20easy%20as%20it%20is%20versatile.%20You%20can%20simply%20define%20a%20threshold%20on%20the%20model's%20prediction%20error%20for%20each%20video%20frame%20(e.g.%20the%20absolute%20sum%20difference%20between%20predicted%20and%20true%20pixel%20values).%20You%20then%20flag%20all%20frames%20as%20anomalous%2C%20for%20which%20the%20error%20was%20above%20that%20threshold.%20A%20slightly%20more%20advanced%20approach%20would%20be%20to%20deal%20with%20possible%20fluctuations%20in%20your%20data.%20For%20example%2C%20there%20are%20likely%20more%20pedestrians%20on%20walkways%20between%20classes%20than%20there%20are%20while%20classes%20are%20in%20session.%20When%20there%20are%20more%20pedestrians%2C%20the%20prediction%20error%20will%20overall%20be%20higher%20and%20you%20may%20end%20up%20incorrectly%20flagging%20a%20lot%20of%20frames%20as%20containing%20anomalies.%20One%20options%20for%20this%20scenario%20would%20be%20to%20send%20the%20output%20of%20your%20model%20to%20the%20new%20%3CA%20href%3D%22https%3A%2F%2Fazure.microsoft.com%2Fen-us%2Fservices%2Fcognitive-services%2Fanomaly-detector%2F%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EAzure%20cognitive%20service%20for%20anomaly%20detection%3C%2FA%3E.%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId--546118385%22%20id%3D%22toc-hId--546118385%22%3E%26nbsp%3B%3C%2FH3%3E%0A%3CH3%20id%3D%22toc-hId-1196691950%22%20id%3D%22toc-hId-1196691950%22%3ESupervised%20Anomaly%20Detection%3C%2FH3%3E%0A%3CP%3EThe%20number%20one%20reason%20to%20use%20a%20supervised%20anomaly%20detection%20approach%20is%20probably%20that%20you%20could%20try%20to%20categorize%20anomalies%20in%20order%20to%20triage%20tasks%20to%20handle%20them.%20If%20your%20service%20detects%20that%20a%20crime%20was%20committed%2C%20it%20calls%20campus%20security%20or%20police.%20If%20somebody%20appears%20to%20be%20injured%2C%20the%20service%20can%20call%20an%20ambulance.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ETo%20create%20a%20supervised%20anomaly%20detection%20solution%2C%20you%20could%20train%20a%20second%20model%20(e.g.%20a%20decision%20tree)%20on%20the%20output%20of%20your%20recurrent%20model%2C%20either%20features%20derived%20from%20the%20model's%20prediction%20errors%20or%20on%20the%20activation%20in%20one%20of%20the%20hidden%20layers.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EAnother%20approach%20would%20be%20to%20modify%20your%20trained%20neural%20network%20to%20also%20have%20a%20softmax%20layer%20for%20classifying%20anomalies%20in%20video%20frames.%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId-441486348%22%20id%3D%22toc-hId-441486348%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId--2110670613%22%20id%3D%22toc-hId--2110670613%22%3EModel%20Development%3C%2FH2%3E%0A%3CP%3EThis%20is%20done%20in%20the%20following%20steps%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3EDefine%20the%20model%20architecture%20and%20optimizer%20for%20training%20it.%3C%2FLI%3E%0A%3CLI%3ESet%20up%20logging%20so%20that%20you%20can%20monitor%20training%20progress%20in%20the%20Azure%20portal.%3C%2FLI%3E%0A%3CLI%3EConnect%20to%20your%20Azure%20ML%20workspace.%3C%2FLI%3E%0A%3CLI%3EConnect%20to%20your%20AML%20Compute%20target.%3C%2FLI%3E%0A%3CLI%3EDefine%20Estimator%20object.%3C%2FLI%3E%0A%3CLI%3ESubmit%20your%20job%20to%20your%20AML%20experiment%20for%20execution.%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CP%3EThe%20first%20two%20steps%20involve%20changes%20to%20a%20%3CEM%3Escript_file%3C%2FEM%3E%20(%3CA%20href%3D%22https%3A%2F%2Fgithub.com%2Fmicrosoft%2FMLOps_VideoAnomalyDetection%2Fblob%2Fmaster%2Ftrain.py%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Etrain.py%3C%2FA%3E).%20The%20remaining%20steps%20are%20achieved%20by%20creating%20a%20control%20script%20(%3CA%20href%3D%22https%3A%2F%2Fgithub.com%2Fmicrosoft%2FMLOps_VideoAnomalyDetection%2Fblob%2Fmaster%2Ftrain_remotely.py%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Etrain_remotely.py%3C%2FA%3E)%20that%20handles%20resources%20and%20job%20submission.%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId-2130155659%22%20id%3D%22toc-hId-2130155659%22%3E%26nbsp%3B%3C%2FH3%3E%0A%3CH3%20id%3D%22toc-hId--422001302%22%20id%3D%22toc-hId--422001302%22%3EDefine%20model%20Architecture%20and%20Optimizer%3C%2FH3%3E%0A%3CP%3EThe%20first%20step%20is%20to%20define%20the%20model%2C%20its%20inputs%20and%20outputs%20(errors).%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%23%20file%3A%20train.py%20%0A%23%20import%20custom%20neural%20network%20definition%20%0Afrom%20prednet%20import%20Prednet%0A%0A%23%20import%20standard%20keras%20modules%20%0Aimport%20keras%20%0Afrom%20keras.optimizers%20import%20Adam%20%0Afrom%20keras.layers%20import%20Input%20%0A%0A%23%20create%20an%20instance%20of%20the%20model%20%0Aprednet%20%3D%20PredNet(output_mode%3D'error')%0A%0A%23%20define%20tensor%20to%20hold%20inputs%20%0Ainputs%20%3D%20Input(n_videoframes%2C%20height%2C%20width%2C%20depth)%0A%0A%23%20errors%20will%20be%20(batch_size%2C%20nt%2C%20nb_layers)%0Aerrors%20%3D%20prednet(inputs)%3C%2FPRE%3E%0A%3CP%3EThe%20second%20step%20is%20to%20set%20up%20the%20%3CA%20href%3D%22https%3A%2F%2Fkeras.io%2Foptimizers%2F%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3Eoptimizer%3C%2FA%3E%20for%20training%20the%20model.%20Here%2C%20we%20are%20using%20the%20Adam%20optimizer.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%3CCODE%3E%3CFONT%20color%3D%22%23808080%22%3E%3CFONT%20color%3D%22%23333333%22%3E%23%20file%3A%20train.py%0A%23%20define%20optimizer%0Aoptimizer%20%3D%20Adam(lr%3Dlearning_rate%2C%20decay%3Dlearning_rate_decay)%0A%0A%23%20put%20it%20all%20together%0Amodel%20%3D%20keras.models.Model(inputs%3Dinputs%2C%20outputs%3Dfinal_errors)%0Amodel.compile(loss%3D'mean_absolute_error'%2C%20optimizer%3Doptimizer)%3C%2FFONT%3E%20%3C%2FFONT%3E%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EAbove%2C%20%3CCODE%3E%3CFONT%20color%3D%22%23808080%22%3Efinal_errors%3C%2FFONT%3E%3C%2FCODE%3E%20is%20a%20scalar%20value%20derived%20from%20%3CFONT%20color%3D%22%23808080%22%3E%3CCODE%3E%3CFONT%20color%3D%22%23808080%22%3Eerrors%3C%2FFONT%3E%3C%2FCODE%3E%3C%2FFONT%3E.%20See%20the%20code%20repository%20for%20details.%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId--734879596%22%20id%3D%22toc-hId--734879596%22%3ESet%20up%20logging%20so%20that%20you%20can%20monitor%20training%20progress%20in%20the%20Azure%20portal%3C%2FH3%3E%0A%3CP%3EThe%20next%20step%20is%20to%20ensure%20that%20hyperparameters%20and%20training%20progress%20are%20properly%20logged%20in%20your%20AML%20workspace%20so%20you%20can%20monitor%20performance%20in%20the%20%3CA%20href%3D%22https%3A%2F%2Fportal.azure.com%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3EAzure%20portal%3C%2FA%3E%20while%20your%20job%20is%20running.%3C%2FP%3E%0A%3CP%3EThis%20is%20how%20you%20can%20log%20hyperparameters.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%23%20file%3A%20train.py%0Afrom%20azureml.core%20import%20Run%0A%0A%23%20log%20hyper%20parameters%0Arun.log('learning_rate'%2C%20learning_rate)%0Arun.log('lr_decay'%2C%20lr_decay)%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ETo%20log%20training%20progress%2C%20we%20have%20to%20create%20a%20custom%20callback%20for%20our%20Keras%20model.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%23%20file%3A%20train.py%0Afrom%20keras.callbacks%20import%20Callback%0A%0Aclass%20LogRunMetrics(Callback)%3A%0A%20%20%20%23%20callback%20at%20the%20end%20of%20every%20epoch%0A%20%20%20def%20on_epoch_end(self%2C%20epoch%2C%20log)%3A%0A%20%20%20%20%20%20%23%20log%20a%20value%20repeated%20which%20creates%20a%20list%0A%20%20%20%20%20%20run.log('val_loss'%2C%20log%5B'val_loss'%5D)%0A%20%20%20%20%20%20run.log('loss'%2C%20log%5B'loss'%5D)%0A%0Acallbacks%20%3D%20%5BLogRunMetrics()%5D%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EYou%20can%20also%20log%20an%20image%20to%20your%20AML%20workspace.%20For%20example%2C%20when%20the%20training%20run%20is%20complete%2C%20you%20can%20create%20a%20plot%20with%20matplotlib%20to%20show%20performance%20(%3CFONT%20color%3D%22%23808080%22%3E%3CCODE%3Eloss%3C%2FCODE%3E%3C%2FFONT%3E)%20on%20the%20training%20and%20the%20validation%20set.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%23%20file%3A%20train.py%0A%0Aimport%20matplotlib.pyplot%20as%20plt%0Aplt.figure(figsize%3D(6%2C%203))%0Aplt.title('(%7B%7D%20epochs)'.format(nb_epoch)%2C%20fontsize%3D14)%0Aplt.plot(history.history%5B'val_loss'%5D%2C%20'b-'%2C%20label%3D'Validation%20Loss'%2C%20lw%3D4%2C%20alpha%3D0.5)%0Aplt.plot(history.history%5B'loss'%5D%2C%20'g-'%2C%20label%3D'Train%20Loss'%2C%20lw%3D4%2C%20alpha%3D0.5)%0Aplt.legend(fontsize%3D12)%0Aplt.grid(True)%0A%0Arun.log_image('Validation%20Loss'%2C%20plot%3Dplt)%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId-1007930739%22%20id%3D%22toc-hId-1007930739%22%3ESet%20up%20AML%20Workspace%20and%20Experiment%3C%2FH3%3E%0A%3CP%3EThe%20%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fmachine-learning%2Fservice%2Fconcept-azure-machine-learning-architecture%23workspace%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EAML%20workspace%3C%2FA%3E%20is%20awesome%20for%20machine%20learning%20experimentation.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20workspace%20is%20the%20top-level%20resource%20for%20Azure%20Machine%20Learning%20service.%20It%20provides%20a%20centralized%20place%20to%20work%20with%20all%20the%20artifacts%20you%20create%20when%20you%20use%20Azure%20Machine%20Learning%20service.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20workspace%20keeps%20a%20list%20of%20compute%20targets%20that%20you%20can%20use%20to%20train%20your%20model.%20It%20also%20keeps%20a%20history%20of%20the%20training%20runs%2C%20including%20logs%2C%20metrics%2C%20output%2C%20and%20a%20snapshot%20of%20your%20scripts.%20You%20use%20this%20information%20to%20determine%20which%20training%20run%20produces%20the%20best%20model.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%23%20file%3A%20train_remotely.py%0Afrom%20azureml.core%20import%20Workspace%2C%20Experiment%0Aws%20%3D%20Workspace.create(name%3Dworkspace_name%2C%20subscription_id%3Dazure_subscription_id%2C%20resource_group%3Dresource_group%2C%20location%3Dazure_region)%0A%0Aexp%20%3D%20Experiment(ws%2C%20experiment_name)%3C%2FPRE%3E%0A%3CP%3EFor%20more%20info%20on%20how%20to%20setup%20your%20AML%20workspace%2C%20go%20%3CA%20href%3D%22https%3A%2F%2Fgithub.com%2FAzure%2FMachineLearningNotebooks%2Fblob%2Fmaster%2Fconfiguration.ipynb%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehere%3C%2FA%3E%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId--1544226222%22%20id%3D%22toc-hId--1544226222%22%3EConnect%20to%20AML%20Compute%20target%3C%2FH3%3E%0A%3CP%3EYou%20can%20either%20create%20a%20new%20%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fmachine-learning%2Fservice%2Fconcept-azure-machine-learning-architecture%23compute-target%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EAML%20compute%20target%3C%2FA%3E%2C%20or%20connect%20to%20an%20existing%20one.%3C%2FP%3E%0A%3CP%3EThe%20model%20will%20be%20trained%20on%20this%20remote%20compute%20target.%20When%20you%20create%20it%2C%20you%20can%20specify%20a%20couple%20of%20important%20parameters.%20-%20vm_size%20-%20the%20size%20of%20the%20compute%20target.%20Make%20sure%20you%20pick%20on%20with%20a%20GPU.%20Read%20more%20here%3A%20%3CA%20href%3D%22https%3A%2F%2Faka.ms%2Fazureml-vm-details%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehttps%3A%2F%2Faka.ms%2Fazureml-vm-details%3C%2FA%3E.%20-%20min_nodes%20-%20It's%20probably%20best%20to%20leave%20this%20at%20the%20default%20(0)%2C%20so%20that%20your%20cluster%20scales%20down%20completely%20when%20you%20don't%20use%20it%20for%20%3CCODE%3E%3CFONT%20color%3D%22%23808080%22%3Eidle_seconds_before_scaledown%3C%2FFONT%3E%3C%2FCODE%3E%20(see%20below)%2C%20which%20can%20save%20you%20a%20lot%20of%20money.%20-%20max_nodes%20-%20Maximum%20number%20of%20nodes%20to%20use%20on%20the%20cluster%20-%20idle_seconds_before_scaledown%20-%20Node%20idle%20time%20in%20seconds%20before%20scaling%20down%20the%20cluster.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%23%20file%3A%20train_remotely.py%0A%0Afrom%20azureml.core.compute%20import%20AmlCompute%0Afrom%20azureml.core.compute%20import%20ComputeTarget%0A%0Atry%3A%0A%20%20%20gpu_compute_target%20%3D%20AmlCompute(workspace%3Dws%2C%20name%3Dgpu_compute_name)%0A%20%20%20print(%22found%20existing%20compute%20target%3A%20%25s%22%20%25%20gpu_compute_name)%0Aexcept%3A%0A%20%20%20print('Creating%20a%20new%20compute%20target...')%0A%20%20%20provisioning_config%20%3D%20AmlCompute.provisioning_configuration(vm_size%3D'STANDARD_NC6'%2C%20max_nodes%3D5%2C%20idle_seconds_before_scaledown%3D1800)%0A%0A%23%20create%20the%20cluster%0Agpu_compute_target%20%3D%20ComputeTarget.create(ws%2C%20gpu_compute_name%2C%20provisioning_config)%0A%0A%23%20can%20poll%20for%20a%20minimum%20number%20of%20nodes%20and%20for%20a%20specific%20timeout.%0A%23%20if%20no%20min%20node%20count%20is%20provided%20it%20uses%20the%20scale%20settings%20for%20the%20cluster%0Agpu_compute_target.wait_for_completion(show_output%3DTrue%2C%20min_node_count%3DNone%2C%20timeout_in_minutes%3D20)%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId-198584113%22%20id%3D%22toc-hId-198584113%22%3EDefine%20Estimator%3C%2FH3%3E%0A%3CP%3E%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fpython%2Fapi%2Fazureml-train-core%2Fazureml.train.estimator%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EEstimators%3C%2FA%3E%20are%20the%20building%20block%20for%20training.%20An%20estimator%20encapsulates%20the%20training%20code%20and%20parameters%2C%20the%20compute%20resources%20and%20runtime%20environment%20for%20a%20particular%20training%20scenario.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%23%20file%3A%20train_remotely.py%0Afrom%20azureml.core.container_registry%20import%20ContainerRegistry%0Afrom%20azureml.train.estimator%20import%20Estimator%0A%0A%23%20configure%20access%20to%20ACR%20for%20pulling%20our%20custom%20docker%20image%0Aacr%20%3D%20ContainerRegistry()%0Aacr.address%20%3D%20config%5B'acr_address'%5D%0Aacr.username%20%3D%20config%5B'acr_username'%5D%0Aacr.password%20%3D%20config%5B'acr_password'%5D%0A%0Aest%20%3D%20Estimator(source_directory%3Dscript_folder%2C%0A%20%20%20%20%20%20%20%20%20compute_target%3Dgpu_compute_target%2C%0A%20%20%20%20%20%20%20%20%20entry_script%3D'train.py'%2C%0A%20%20%20%20%20%20%20%20%20use_gpu%3DTrue%2C%0A%20%20%20%20%20%20%20%20%20node_count%3D1%2C%0A%20%20%20%20%20%20%20%20%20custom_docker_image%20%3D%20%22wopauli_1.8-gpu%3A1%22%2C%0A%20%20%20%20%20%20%20%20%20image_registry_details%3Dacr%2C%0A%20%20%20%20%20%20%20%20%20user_managed%3DTrue)%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ENote%20how%20we%20are%20using%20a%20%3CCODE%3E%3CFONT%20color%3D%22%23808080%22%3Ecustom_docker_image%3C%2FFONT%3E%3C%2FCODE%3E.%20This%20is%20because%20we%20are%20using%20Tensorflow%201.8%20and%20Keras%202.0.8%2C%20which%20are%20no%20longer%20supported%20by%20AML%20services.%20Apart%20from%20that%2C%20knowing%20how%20to%20create%20a%20custom%20docker%20image%20for%20training%20also%20gives%20you%20full%20control%20over%20your%20execution%20environment%20and%20can%20speed%20up%20provisioning%20compute%20targets%20considerably.%3C%2FP%3E%0A%3CP%3EThe%20steps%20to%20create%20a%20custom%20docker%20image%20are%20described%20%3CA%20href%3D%22https%3A%2F%2Fgithub.com%2Fmicrosoft%2FMLOps_VideoAnomalyDetection%2Fblob%2Fmaster%2Fconfig%2FReadme.md%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehere%3C%2FA%3E.%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId-1941394448%22%20id%3D%22toc-hId-1941394448%22%3ESubmit%20your%20job%20to%20your%20AML%20experiment%20for%20execution.%3C%2FH3%3E%0A%3CP%3ENow%20we%20are%20ready%20to%20submit%20our%20job%20to%20run%20on%20our%20AML%20compute%20target.%20The%20last%20line%20below%20keeps%20you%20connected%20to%20the%20job%20while%20it%20is%20running%20remotely%2C%20so%20you%20can%20see%20progress%20printed%20on%20the%20command%20line.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%23%20file%3A%20train_remotely.py%0A%0Afrom%20azureml.core%20import%20Run%0Arun%20%3D%20exp.submit(est)%0Arun.wait_for_completion(show_output%3DTrue)%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIf%20everything%20works%20as%20expected%2C%20you%20should%20be%20able%20to%20see%20progress%20in%20the%20azure%20portal.%20Below%20is%20what%20this%20should%20look%20like%20after%20a%20successful%20training%20run.%20You%20can%20see%20%3CEM%3EAttributes%3C%2FEM%3E%2C%20like%20how%20long%20it%20ran%20and%20what%20the%20status%20is.%20You%20can%20also%20see%20%3CEM%3ETracked%20Metrics%3C%2FEM%3E%2C%20which%20includes%20hyperparameters%20and%20the%20performance%20of%20your%20model.%20The%20performance%20of%20the%20model%20(training%20loss%20and%20validation%20loss)%20are%20also%20shown%20in%20%3CEM%3ECharts%3C%2FEM%3E%20on%20the%20right.%20Plots%20like%20these%20are%20automatically%20created%20when%20you%20log%20lists%20of%20values%20to%20the%20portal.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20style%3D%22width%3A%20999px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Fgxcuf89792.i.lithium.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F113033i694EC044AF79C5AA%2Fimage-size%2Flarge%3Fv%3D1.0%26amp%3Bpx%3D999%22%20alt%3D%22portal_details.PNG%22%20title%3D%22portal_details.PNG%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CH3%20id%3D%22toc-hId--610762513%22%20id%3D%22toc-hId--610762513%22%3EDownload%20the%20trained%20model%3C%2FH3%3E%0A%3CP%3EIf%20you%20go%20to%20the%20panel%20for%20%3CEM%3EOutputs%3C%2FEM%3E%2C%20you%20can%20find%20a%20your%20trained%20model%20as%20a%20json%20file%2C%20with%20weights%20saved%20to%20a%20hdf5.%20To%20create%20an%20anomaly%20detection%20solution%2C%20you%20could%20now%20download%20those%20and%20run%20them%20on%20your%20test%20dataset.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20style%3D%22width%3A%20999px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Fgxcuf89792.i.lithium.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F113034i1D0552E45F084E9F%2Fimage-size%2Flarge%3Fv%3D1.0%26amp%3Bpx%3D999%22%20alt%3D%22portal_outputs.png%22%20title%3D%22portal_outputs.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId--1365968115%22%20id%3D%22toc-hId--1365968115%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId-376842220%22%20id%3D%22toc-hId-376842220%22%3ENext%20steps%3C%2FH2%3E%0A%3CP%3EPlease%20let%20me%20know%20in%20the%20comments%20below%20if%20you%20found%20this%20helpful.%20Be%20on%20the%20lookout%20for%20upcoming%20blog%20posts%20on%20getting%20more%20out%20of%20AML%20services%20for%20creating%20a%20video%20anomaly%20detection%20service.%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId-2119652555%22%20id%3D%22toc-hId-2119652555%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId--432504406%22%20id%3D%22toc-hId--432504406%22%3ELiterature%3C%2FH2%3E%0A%3CP%3EIf%20you%20want%20to%20find%20out%20more%20about%20anomaly%20detection%2C%20I%20recommend%20the%20following%20two%20items.%3C%2FP%3E%0A%3CUL%3E%0A%3CLI%3ETalk%20at%20Microsoft%20Research%3A%20%3CA%20href%3D%22https%3A%2F%2Fwww.microsoft.com%2Fen-us%2Fresearch%2Fvideo%2Fanomaly-detection-algorithms-explanations-applications%2F%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EAnomaly%20Detection%3A%20Algorithms%2C%20Explanations%2C%20Applications%3C%2FA%3E%3C%2FLI%3E%0A%3CLI%3EChandola%2C%20V.%2C%20Banerjee%2C%20A.%2C%20%26amp%3B%20Kumar%2C%20V.%20(2009).%20Anomaly%20detection%3A%20A%20survey.%20ACM%20computing%20surveys%20(CSUR)%2C%2041(3)%2C%2015.%20%3CA%20href%3D%22http%3A%2F%2Fwww.dtc.umn.edu%2Fpublications%2Freports%2F2008_16.pdf%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3Epdf%3C%2FA%3E%3C%2FLI%3E%0A%3C%2FUL%3E%3C%2FLINGO-BODY%3E%3CLINGO-TEASER%20id%3D%22lingo-teaser-560598%22%20slang%3D%22en-US%22%3E%3CP%3EThe%20automation%20of%20detecting%20anomalous%20events%20in%20videos%20is%20a%20challenging%20problem%20that%20currently%20attracts%20a%20lot%20of%20attention%20by%20researchers%2C%20but%20also%20has%20broad%20applications%20across%20industry%20verticals.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EOne%20popular%20approach%20involves%20training%20deep%20recurrent%20neural%20networks%20to%20develop%20an%20in-depth%20understanding%20of%20the%20physical%20and%20causal%20rules%20in%20the%20observed%20scenes%2C%20to%20predict%20future%20frames%20in%20a%20video.%20It%20is%20then%20possible%20to%20detect%20if%20something%20unusual%20occurred%20in%20the%20video%2C%20because%20the%20model%20is%20unable%20to%20predict%20pixel%20values%20in%20the%20next%20frame%20of%20the%20video%2C%20resulting%20in%20a%20large%20error%20in%20the%20models%20prediction.%3C%2FP%3E%0A%3CP%3EThe%20approach%20can%20be%20used%20both%20in%20a%20supervised%20and%20unsupervised%20fashion%2C%20thus%20enabling%20the%20detection%20of%20pre-defined%20anomalies%2C%20but%20also%20of%20anomalous%20events%20that%20have%20never%20been%20experienced%20in%20the%20past.%3C%2FP%3E%3C%2FLINGO-TEASER%3E
Microsoft

Video Anomaly Detection with Deep Predictive Coding Networks

 

The code to reproduce this approach can be found on github: https://github.com/Microsoft/MLOps_VideoAnomalyDetection.

 

Background

The automation of detecting anomalous events in videos is a challenging problem that currently attracts a lot of attention by researchers, but also has broad applications across industry verticals.

 

One popular approach involves training deep recurrent neural networks to develop an in-depth understanding of the physical and causal rules in the observed scenes, to predict future frames in a video. It is then possible to detect if something unusual occurred in the video, because the model is unable to predict pixel values in the next frame of the video, resulting in a large error in the models prediction.

 

The approach can be used both in a supervised and unsupervised fashion, thus enabling the detection of predefined anomalies, but also of anomalous events that have never been experienced in the past.

 

Scenario

To demonstrate how to implement this approach, we will use a publicly available dataset from the University of California, San Diego, which uses stationary cameras to monitor walkways around campus. The goal is to use AI to detect anomalies in the pedestrian traffic on these walkways. Commonly occurring anomalies include bikers, skaters, small carts, and people walking across a walkway or in the grass that surrounds it. The goal is of course not to prosecute the people behind these anomalies, it's just a benchmark dataset for testing this approach.

 

The approach introduced here is applicable to various other scenarios. In manufacturing, the model can detect accidents on the factory floor (e.g. explosions, disregard of safety guidelines, injuries). In healthcare, it can be used for any kind of visual monitoring (e.g. hallways in hospitals, patients in bed, ultrasound). In financial services, it can be used to detect suspicious behavior (e.g. bank robbery, theft at ATM). In the agricultural industry, it can be used to detect anomalies in the behavior of ranch animals (e.g. limping, predators, thieves). In the education sector, it can be used to detect bullying or other violence in schools or universities.

 

Outline

In this blog post, I will first provide an overview of the approach. Then I will talk about how to train your model using AML services.

 

In future blog posts, I will cover these topics:

  1. Tuning hyperparameters with HyperDrive
  2. Deploying a real-time webservice for anomaly detection to AKS.
  3. Defining an AML pipeline that combines all steps from data ingestion and preparation, model training and hyperparameter tuning, model registration, and deployment.
  4. Performing transfer learning, to quickly scale your solution to new videos.
  5. Setting up a DevOps build pipeline for retraining your model.

 

Overview

Neural Network Architecture

 

Our solution relies an existing architecture (Lotter, W., Kreiman, G. and Cox, D., 2016. Deep predictive coding networks for video prediction and unsupervised learning. arXiv preprint arXiv:1605.08104.). The source code of the original architecture is available on github.

The model learns to maintain a temporally evolving representation of what is going on in the video, because it has recurrent elements. The recurrent elements exist at each depth of the model, so that deeper layers form more abstract and complex representations of the videos. The following figure from the github repository for Prednet describes the basic architecture of the model.

 

prednet_model.png

At each depth l, the model has four types of convolutional layers: a recurrent layer (LSTM) R_l, and regular convolutional layers A^hat_l, A_l, and E_l. A represents the input at depth l. This is the current video frame for the most shallow layer of the model. For deeper layers, this is the output of layer E from the previous depth (l - 1). Layer E represents the error in the prediction of the model, that is the difference between A and the prediction of the model Ahat. The prediction Ahat is based on an internal state representation, which is provided by the recurrent layer R.

By passing the error E to next A, deeper layers are required to learn increasingly abstract representations of the task to reduce the overall performance of the model.

 

Anomaly Detection - Supervised and Unsupervised

Once the model was successfully trained with a dataset that does not contain (m)any anomalies, the model can then be used to detect anomalies. This can be done in a supervised fashion, but you can also perform unsupervised anomaly detection. You can also combine the two approaches, using the output of your neural network for supervised and unsupervised anomaly detection at the same time.

 

Unsupervised Anomaly Detection

There are several scenarios under which you would perform unsupervised anomaly detection:

  1. You don't have a labeled dataset. Any supervised approach requires a dataset in which video frames are labeled for whether they contain anomalies.
  2. You want to be able to detect novel anomalies. If you use a supervised anomaly detection approach, you are limited to detecting anomalies that have occurred in the past.

For these reasons, unsupervised anomaly detection solutions are often preferred. Anomalies are rare (hopefully), so it is often difficult to find a dataset with enough anomalies for training. You also want to be able to detect anomalies that you have never experienced before or that are unique. Imagine an UFO landing on UCSD campus. Would you want be able to detect that UFO the very first time it shows up? Or do you want to rely on an approach where you need to wait until you have enough labeled data to use a supervised approach for UFO detection?

 

Using unsupervised anomaly detection is as easy as it is versatile. You can simply define a threshold on the model's prediction error for each video frame (e.g. the absolute sum difference between predicted and true pixel values). You then flag all frames as anomalous, for which the error was above that threshold. A slightly more advanced approach would be to deal with possible fluctuations in your data. For example, there are likely more pedestrians on walkways between classes than there are while classes are in session. When there are more pedestrians, the prediction error will overall be higher and you may end up incorrectly flagging a lot of frames as containing anomalies. One options for this scenario would be to send the output of your model to the new Azure cognitive service for anomaly detection.

 

Supervised Anomaly Detection

The number one reason to use a supervised anomaly detection approach is probably that you could try to categorize anomalies in order to triage tasks to handle them. If your service detects that a crime was committed, it calls campus security or police. If somebody appears to be injured, the service can call an ambulance.

 

To create a supervised anomaly detection solution, you could train a second model (e.g. a decision tree) on the output of your recurrent model, either features derived from the model's prediction errors or on the activation in one of the hidden layers.

 

Another approach would be to modify your trained neural network to also have a softmax layer for classifying anomalies in video frames.

 

Model Development

This is done in the following steps:

  1. Define the model architecture and optimizer for training it.
  2. Set up logging so that you can monitor training progress in the Azure portal.
  3. Connect to your Azure ML workspace.
  4. Connect to your AML Compute target.
  5. Define Estimator object.
  6. Submit your job to your AML experiment for execution.

The first two steps involve changes to a script_file (train.py). The remaining steps are achieved by creating a control script (train_remotely.py) that handles resources and job submission.

 

Define model Architecture and Optimizer

The first step is to define the model, its inputs and outputs (errors).

 

# file: train.py 
# import custom neural network definition 
from prednet import Prednet

# import standard keras modules 
import keras 
from keras.optimizers import Adam 
from keras.layers import Input 

# create an instance of the model 
prednet = PredNet(output_mode='error')

# define tensor to hold inputs 
inputs = Input(n_videoframes, height, width, depth)

# errors will be (batch_size, nt, nb_layers)
errors = prednet(inputs)

The second step is to set up the optimizer for training the model. Here, we are using the Adam optimizer.

 

# file: train.py
# define optimizer
optimizer = Adam(lr=learning_rate, decay=learning_rate_decay)

# put it all together
model = keras.models.Model(inputs=inputs, outputs=final_errors)
model.compile(loss='mean_absolute_error', optimizer=optimizer) 

 

Above, final_errors is a scalar value derived from errors. See the code repository for details.

Set up logging so that you can monitor training progress in the Azure portal

The next step is to ensure that hyperparameters and training progress are properly logged in your AML workspace so you can monitor performance in the Azure portal while your job is running.

This is how you can log hyperparameters.

 

# file: train.py
from azureml.core import Run

# log hyper parameters
run.log('learning_rate', learning_rate)
run.log('lr_decay', lr_decay)

 

To log training progress, we have to create a custom callback for our Keras model.

 

# file: train.py
from keras.callbacks import Callback

class LogRunMetrics(Callback):
   # callback at the end of every epoch
   def on_epoch_end(self, epoch, log):
      # log a value repeated which creates a list
      run.log('val_loss', log['val_loss'])
      run.log('loss', log['loss'])

callbacks = [LogRunMetrics()]

 

You can also log an image to your AML workspace. For example, when the training run is complete, you can create a plot with matplotlib to show performance (loss) on the training and the validation set.

 

# file: train.py

import matplotlib.pyplot as plt
plt.figure(figsize=(6, 3))
plt.title('({} epochs)'.format(nb_epoch), fontsize=14)
plt.plot(history.history['val_loss'], 'b-', label='Validation Loss', lw=4, alpha=0.5)
plt.plot(history.history['loss'], 'g-', label='Train Loss', lw=4, alpha=0.5)
plt.legend(fontsize=12)
plt.grid(True)

run.log_image('Validation Loss', plot=plt)

 

Set up AML Workspace and Experiment

The AML workspace is awesome for machine learning experimentation.

 

The workspace is the top-level resource for Azure Machine Learning service. It provides a centralized place to work with all the artifacts you create when you use Azure Machine Learning service.

 

The workspace keeps a list of compute targets that you can use to train your model. It also keeps a history of the training runs, including logs, metrics, output, and a snapshot of your scripts. You use this information to determine which training run produces the best model.

 

# file: train_remotely.py
from azureml.core import Workspace, Experiment
ws = Workspace.create(name=workspace_name, subscription_id=azure_subscription_id, resource_group=resource_group, location=azure_region)

exp = Experiment(ws, experiment_name)

For more info on how to setup your AML workspace, go here

 

Connect to AML Compute target

You can either create a new AML compute target, or connect to an existing one.

The model will be trained on this remote compute target. When you create it, you can specify a couple of important parameters. - vm_size - the size of the compute target. Make sure you pick on with a GPU. Read more here: https://aka.ms/azureml-vm-details. - min_nodes - It's probably best to leave this at the default (0), so that your cluster scales down completely when you don't use it for idle_seconds_before_scaledown (see below), which can save you a lot of money. - max_nodes - Maximum number of nodes to use on the cluster - idle_seconds_before_scaledown - Node idle time in seconds before scaling down the cluster.

 

# file: train_remotely.py

from azureml.core.compute import AmlCompute
from azureml.core.compute import ComputeTarget

try:
   gpu_compute_target = AmlCompute(workspace=ws, name=gpu_compute_name)
   print("found existing compute target: %s" % gpu_compute_name)
except:
   print('Creating a new compute target...')
   provisioning_config = AmlCompute.provisioning_configuration(vm_size='STANDARD_NC6', max_nodes=5, idle_seconds_before_scaledown=1800)

# create the cluster
gpu_compute_target = ComputeTarget.create(ws, gpu_compute_name, provisioning_config)

# can poll for a minimum number of nodes and for a specific timeout.
# if no min node count is provided it uses the scale settings for the cluster
gpu_compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20)

 

Define Estimator

Estimators are the building block for training. An estimator encapsulates the training code and parameters, the compute resources and runtime environment for a particular training scenario.

 

# file: train_remotely.py
from azureml.core.container_registry import ContainerRegistry
from azureml.train.estimator import Estimator

# configure access to ACR for pulling our custom docker image
acr = ContainerRegistry()
acr.address = config['acr_address']
acr.username = config['acr_username']
acr.password = config['acr_password']

est = Estimator(source_directory=script_folder,
         compute_target=gpu_compute_target,
         entry_script='train.py',
         use_gpu=True,
         node_count=1,
         custom_docker_image = "wopauli_1.8-gpu:1",
         image_registry_details=acr,
         user_managed=True)

 

Note how we are using a custom_docker_image. This is because we are using Tensorflow 1.8 and Keras 2.0.8, which are no longer supported by AML services. Apart from that, knowing how to create a custom docker image for training also gives you full control over your execution environment and can speed up provisioning compute targets considerably.

The steps to create a custom docker image are described here.

Submit your job to your AML experiment for execution.

Now we are ready to submit our job to run on our AML compute target. The last line below keeps you connected to the job while it is running remotely, so you can see progress printed on the command line.

 

# file: train_remotely.py

from azureml.core import Run
run = exp.submit(est)
run.wait_for_completion(show_output=True)

 

If everything works as expected, you should be able to see progress in the azure portal. Below is what this should look like after a successful training run. You can see Attributes, like how long it ran and what the status is. You can also see Tracked Metrics, which includes hyperparameters and the performance of your model. The performance of the model (training loss and validation loss) are also shown in Charts on the right. Plots like these are automatically created when you log lists of values to the portal.

 

portal_details.PNG

Download the trained model

If you go to the panel for Outputs, you can find a your trained model as a json file, with weights saved to a hdf5. To create an anomaly detection solution, you could now download those and run them on your test dataset.

 

portal_outputs.png

 

Next steps

Please let me know in the comments below if you found this helpful. Be on the lookout for upcoming blog posts on getting more out of AML services for creating a video anomaly detection service.

 

Literature

If you want to find out more about anomaly detection, I recommend the following two items.