Home
%3CLINGO-SUB%20id%3D%22lingo-sub-768002%22%20slang%3D%22en-US%22%3EPerform%20transfer%20learning%20with%20AML%20service%20to%20propagate%20a%20deep%20learning%20model%20for%20anomaly%20detection%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-768002%22%20slang%3D%22en-US%22%3E%3CP%3EIn%20a%20previous%20blog%20post%20(%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2FAI-Customer-Engineering-Team%2FVideo-Anomaly-Detection-with-Deep-Predictive-Coding-Networks%2Fba-p%2F560598%22%20target%3D%22_blank%22%20rel%3D%22noopener%22%3EVideo%20Anomaly%20Detection%20with%20Deep%20Predictive%20Coding%20Networks%3C%2FA%3E)%2C%20I%20provided%20an%20overview%20for%20how%20to%20train%20a%20recurrent%20neural%20network%20to%20detect%20behavioral%20anomalies%20in%20videos.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3EIn%20this%20post%20we%20are%20going%20to%20take%20it%20a%20step%20further%3A%20Let%E2%80%99s%20imagine%20the%20University%20of%20California%2C%20San%20Diego%20was%20so%20impressed%20with%20the%20incredible%20performance%20of%20your%20model%20in%20detecting%20unusual%20events%20on%20a%20sidewalk%20that%20the%20they%20want%20to%20detect%20anomalies%20in%20video%20feeds%20from%20all%20sorts%20of%20cameras%20on%20campus.%20Some%20of%20these%20cameras%20are%20similarly%20monitoring%20sidewalks%2C%20but%20other%20cameras%20might%20observe%20other%20types%20of%20scenes%2C%20e.g.%20the%20entrance%20to%20the%20library%20or%20a%20parking%20lot.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3EHow%20can%20we%20scale%20our%20existing%20solution%20so%20that%20we%20can%20quickly%20offer%20anomaly%20detection%20at%20all%20these%20other%20locations%3F%20Can%20we%20do%20better%20than%20implementing%20anomaly%20detection%20services%20for%20all%20these%20cameras%20with%20brute%20force%2C%20by%20repeatedly%20going%20through%20the%20steps%20described%20in%20the%20previous%20blog%20post%20for%20each%20of%20these%20cameras%3F%20Luckily%20%3CA%20href%3D%22https%3A%2F%2Fazure.microsoft.com%2Fen-us%2Fservices%2Fmachine-learning-service%2F%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EMicrosoft%20Azure%20Machine%20Learning%20service%3C%2FA%3Eoffers%20a%20couple%20of%20useful%20tools%20that%20will%20make%20our%20lives%20much%20easier%20and%20allow%20us%20to%20train%20and%20deploy%20models%20much%20more%20quickly.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3EFirst%2C%20the%20steps%20for%20developing%20a%20model%20are%20analogous%20for%20each%20of%20the%20cameras%3A%20(1)%20video%20decoding%2C%20(2)%20data%20augmentation%2C%20(3)%20training%20with%20hyperparameter%20sweeps%2C%20(4)%20model%20registration.%20It%20would%20be%20nice%20if%20we%20could%20define%20a%20pipeline%20that%20automatically%20executes%20these%20steps%20in%20sequence%20for%20each%20camera.%20This%20pipeline%20could%20cache%20the%20intermediate%20results%20of%20pipeline%20steps%20from%20previous%20runs%2C%20to%20avoid%20redundant%20re-runs%20of%20pipeline%20steps.%20This%20is%20exactly%20what%20AML%20pipelines%20were%20built%20for.%20We%20can%20further%20attach%20a%20Scheduler%20to%20each%20pipeline%2C%20to%20monitor%20our%20Azure%20blob%20storage%20container%20for%20new%20training%20data.%20This%20scheduler%20then%20automatically%20triggers%20a%20pipeline%20run%20to%20ensure%20that%20our%20models%20stay%20up-to-date.%20For%20example%2C%20maybe%20the%20original%20training%20data%20was%20collected%20in%20the%20middle%20of%20summer%2C%20but%20we%20want%20to%20make%20sure%20that%20our%20model%20also%20works%20in%20the%20winter%20when%20there%20is%20snow%20on%20the%20ground.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3ESecond%2C%20we%20already%20have%20a%20trained%20model%20for%20anomaly%20detection.%20We%20can%20therefore%20try%20to%20speed%20things%20up%20with%20%3CA%20href%3D%22https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FTransfer_learning%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3Etransfer%20learning%3C%2FA%3E%3A%20Instead%20of%20training%20from%20scratch%2C%20we%20load%20the%20parameters%20(weights)%20of%20the%20trained%20model%20and%20start%20training%20on%20a%20new%20dataset%20from%20there.%20One%20way%20to%20achieve%20this%20is%20to%20pull%20an%20already%20trained%20model%20from%20our%20%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fmachine-learning%2Fservice%2Fconcept-workspace%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EAzure%20Machine%20Learning%20service%20Workspace%3C%2FA%3Eto%20then%20train%20the%20model%20on%20the%20new%20data.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3EThird%2C%20in%20the%20previous%20blog%20post%20I%20omitted%20to%20talk%20about%20how%20to%20find%20hyperparameters%20(e.g.%20learning%20rate%20and%20learning%20rate%20decay)%20for%20our%20model%2C%20but%20just%20picked%20some%20that%20worked.%20Whether%20these%20same%20hyperparameters%20will%20work%20for%20a%20different%20camera%20is%20far%20from%20certain.%20For%20example%2C%20one%20often%20uses%20relatively%20smaller%20learning%20rates%20during%20transfer%20learning%20to%20avoid%20that%20the%20model%20unlearns%20previous%20knowledge.%20We%20will%20also%20want%20to%20use%20different%20hyperparameters%20depending%20on%20whether%20we%20perform%20transfer%20learning%20or%20train%20from%20scratch.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3ETo%20build%20this%20new%2C%20scalable%20solution%2C%20you%E2%80%99ll%20want%20to%20follow%20these%20steps%2C%20which%20are%20typical%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3ESetting%20up%20AML%20pipeline%20(with%20a%20DataStore%20scheduler)%3C%2FLI%3E%0A%3CLI%3EPerforming%20transfer%20learning%3C%2FLI%3E%0A%3CLI%3EPerforming%20hyperparameter%20sweeps%20with%20%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fmachine-learning%2Fservice%2Fhow-to-tune-hyperparameters%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EHyperDrive%3C%2FA%3E%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CH2%20id%3D%22toc-hId-1793506580%22%20id%3D%22toc-hId-1793506580%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId--758650381%22%20id%3D%22toc-hId--758650381%22%3ESetting%20up%20an%20AML%20pipeline%3C%2FH2%3E%0A%3CP%3E(see%20%3CA%20href%3D%22https%3A%2F%2Fgithub.com%2Fmicrosoft%2FMLOps_VideoAnomalyDetection%2Fblob%2Fmaster%2Fpipelines_create.py%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Epipelines_create.py%3C%2FA%3E)%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%2F124050iFF24B22986BFDBA7%2Fimage-size%2Flarge%3Fv%3D1.0%26amp%3Bpx%3D999%22%20alt%3D%22pipeline.png%22%20title%3D%22pipeline.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3EFigure%201%3A%20Screenshot%20of%20the%20AML%20pipeline%20in%20the%20Azure%20Portal.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EAs%20you%20can%20see%20in%20Figure%201%2C%20our%20AML%20pipeline%20for%20training%20a%20model%20contains%20the%20following%20steps%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3Evideo_decoding%20-%20extract%20individual%20frames%20of%20the%20video%20and%20store%20them%20in%20separate%20files%20(e.g.%20tiff).%3C%2FLI%3E%0A%3CLI%3Edata_prep%20-%20scale%20and%20crop%20images%20so%20that%20their%20size%20matches%20the%20size%20of%20the%20input%20layer%20of%20our%20model.%3C%2FLI%3E%0A%3CLI%3Etrain_w_hyperdrive%20-%20train%20the%20model%20using%20HyperDrive.%3C%2FLI%3E%0A%3CLI%3Eregister_model%20-%20register%20the%20model%20in%20the%20AML%20workspace%20for%20later%20deployment.%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CP%3EWe%20define%20steps%201%2C%202%2C%20and%204%20with%20the%20PythonScriptStep%20class.%20For%20example%2C%20video_decoding%20looks%20like%20this%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%20%20%20video_decoding%20%3D%20PythonScriptStep(%0A%20%20%20%20%20%20%20name%3D'decode_videos'%2C%0A%20%20%20%20%20%20%20script_name%3D%22video_decoding.py%22%2C%0A%20%20%20%20%20%20%20arguments%3D%5B%22--input_data%22%2C%20video_data%2C%20%22--output_data%22%2C%20raw_data%5D%2C%0A%20%20%20%20%20%20%20inputs%3D%5Bvideo_data%5D%2C%0A%20%20%20%20%20%20%20outputs%3D%5Braw_data%5D%2C%0A%20%20%20%20%20%20%20compute_target%3Dcpu_compute_target%2C%0A%20%20%20%20%20%20%20source_directory%3Dscript_folder%2C%0A%20%20%20%20%20%20%20runconfig%3Dcpu_compute_run_config%2C%0A%20%20%20%20%20%20%20allow_reuse%3DTrue%0A%20%20%20)%3C%2FPRE%3E%0A%3CP%3EA%20%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fpython%2Fapi%2Fazureml-pipeline-steps%2Fazureml.pipeline.steps.python_script_step.pythonscriptstep%3Fview%3Dazure-ml-py%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EPythonScriptStep%3C%2FA%3Eis%20the%20most%20generic%20kind%20of%20step%20in%20AML%20pipelines.%20You%20can%20use%20it%20to%20run%20any%20kind%20of%20python%20script%20(e.g.%20video_decoding.py).%20If%20your%20script%20accepts%20input%20and%20output%20data%2C%20you%20can%20specify%20those%20as%20well.%20Don%E2%80%99t%20forget%20to%20also%20define%20script%20arguments%20that%20allow%20the%20script%20to%20interpret%20what%20to%20do%20with%20these%20data.%20The%20PythonScriptStep%20also%20allows%20you%20to%20configure%20on%20which%20compute%20target%20and%20which%20python%20environment%20to%20execute%20the%20script.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3EOne%20of%20the%20most%20useful%20features%20of%20%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fmachine-learning%2Fservice%2Fconcept-ml-pipelines%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3EAML%20pipelines%3C%2FA%3E%2C%20in%20my%20opinion%2C%20is%20that%20you%20can%20attach%20a%20Scheduler%20to%20a%20published%20AML%20pipeline.%20This%20scheduler%20can%20poll%20a%20defined%20storage%20location%20at%20a%20given%20interval.%20This%20means%20that%20we%20have%20an%20opportunity%20to%20automatically%20retrain%20our%20model%20whenever%20new%20training%20data%20is%20available.%20For%20example%2C%20you%20can%20set%20up%20the%20scheduler%20to%20check%20your%20Azure%20Blob%20storage%20container%20every%20hour%20to%20see%20whether%20there%20is%20new%20training%20data%20available%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%20%20%20schedule%20%3D%20Schedule.create(workspace%3Dws%2C%20name%3Dpipeline_name%20%2B%20%22_sch%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20pipeline_id%3Dpublished_pipeline.id%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20experiment_name%3Dpipeline_name%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20datastore%3Ddef_blob_store%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20wait_for_provisioning%3DTrue%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20description%3D%22Datastore%20scheduler%20for%20Pipeline%22%20%2B%20pipeline_name%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20path_on_datastore%3Dos.path.join('prednet%2Fdata%2Fvideo%2FUCSD1%2FTrain')%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20polling_interval%3D1%0A%20%20%20)%3C%2FPRE%3E%0A%3CP%3EIn%20this%20example%2C%20we%20are%20telling%20the%20scheduler%20to%20look%20at%20the%20DataStore%20def_blob_store%20(the%20default%20blob%20store%20of%20our%20AML%20workspace)%20and%20check%20the%20path_on_datastore%20for%20new%20video%20files.%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId-984159954%22%20id%3D%22toc-hId-984159954%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId--1567997007%22%20id%3D%22toc-hId--1567997007%22%3EPerforming%20transfer%20learning%3C%2FH2%3E%0A%3CP%3EAnother%20trick%20when%20propagating%20our%20solution%20to%20other%20cameras%20is%20to%20not%20train%20every%20model%20from%20scratch%2C%20but%20to%20take%20an%20already%20trained%20model%20from%20the%20Azure%20Machine%20Learning%20service%20Workspace%2C%20to%20train%20it%20on%20the%20data%20from%20a%20new%20camera.%20This%20can%20lead%20to%20a%20very%20large%20speedup%20of%20the%20training%20process.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EFor%20this%20to%20work%2C%20you%20need%20to%20register%20a%20trained%20model%20in%20the%20Model%20Registry%20of%20your%20AML%20service%20Workspace%20(see%20model_registration.py)%2C%20so%20that%20you%20can%20then%20pull%20the%20model%20and%20use%20it%20for%20transfer%20learning.%20The%20following%20code%20shows%20how%20to%20pull%20and%20initialize%20a%20new%20model%20with%20the%20trained%20weights%3A%3C%2FP%3E%0A%3CP%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3C%2FP%3E%0A%3CPRE%3Efrom%20azureml.core%20import%20Workspace%0Afrom%20azureml.core.model%20import%20Model%0A%0A%23%20connect%20to%20AML%20workspace%0Aws%20%3D%20Workspace.from_config(path%3Dconfig_json)%0A%20%0A%23%20pull%20model%20from%20ACR%0Amodel_root%20%3D%20Model.get_model_path('prednet_UCSDped1'%2C%20_workspace%3Dws)%0Ajson_file%20%3D%20open(os.path.join(model_root%2C%20'model.json')%2C%20'r')%20%23%20todo%2C%20this%20is%20going%20to%20the%20real%20one%0Amodel_json%20%3D%20json_file.read()%0Ajson_file.close()%0A%20%20%20%0A%23%20load%20weights%0Atrained_model%20%3D%20model_from_json(model_json%2C%20custom_objects%3D%7B%22PredNet%22%3A%20PredNet%7D)%0Atrained_model.load_weights(os.path.join(model_root%2C%20%22weights.hdf5%22))%20%0A%20%0A%23%20create%20instance%20of%20prednet%20model%20with%20the%20above%20weights%20and%20our%20layer_config%0Aprednet%20%3D%20PredNet(weights%3Dtrained_model.layers%5B1%5D.get_weights()%2C%20**layer_config)%3C%2FPRE%3E%0A%3CP%3ENow%20we%20can%20train%20our%20instance%20of%20PredNet%20as%20before%20but%2C%20instead%20of%20starting%20from%20randomly%20initialized%20weights%2C%20we%20start%20with%20the%20weights%20of%20the%20trained%20model%20(see%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).%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId-174813328%22%20id%3D%22toc-hId-174813328%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId-1917623663%22%20id%3D%22toc-hId-1917623663%22%3EPerforming%20hyperparameter%20sweeps%20with%20HyperDrive%3C%2FH2%3E%0A%3CP%3EOne%20more%20thing%20we%20can%20do%20to%20optimize%20our%20process%20of%20scaling%20our%20video%20anomaly%20detection%20solution%20is%20to%20use%20HyperDrive%20to%20perform%20automated%20hyperparameter%20sweeps.%20This%20is%20useful%20if%20we%20want%20to%20train%20models%20on%20completely%20different%20training%20data%20because%20we%20don%E2%80%99t%20know%20whether%20we%20can%20use%20the%20same%20hyperparameters%20that%20we%20also%20used%20in%20our%20initial%20solution.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EFirst%2C%20we%20define%20the%20hyperparameters%20that%20we%20are%20interested%20in%20and%20how%20to%20choose%20hyperparameters%20for%20the%20next%20run.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%20%20%20ps%20%3D%20RandomParameterSampling(%0A%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%5B%E2%80%A6%5D%0A%20%20%20%20%20%20%20%20%20%20%20'--learning_rate'%3A%20loguniform(-6%2C%20-1)%2C%0A%20%20%20%20%20%20%20%20%20%20%20'--lr_decay'%3A%20loguniform(-9%2C%20-1)%2C%0A%20%20%20%20%20%20%20%20%20%20%20%5B%E2%80%A6%5D%0A%20%20%20%20%20%20%20%20%20%20%20'--transfer_learning'%3A%20choice(%22True%22%2C%20%22False%22)%0A%20%20%20%20%20%20%20%7D%0A%20%20%20)%3C%2FPRE%3E%0A%3CP%3ENote%20how%20we%20are%20also%20including%20a%20hyperparameter%20called%20%E2%80%9Ctransfer_learning.%E2%80%9D%20This%20allows%20us%20to%20simultaneously%20evaluate%20whether%20training%20a%20model%20from%20scratch%20or%20training%20via%20transfer%20learning%20gives%20us%20an%20advantage.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ENext%2C%20we%20need%20to%20define%20how%20to%20decide%20when%20a%20run%20should%20be%20aborted%20if%20it%20becomes%20clear%20that%20a%20configuration%20of%20hyperparameters%20is%20not%20going%20to%20lead%20to%20good%20model%20performance.%20Computing%20costs%20can%20be%20minimized%20if%20we%20cancel%20those%20unhelpful%20jobs.%20Here%2C%20we%20use%20a%20BanditPolicy%2C%20which%20is%20evaluated%20every%202%20epochs.%20Training%20runs%20in%20which%20the%20model%20performance%20(ability%20to%20predict%20the%20next%20video%20frame)%20is%20worse%20by%20slack_factor%20times%20the%20performance%20of%20the%20best%20model%20(after%20the%20same%20number%20of%20training%20epochs)%20are%20aborted.%20We%20wait%20for%20at%20least%2010%20epochs%2C%20because%20initial%20model%20performance%20is%20not%20a%20reliable%20predictor%20of%20performance%20after%20training%20is%20complete.%20Figure%202%20illustrates%20the%20result%20of%20applying%20such%20a%20policy.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%20%20%20policy%20%3D%20BanditPolicy(evaluation_interval%3D2%2C%20slack_factor%3D0.1%2C%20delay_evaluation%3D10)%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EInstead%20of%20a%20PythonScriptStep%20for%20training%2C%20we%20use%20a%20HyperDriveStep%20for%20executing%20this%20step%20to%20get%20better%20resource%20management%20and%20logging%20of%20results.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%3E%20%20%20%20hdc%20%3D%20HyperDriveConfig(estimator%3Dest%2C%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20hyperparameter_sampling%3Dps%2C%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20policy%3Dpolicy%2C%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20primary_metric_name%3D'val_loss'%2C%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20primary_metric_goal%3DPrimaryMetricGoal.MINIMIZE%2C%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20max_total_runs%3D10%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20max_concurrent_runs%3D5%2C%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20max_duration_minutes%3D60*6%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20)%0A%0A%20%20%20%20hd_step%20%3D%20HyperDriveStep(%0A%20%20%20%20%20%20%20%20%22train_w_hyperdrive%22%2C%0A%20%20%20%20%20%20%20%20hdc%2C%0A%20%20%20%20%20%20%20%20estimator_entry_script_arguments%3D%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20'--data-folder'%2C%20preprocessed_data%2C%20%0A%20%20%20%20%20%20%20%20%20%20%20%20...%0A%20%20%20%20%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20inputs%3D%5Bpreprocessed_data%5D%2C%0A%20%20%20%20%20%20%20%20metrics_output%20%3D%20data_metrics%2C%0A%20%20%20%20%20%20%20%20allow_reuse%3DTrue%0A%20%20%20%20)%0A%20%20%20%20hd_step.run_after(data_prep)%3C%2FPRE%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%2F124051i6795507BC6AEBB7B%2Fimage-size%2Flarge%3Fv%3D1.0%26amp%3Bpx%3D999%22%20alt%3D%22hyperdrive.png%22%20title%3D%22hyperdrive.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3EFigure%202%3A%20Snapshot%20of%20run%20logs%20of%20a%20HyperDrive%20run%20in%20the%20Azure%20Portal.%20The%20horizontal%20axis%20indicates%20training%20epoch%20and%20the%20vertical%20axis%20shows%20error%20in%20predicting%20each%20pixel%20in%20the%20next%20frame%20of%20the%20video.%20You%20can%20see%20that%20run%20%2372%20is%20cancelled%20after%2010%20epochs%20(at%20the%20end%20of%20the%20evaluation%20delay%20period)%20because%20the%20error%20of%20about%20.27%20is%20much%20larger%20than%20the%20error%20of%20the%20best%20models%20(~0.01).%3C%2FP%3E%0A%3CH2%20id%3D%22toc-hId--634533298%22%20id%3D%22toc-hId--634533298%22%3E%26nbsp%3B%3C%2FH2%3E%0A%3CH2%20id%3D%22toc-hId-1108277037%22%20id%3D%22toc-hId-1108277037%22%3ESummary%3C%2FH2%3E%0A%3CP%3EThis%20blog%20post%20provided%20an%20overview%20of%20how%20to%20scale%20your%20video%20anomaly%20detection%20solution%20to%20include%20data%20from%20other%20cameras.%20In%20effect%2C%20all%20the%20user%20has%20to%20do%20is%20to%20upload%20training%20data%20for%20a%20new%20camera%2C%20and%20this%20solution%20then%20automatically%20trains%20a%20model%20to%20perform%20anomaly%20detection%20on%20this%20new%20camera.%20This%20is%20achieved%20by%20combining%20AML%20pipelines%20and%20HyperDrive.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EHave%20you%20encountered%20similar%20scenarios%20in%20the%20past%3F%20I%20have%20encountered%20scenarios%20in%20many%20industry%20verticals%20in%20which%20anomaly%20detection%20could%20be%20useful.%20The%20following%20table%20gives%20a%20couple%20of%20examples.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CTABLE%3E%0A%3CTBODY%3E%0A%3CTR%3E%0A%3CTD%20width%3D%22215%22%3E%0A%3CP%3E%3CSTRONG%3EIndustry%3C%2FSTRONG%3E%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3CTD%20width%3D%22407%22%3E%0A%3CP%3E%3CSTRONG%3EUse%20Case%3C%2FSTRONG%3E%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3C%2FTR%3E%0A%3CTR%3E%0A%3CTD%20width%3D%22215%22%3E%0A%3CP%3EManufacturing%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3CTD%20width%3D%22407%22%3E%0A%3CP%3EThe%20model%20can%20detect%20accidents%20on%20the%20factory%20floor%20(e.g.%20explosions%2C%20violation%20of%20safety%20guidelines%2C%20injuries).%26nbsp%3B%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3C%2FTR%3E%0A%3CTR%3E%0A%3CTD%20width%3D%22215%22%3E%0A%3CP%3ETransportation%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3CTD%20width%3D%22407%22%3E%0A%3CP%3EThis%20can%20be%20used%20to%20detect%20unusual%20or%20illegal%20events%20in%20crowds%20(e.g.%20traffic%20accidents%2C%20cars%20on%20bike%20paths%2C%20physical%20assault%2C%20injured%20pedestrians%2C%20illegally%20entering%2Fexiting%20public%20transportation%2C%20anomalies%20in%20video%20of%20dashboard%20camera%20in%20car).%3C%2FP%3E%0A%3C%2FTD%3E%0A%3C%2FTR%3E%0A%3CTR%3E%0A%3CTD%20width%3D%22215%22%3E%0A%3CP%3EHealth%20Care%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3CTD%20width%3D%22407%22%3E%0A%3CP%3EThe%20approach%20can%20be%20used%20for%20any%20kind%20of%20visual%20monitoring%20(e.g.%20hallways%20in%20hospitals%2C%20patients%20in%20bed%2C%20ultrasound)%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3C%2FTR%3E%0A%3CTR%3E%0A%3CTD%20width%3D%22215%22%3E%0A%3CP%3EBanking%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3CTD%20width%3D%22407%22%3E%0A%3CP%3EThe%20approach%20could%20be%20used%20to%20detect%20suspicious%20behavior%20(e.g.%20bank%20robbery%2C%20theft%20at%20ATM).%26nbsp%3B%3C%2FP%3E%0A%3C%2FTD%3E%0A%3C%2FTR%3E%0A%3CTR%3E%0A%3CTD%20width%3D%22215%22%3E%0A%3CP%3EFarming%3C%2FP%3E%0A%3C%2FTD%3E%0A%3CTD%20width%3D%22407%22%3E%0A%3CP%3EThe%20approach%20can%20be%20used%20to%20detect%20anomalies%20in%20the%20behavior%20of%20ranch%20animals%20(e.g.%20limping%2C%20predators%2C%20thieves).%3C%2FP%3E%0A%3C%2FTD%3E%0A%3C%2FTR%3E%0A%3CTR%3E%0A%3CTD%20width%3D%22215%22%3E%0A%3CP%3EEducation%3C%2FP%3E%0A%3C%2FTD%3E%0A%3CTD%20width%3D%22407%22%3E%0A%3CP%3EDetecting%20bullying%20or%20other%20violence%20in%20schools%20or%20universities.%3C%2FP%3E%0A%3C%2FTD%3E%0A%3C%2FTR%3E%0A%3C%2FTBODY%3E%0A%3C%2FTABLE%3E%0A%3CP%3E%3CBR%20%2F%3EPlease%20be%20responsible%20when%20you%20implement%20such%20a%20solution.%20For%20example%2C%20take%20a%20look%20at%20the%20Microsoft%20AI%20principlesbefore%20you%20deploy%20a%20solution.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20complete%20code%20for%20this%20blog%20post%20can%20be%20found%20on%20%3CA%20href%3D%22https%3A%2F%2Fgithub.com%2Fmicrosoft%2FMLOps_VideoAnomalyDetection%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Egithub%3C%2FA%3E.%20Please%20let%20me%20know%20if%20you%20have%20any%20questions%20or%20comments!%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-TEASER%20id%3D%22lingo-teaser-768002%22%20slang%3D%22en-US%22%3E%3CP%3EIn%20a%20previous%20blog%20post%20(%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2FAI-Customer-Engineering-Team%2FVideo-Anomaly-Detection-with-Deep-Predictive-Coding-Networks%2Fba-p%2F560598%22%20target%3D%22_blank%22%3EVideo%20Anomaly%20Detection%20with%20Deep%20Predictive%20Coding%20Networks%3C%2FA%3E)%2C%20I%20provided%20an%20overview%20for%20how%20to%20train%20a%20recurrent%20neural%20network%20to%20detect%20behavioral%20anomalies%20in%20videos.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EIn%20this%20blog%2C%20we%20are%20going%20to%20take%20it%20a%20step%20further%3A%20Let%E2%80%99s%20imagine%20the%20University%20of%20California%2C%20San%20Diego%20was%20so%20impressed%20with%20your%20implementation%20and%20the%20incredible%20performance%20of%20your%20model%20in%20detecting%20unusual%20events%20on%20a%20sidewalk%20that%20the%20they%20decided%20they%20want%20to%20detect%20anomalies%20in%20video%20feeds%20from%20all%20sorts%20of%20cameras%20on%20campus.%20Some%20of%20these%20cameras%20are%20similarly%20monitoring%20sidewalks%2C%20but%20other%20cameras%20might%20observe%20other%20types%20of%20scenes%2C%20e.g.%20the%20entrance%20to%20the%20library%20or%20a%20parking%20lot.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EHow%20can%20we%20scale%20our%20existing%20solution%20so%20that%20we%20can%20quickly%20offer%20anomaly%20detection%20at%20all%20these%20other%20locations%3F%20Can%20we%20do%20better%20than%20implementing%20anomaly%20detection%20services%20for%20all%20these%20cameras%20with%20brute%20force%2C%20by%20repeatedly%20going%20through%20the%20steps%20described%20in%20the%20previous%20blog%20post%20for%20each%20of%20these%20cameras%3F%3C%2FP%3E%3C%2FLINGO-TEASER%3E%3CLINGO-LABS%20id%3D%22lingo-labs-768002%22%20slang%3D%22en-US%22%3E%3CLINGO-LABEL%3Eazure%20ml%3C%2FLINGO-LABEL%3E%3CLINGO-LABEL%3EAzureAI%3C%2FLINGO-LABEL%3E%3CLINGO-LABEL%3EMachine%20Learning%3C%2FLINGO-LABEL%3E%3C%2FLINGO-LABS%3E
Microsoft

In a previous blog post (Video Anomaly Detection with Deep Predictive Coding Networks), I provided an overview for how to train a recurrent neural network to detect behavioral anomalies in videos.

In this post we are going to take it a step further: Let’s imagine the University of California, San Diego was so impressed with the incredible performance of your model in detecting unusual events on a sidewalk that the they want to detect anomalies in video feeds from all sorts of cameras on campus. Some of these cameras are similarly monitoring sidewalks, but other cameras might observe other types of scenes, e.g. the entrance to the library or a parking lot.

How can we scale our existing solution so that we can quickly offer anomaly detection at all these other locations? Can we do better than implementing anomaly detection services for all these cameras with brute force, by repeatedly going through the steps described in the previous blog post for each of these cameras? Luckily Microsoft Azure Machine Learning service offers a couple of useful tools that will make our lives much easier and allow us to train and deploy models much more quickly.

First, the steps for developing a model are analogous for each of the cameras: (1) video decoding, (2) data augmentation, (3) training with hyperparameter sweeps, (4) model registration. It would be nice if we could define a pipeline that automatically executes these steps in sequence for each camera. This pipeline could cache the intermediate results of pipeline steps from previous runs, to avoid redundant re-runs of pipeline steps. This is exactly what AML pipelines were built for. We can further attach a Scheduler to each pipeline, to monitor our Azure blob storage container for new training data. This scheduler then automatically triggers a pipeline run to ensure that our models stay up-to-date. For example, maybe the original training data was collected in the middle of summer, but we want to make sure that our model also works in the winter when there is snow on the ground.

Second, we already have a trained model for anomaly detection. We can therefore try to speed things up with transfer learning: Instead of training from scratch, we load the parameters (weights) of the trained model and start training on a new dataset from there. One way to achieve this is to pull an already trained model from our Azure Machine Learning service Workspace to then train the model on the new data.

Third, in the previous blog post I omitted to talk about how to find hyperparameters (e.g. learning rate and learning rate decay) for our model, but just picked some that worked. Whether these same hyperparameters will work for a different camera is far from certain. For example, one often uses relatively smaller learning rates during transfer learning to avoid that the model unlearns previous knowledge. We will also want to use different hyperparameters depending on whether we perform transfer learning or train from scratch.

To build this new, scalable solution, you’ll want to follow these steps, which are typical:

  1. Setting up AML pipeline (with a DataStore scheduler)
  2. Performing transfer learning
  3. Performing hyperparameter sweeps with HyperDrive

 

Setting up an AML pipeline

(see pipelines_create.py)

pipeline.png

Figure 1: Screenshot of the AML pipeline in the Azure Portal.

 

As you can see in Figure 1, our AML pipeline for training a model contains the following steps:

  1. video_decoding - extract individual frames of the video and store them in separate files (e.g. tiff).
  2. data_prep - scale and crop images so that their size matches the size of the input layer of our model.
  3. train_w_hyperdrive - train the model using HyperDrive.
  4. register_model - register the model in the AML workspace for later deployment.

We define steps 1, 2, and 4 with the PythonScriptStep class. For example, video_decoding looks like this:

 

   video_decoding = PythonScriptStep(
       name='decode_videos',
       script_name="video_decoding.py",
       arguments=["--input_data", video_data, "--output_data", raw_data],
       inputs=[video_data],
       outputs=[raw_data],
       compute_target=cpu_compute_target,
       source_directory=script_folder,
       runconfig=cpu_compute_run_config,
       allow_reuse=True
   )

A PythonScriptStep is the most generic kind of step in AML pipelines. You can use it to run any kind of python script (e.g. video_decoding.py). If your script accepts input and output data, you can specify those as well. Don’t forget to also define script arguments that allow the script to interpret what to do with these data. The PythonScriptStep also allows you to configure on which compute target and which python environment to execute the script.

One of the most useful features of AML pipelines, in my opinion, is that you can attach a Scheduler to a published AML pipeline. This scheduler can poll a defined storage location at a given interval. This means that we have an opportunity to automatically retrain our model whenever new training data is available. For example, you can set up the scheduler to check your Azure Blob storage container every hour to see whether there is new training data available:

 

   schedule = Schedule.create(workspace=ws, name=pipeline_name + "_sch",
                           pipeline_id=published_pipeline.id,
                           experiment_name=pipeline_name,
                           datastore=def_blob_store,
                           wait_for_provisioning=True,
                           description="Datastore scheduler for Pipeline" + pipeline_name,
                           path_on_datastore=os.path.join('prednet/data/video/UCSD1/Train'),
                           polling_interval=1
   )

In this example, we are telling the scheduler to look at the DataStore def_blob_store (the default blob store of our AML workspace) and check the path_on_datastore for new video files.

 

Performing transfer learning

Another trick when propagating our solution to other cameras is to not train every model from scratch, but to take an already trained model from the Azure Machine Learning service Workspace, to train it on the data from a new camera. This can lead to a very large speedup of the training process.

 

For this to work, you need to register a trained model in the Model Registry of your AML service Workspace (see model_registration.py), so that you can then pull the model and use it for transfer learning. The following code shows how to pull and initialize a new model with the trained weights:

 

from azureml.core import Workspace
from azureml.core.model import Model

# connect to AML workspace
ws = Workspace.from_config(path=config_json)
 
# pull model from ACR
model_root = Model.get_model_path('prednet_UCSDped1', _workspace=ws)
json_file = open(os.path.join(model_root, 'model.json'), 'r') # todo, this is going to the real one
model_json = json_file.read()
json_file.close()
   
# load weights
trained_model = model_from_json(model_json, custom_objects={"PredNet": PredNet})
trained_model.load_weights(os.path.join(model_root, "weights.hdf5")) 
 
# create instance of prednet model with the above weights and our layer_config
prednet = PredNet(weights=trained_model.layers[1].get_weights(), **layer_config)

Now we can train our instance of PredNet as before but, instead of starting from randomly initialized weights, we start with the weights of the trained model (see train.py).

 

Performing hyperparameter sweeps with HyperDrive

One more thing we can do to optimize our process of scaling our video anomaly detection solution is to use HyperDrive to perform automated hyperparameter sweeps. This is useful if we want to train models on completely different training data because we don’t know whether we can use the same hyperparameters that we also used in our initial solution.

 

First, we define the hyperparameters that we are interested in and how to choose hyperparameters for the next run.

 

   ps = RandomParameterSampling(
       {
           […]
           '--learning_rate': loguniform(-6, -1),
           '--lr_decay': loguniform(-9, -1),
           […]
           '--transfer_learning': choice("True", "False")
       }
   )

Note how we are also including a hyperparameter called “transfer_learning.” This allows us to simultaneously evaluate whether training a model from scratch or training via transfer learning gives us an advantage.

 

Next, we need to define how to decide when a run should be aborted if it becomes clear that a configuration of hyperparameters is not going to lead to good model performance. Computing costs can be minimized if we cancel those unhelpful jobs. Here, we use a BanditPolicy, which is evaluated every 2 epochs. Training runs in which the model performance (ability to predict the next video frame) is worse by slack_factor times the performance of the best model (after the same number of training epochs) are aborted. We wait for at least 10 epochs, because initial model performance is not a reliable predictor of performance after training is complete. Figure 2 illustrates the result of applying such a policy.

 

   policy = BanditPolicy(evaluation_interval=2, slack_factor=0.1, delay_evaluation=10)

 

Instead of a PythonScriptStep for training, we use a HyperDriveStep for executing this step to get better resource management and logging of results.

 

    hdc = HyperDriveConfig(estimator=est, 
                            hyperparameter_sampling=ps, 
                            policy=policy, 
                            primary_metric_name='val_loss', 
                            primary_metric_goal=PrimaryMetricGoal.MINIMIZE, 
                            max_total_runs=10,
                            max_concurrent_runs=5, 
                            max_duration_minutes=60*6
                            )

    hd_step = HyperDriveStep(
        "train_w_hyperdrive",
        hdc,
        estimator_entry_script_arguments=[
            '--data-folder', preprocessed_data, 
            ...
            ],
        inputs=[preprocessed_data],
        metrics_output = data_metrics,
        allow_reuse=True
    )
    hd_step.run_after(data_prep)

 

hyperdrive.png

Figure 2: Snapshot of run logs of a HyperDrive run in the Azure Portal. The horizontal axis indicates training epoch and the vertical axis shows error in predicting each pixel in the next frame of the video. You can see that run #72 is cancelled after 10 epochs (at the end of the evaluation delay period) because the error of about .27 is much larger than the error of the best models (~0.01).

 

Summary

This blog post provided an overview of how to scale your video anomaly detection solution to include data from other cameras. In effect, all the user has to do is to upload training data for a new camera, and this solution then automatically trains a model to perform anomaly detection on this new camera. This is achieved by combining AML pipelines and HyperDrive.

 

Have you encountered similar scenarios in the past? I have encountered scenarios in many industry verticals in which anomaly detection could be useful. The following table gives a couple of examples.

 

Industry 

Use Case 

Manufacturing 

The model can detect accidents on the factory floor (e.g. explosions, violation of safety guidelines, injuries).  

Transportation 

This can be used to detect unusual or illegal events in crowds (e.g. traffic accidents, cars on bike paths, physical assault, injured pedestrians, illegally entering/exiting public transportation, anomalies in video of dashboard camera in car).

Health Care 

The approach can be used for any kind of visual monitoring (e.g. hallways in hospitals, patients in bed, ultrasound) 

Banking 

The approach could be used to detect suspicious behavior (e.g. bank robbery, theft at ATM). 

Farming

The approach can be used to detect anomalies in the behavior of ranch animals (e.g. limping, predators, thieves).

Education

Detecting bullying or other violence in schools or universities.


Please be responsible when you implement such a solution. For example, take a look at the Microsoft AI principles before you deploy a solution.

 

The complete code for this blog post can be found on github. Please let me know if you have any questions or comments!