import%20marimo%0A%0A__generated_with%20%3D%20%220.25.2%22%0Aapp%20%3D%20marimo.App(width%3D%22medium%22%2C%20app_title%3D%22Anomalies%20with%20machine%20learning%22)%0A%0Awith%20app.setup%3A%0A%20%20%20%20%23%20The%20setup%20cell%20runs%20first.%20It%20holds%20the%20imports%20and%20the%20survey's%20tables%20every%20other%20cell%20uses.%0A%20%20%20%20import%20duckdb%0A%20%20%20%20import%20marimo%20as%20mo%0A%20%20%20%20import%20matplotlib.pyplot%20as%20plt%0A%20%20%20%20import%20numpy%20as%20np%0A%20%20%20%20import%20pandas%20as%20pd%0A%20%20%20%20import%20polars%20as%20pl%0A%20%20%20%20import%20pyarrow.parquet%20as%20pq%0A%20%20%20%20import%20shap%0A%20%20%20%20from%20pyod.models.ecod%20import%20ECOD%0A%20%20%20%20from%20sklearn.ensemble%20import%20IsolationForest%2C%20RandomForestClassifier%0A%20%20%20%20from%20sklearn.metrics%20import%20confusion_matrix%2C%20precision_score%2C%20recall_score%0A%20%20%20%20from%20sklearn.model_selection%20import%20train_test_split%0A%20%20%20%20from%20sklearn.neighbors%20import%20LocalOutlierFactor%0A%20%20%20%20from%20sklearn.preprocessing%20import%20OneHotEncoder%2C%20RobustScaler%0A%0A%20%20%20%20import%20course%20%20%23%20this%20course's%20helpers%3A%20the%20survey's%20tables%2C%20file%20locations%20and%20exercise%20checks%0A%20%20%20%20from%20course%20import%20NOT_YET%2C%20PATHS%2C%20UNIT_KEY%2C%20attempt%2C%20check_cases%2C%20try_it%2C%20waiting_for%0A%0A%20%20%20%20%23%20The%20survey%2C%20clean%20as%20module%202%20teaches%3A%20every%20region's%20rows%2C%20removed%20households%20and%20voided%20rows%20left%20out%0A%20%20%20%20units%20%3D%20course.units()%0A%20%20%20%20boats%20%3D%20course.child(%22boat%22)%0A%20%20%20%20catch%20%3D%20course.child(%22catch%22)%0A%20%20%20%20gears%20%3D%20course.child(%22gear%22)%0A%20%20%20%20landings%20%3D%20course.child(%22landing%22)%0A%20%20%20%20crew%20%3D%20course.child(%22crew%22)%0A%20%20%20%20members%20%3D%20course.members()%0A%20%20%20%20households%20%3D%20course.households()%0A%20%20%20%20planted%20%3D%20course.planted_defects()%20%20%23%20every%20defect%20the%20course%20planted%3B%20a%20real%20survey%20has%20no%20such%20list%0A%0A%20%20%20%20%23%20The%20features%20every%20detector%20in%20this%20module%20reads%3A%20one%20number%20each%20per%20fishing%20unit%20(section%201)%0A%20%20%20%20FEATURES%20%3D%20%5B%22n_boats%22%2C%20%22largest_tonnage%22%2C%20%22longest_boat_m%22%2C%20%22sum_tonnage%22%2C%20%22sum_engine_hp%22%2C%20%22n_species%22%2C%20%22n_gears%22%2C%20%22n_landings%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22n_crew%22%2C%20%22hh_size%22%2C%20%22age_of_operator%22%2C%20%22hh_interview_minutes%22%5D%0A%20%20%20%20HOUSEHOLD%20%3D%20%5B%22region_code%22%2C%20%22hh_id%22%5D%20%20%23%20a%20household%20is%20its%20region%20and%20its%20id%3A%20ids%20repeat%20across%20regions%0A%20%20%20%20BLUE%2C%20ORANGE%2C%20GREY%20%3D%20%22%230072B2%22%2C%20%22%23E69F00%22%2C%20%22%23999999%22%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%20Anomalies%20with%20machine%20learning%0A%0A%20%20%20%20**Where%20this%20is%20in%20a%20survey's%20processing.**%20Reviewing%20and%20validating%20the%20data%20a%20second%20time%2C%20with%20models%3A%20a%20second%20look%20after%20module%204's%20edit%20rules%20and%20module%208's%20statistics%2C%20on%20the%20survey%20the%20modules%20before%20it%20matched%2C%20edited%20and%20tabulated.%0A%0A%20%20%20%20Module%208%20found%20anomalies%20with%20rules%20and%20statistics%3A%20a%20code%20outside%20its%20list%2C%20a%20ratio%20far%20from%20its%20group's%2C%20an%20interviewer%20whose%20interviews%20are%20too%20short.%20Someone%20who%20knew%20what%20a%20wrong%20row%20looks%20like%20wrote%20each%20check.%20This%20module%20asks%20what%20a%20computer%20finds%20when%20nobody%20wrote%20the%20check.%20A%20**detector**%20learns%20what%20the%20survey's%20fishing%20units%20usually%20look%20like%20and%20scores%20each%20one%20by%20how%20far%20it%20sits%20from%20that.%20Then%20the%20module%20asks%20the%20question%20every%20flag%20has%20to%20answer%20before%20a%20supervisor%20spends%20an%20afternoon%20on%20it%3A%20**did%20the%20detector%20find%20anything%20the%20rules%20had%20not%3F**%0A%0A%20%20%20%20%7C%20section%20%7C%20what%20you%20do%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%201%20%C2%B7%20Features%20from%20survey%20rows%20%7C%20one%20row%20of%20numbers%20per%20fishing%20unit%2C%20built%20from%20nine%20tables%3A%20what%20goes%20in%2C%20what%20stays%20out%2C%20how%20codes%20and%20scales%20are%20handled%20%7C%0A%20%20%20%20%7C%202%20%C2%B7%20Isolation%20Forest%2C%20LOF%20and%20ECOD%20%7C%20three%20detectors%2C%20their%20scores%2C%20and%20how%20many%20rows%20they%20flag%20%7C%0A%20%20%20%20%7C%203%20%C2%B7%20Judging%20detectors%20%7C%20precision%20and%20recall%20against%20the%20planted%20defects%20and%20against%20the%20rules%2C%20and%20why%20a%20row%20was%20flagged%20%7C%0A%20%20%20%20%7C%204%20%C2%B7%20When%20you%20have%20labels%20%7C%20a%20random%20forest%20trained%20on%20the%202021%20round's%20edits%2C%20and%20what%20those%20edits%20cannot%20teach%20it%20%7C%0A%20%20%20%20%7C%205%20%C2%B7%20A%20large%20table%20%7C%20240%2C000%20fishing%20units%20scored%20with%20polars%2C%20DuckDB%20and%20Parquet%2C%20in%20chunks%20where%20that%20gives%20the%20same%20answer%20%7C%0A%0A%20%20%20%20**The%20tables.**%20The%20setup%20cell%20reads%20the%20survey%20clean%2C%20as%20module%202%20taught%3A%20removed%20households%20and%20voided%20rows%20left%20out%2C%20every%20region%20in%20one%20table.%20%60planted%60%20is%20the%20course's%20list%20of%20planted%20defects%20(%60course.planted_defects()%60).%20A%20real%20survey%20has%20no%20such%20list%3B%20this%20module%20uses%20it%20as%20a%20survey%20team%20would%20use%20a%20reinterview%20sample%2C%20to%20measure%20how%20often%20a%20detector%20is%20right.%0A%0A%20%20%20%20**The%20libraries.**%20scikit-learn%201.9%20(%60sklearn%60)%20for%20Isolation%20Forest%2C%20the%20Local%20Outlier%20Factor%20and%20the%20random%20forest%3B%20PyOD%203.6%20(%60pyod%60)%20for%20ECOD%3B%20shap%200.54%20to%20explain%20a%20flag.%20Every%20method%20that%20draws%20random%20numbers%20gets%20a%20fixed%20%60random_state%60%2C%20so%20the%20same%20code%20flags%20the%20same%20rows%20on%20every%20computer%20and%20in%20every%20run.%20The%20checks%20depend%20on%20that.%0A%0A%20%20%20%20Exercises%20work%20as%20in%20the%20modules%20before%3A%20write%20the%20function%2C%20delete%20the%20%60raise%60%20line%2C%20use%20the%20**Try%20it**%20cell%2C%20read%20the%20check.%20If%20something%20goes%20red%2C%20read%20the%20error's%20**last%20line**%20first.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20course.quizzes_at(%229.0%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%201%20%C2%B7%20Features%20from%20survey%20rows%3A%20encoding%2C%20scaling%2C%20what%20to%20leave%20out%0A%0A%20%20%20%20**The%20problem.**%20A%20detector%20reads%20a%20table%20of%20numbers%3A%20one%20row%20per%20unit%2C%20one%20column%20per%20**feature**%20(a%20measured%20property%20of%20the%20unit)%2C%20and%20nothing%20else.%20The%20survey%20is%20ten%20tables%20of%20codes%20held%20together%20by%20keys.%20Before%20any%20detector%20runs%2C%20someone%20decides%20what%20the%20unit%20is%2C%20which%20answers%20describe%20it%2C%20and%20how%20a%20code%20becomes%20a%20number.%20Those%20decisions%20shape%20the%20flags%20more%20than%20the%20choice%20of%20detector%20does.%0A%0A%20%20%20%20**The%20unit.**%20The%20questionnaire%20describes%20each%20fishing%20unit%20a%20household%20runs%2C%20so%20the%20unit%20is%20the%20fishing%20unit%2C%20keyed%20on%20%60UNIT_KEY%60%3A%20the%20region%2C%20the%20household%20and%20the%20two%20key%20parts%20module%203%20matched%2C%20the%20operator's%20roster%20line%20and%20the%20unit's%20number.%20A%20unit%20has%20boats%2C%20crew%2C%20gear%2C%20catch%20and%20landing%20sites%20in%20its%20child%20tables%2C%20and%20an%20operator%20and%20a%20household%20in%20%60member%60%20and%20%60household%60.%0A%0A%20%20%20%20**The%20features.**%20Each%20is%20one%20number%20per%20unit%3A%0A%0A%20%20%20%20%7C%20feature%20%7C%20from%20%7C%20how%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%60n_boats%60%20%7C%20%60boat%60%20%7C%20the%20unit's%20boat%20rows%20%7C%0A%20%20%20%20%7C%20%60largest_tonnage%60%2C%20%60sum_tonnage%60%20%7C%20boat%20%7C%20the%20largest%20and%20the%20summed%20gross%20tonnage%20%7C%0A%20%20%20%20%7C%20%60longest_boat_m%60%20%7C%20boat%20%7C%20the%20longest%20boat%2C%20in%20meters%20%7C%0A%20%20%20%20%7C%20%60sum_engine_hp%60%20%7C%20boat%20%7C%20the%20engines'%20power%20added%20up%2C%200%20for%20a%20boat%20with%20no%20engine%20%7C%0A%20%20%20%20%7C%20%60n_species%60%20%7C%20%60catch%60%20%7C%20distinct%20species%20codes%20%7C%0A%20%20%20%20%7C%20%60n_gears%60%20%7C%20%60gear%60%20%7C%20the%20unit's%20gear%20rows%20%7C%0A%20%20%20%20%7C%20%60n_landings%60%20%7C%20%60landing%60%20%7C%20the%20unit's%20landing%20sites%20%7C%0A%20%20%20%20%7C%20%60n_crew%60%20%7C%20%60crew%60%20%7C%20the%20unit's%20crew%20rows%20%7C%0A%20%20%20%20%7C%20%60hh_size%60%20%7C%20%60member%60%20%7C%20the%20household's%20member%20rows%20%7C%0A%20%20%20%20%7C%20%60age_of_operator%60%20%7C%20member%20%7C%20the%20age%20of%20the%20member%20whose%20roster%20line%20is%20the%20unit's%20%60operator_line%60%20%7C%0A%20%20%20%20%7C%20%60hh_interview_minutes%60%20%7C%20%60household%60%20%7C%20the%20interview's%20length%20%7C%0A%0A%20%20%20%20%23%23%23%20One%20boat%2C%20one%20length%20in%20meters%0A%0A%20%20%20%20A%20boat's%20gross%20tonnage%20is%20one%20column%2C%20%60boat_tonnage%60%2C%20which%20the%20capture%20program%20stored.%20Its%20length%20is%20not%3A%20%60boat_measured_in%60%20says%20where%20the%20size%20comes%20from%2C%20measured%20in%20meters%20(2)%2C%20measured%20in%20feet%20(3)%2C%20or%20copied%20from%20the%20registration%20papers%20(1)%2C%20which%20give%20no%20length.%20Taking%20the%20largest%20%60boat_length%60%20as%20it%20stands%20would%20compare%20feet%20with%20meters.%20%60np.select%60%20(module%205)%20turns%20each%20length%20into%20meters%20by%20the%20code%20beside%20it%3A%20a%20length%20in%20feet%20is%20divided%20by%203.281%2C%20and%20a%20boat%20sized%20from%20its%20papers%20gets%20no%20length.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20boat_features(boats%3A%20pd.DataFrame)%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22One%20row%20per%20unit%20that%20has%20boats%3A%20n_boats%2C%20largest_tonnage%2C%20longest_boat_m%2C%20sum_tonnage%20and%20sum_engine_hp%2C%20keyed%20on%20UNIT_KEY.%22%22%22%0A%20%20%20%20measured%20%3D%20boats%5B%22boat_measured_in%22%5D%20%20%23%201%20%3D%20from%20the%20papers%2C%20no%20length%3B%202%20%3D%20measured%20in%20meters%3B%203%20%3D%20measured%20in%20feet%0A%20%20%20%20length_m%20%3D%20np.select(%5Bmeasured%20%3D%3D%202%2C%20measured%20%3D%3D%203%5D%2C%20%5Bboats%5B%22boat_length%22%5D%2C%20boats%5B%22boat_length%22%5D%20%2F%203.281%5D%2C%20default%3Dnp.nan)%0A%20%20%20%20return%20(boats%5BUNIT_KEY%5D.assign(gt%3Dboats%5B%22boat_tonnage%22%5D%2C%20length_m%3Dlength_m%2C%20hp%3Dboats%5B%22boat_engine_hp%22%5D.fillna(0))%0A%20%20%20%20%20%20%20%20%20%20%20%20.groupby(UNIT_KEY%2C%20as_index%3DFalse)%0A%20%20%20%20%20%20%20%20%20%20%20%20.agg(n_boats%3D(%22gt%22%2C%20%22size%22)%2C%20largest_tonnage%3D(%22gt%22%2C%20%22max%22)%2C%20longest_boat_m%3D(%22length_m%22%2C%20%22max%22)%2C%20sum_tonnage%3D(%22gt%22%2C%20%22sum%22)%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20sum_engine_hp%3D(%22hp%22%2C%20%22sum%22)))%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20The%20boat%20features%20of%20the%20first%20units%3A%20one%20row%20each%2C%20whatever%20unit%20their%20boats%20were%20measured%20in%0A%20%20%20%20boat_features(boats).head(5)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22The%20R%20way%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%60%60%60r%0A%20%20%20%20boats%20%7C%3E%0A%20%20%20%20%20%20mutate(length_m%20%3D%20case_when(boat_measured_in%20%3D%3D%202%20~%20boat_length%2C%20boat_measured_in%20%3D%3D%203%20~%20boat_length%20%2F%203.281)%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20hp%20%3D%20coalesce(boat_engine_hp%2C%200))%20%7C%3E%0A%20%20%20%20%20%20group_by(region_code%2C%20hh_id%2C%20boat_operator_line%2C%20boat_unit_no)%20%7C%3E%0A%20%20%20%20%20%20summarise(n_boats%20%3D%20n()%2C%20largest_tonnage%20%3D%20max(boat_tonnage)%2C%20longest_boat_m%20%3D%20max(length_m%2C%20na.rm%20%3D%20TRUE)%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20sum_tonnage%20%3D%20sum(boat_tonnage)%2C%20sum_engine_hp%20%3D%20sum(hp)%2C%20.groups%20%3D%20%22drop%22)%0A%20%20%20%20%60%60%60%0A%0A%20%20%20%20%60np.select%60%20is%20%60case_when%60%20with%20the%20conditions%20and%20the%20values%20in%20two%20lists%3B%20%60default%3D%60%20is%20what%20%60case_when%60%20gives%20a%20row%20no%20condition%20matches%20(%60NA%60).%20One%20difference%3A%20R's%20%60max(...%2C%20na.rm%20%3D%20TRUE)%60%20of%20nothing%20but%20missing%20values%20is%20%60-Inf%60%20with%20a%20warning%2C%20while%20pandas'%20%60max%60%20gives%20a%20missing%20value%2C%20which%20the%20next%20step%20fills.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Counts%20from%20the%20other%20child%20tables%2C%20and%20the%20household's%20answers%0A%0A%20%20%20%20The%20catch%2C%20gear%2C%20landing%20and%20crew%20features%20count%20rows%20per%20unit.%20%60n_species%60%20counts%20**distinct**%20codes%20(%60nunique%60%2C%20R's%20%60n_distinct%60)%3A%20module%204%20found%20catch%20rows%20entered%20twice%2C%20and%20a%20row%20count%20would%20add%20one%20species%20for%20each.%20Two%20features%20come%20from%20%60member%60%3A%20the%20household's%20number%20of%20member%20rows%2C%20and%20the%20operator's%20age%2C%20from%20the%20member%20whose%20roster%20line%20(%60mem_line%60)%20is%20the%20unit's%20%60operator_line%60.%0A%0A%20%20%20%20**A%20household%20is%20its%20region%20and%20its%20id.**%20Each%20regional%20database%20numbers%20its%20households%20on%20its%20own%2C%20so%20one%20%60hh_id%60%20names%20a%20household%20in%20region%2001%20and%20another%20in%20region%2007.%20Join%20the%20households%20on%20%60hh_id%60%20alone%20and%20every%20unit%20finds%20every%20household%20with%20its%20number%2C%20in%20every%20region.%20%60validate%3D%22many_to_one%22%60%20(module%203)%20writes%20down%20that%20each%20unit%20has%20one%20household%2C%20and%20pandas%20refuses%20when%20that%20is%20false.%20Read%20the%20error%20from%20its%20last%20line%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20The%20household's%20interview%20joined%20on%20the%20id%20alone%2C%20then%20on%20the%20region%20and%20the%20id%0A%20%20%20%20_on_id%20%3D%20units%5BUNIT_KEY%5D.merge(households%5B%5B%22hh_id%22%2C%20%22hh_interview_minutes%22%5D%5D%2C%20on%3D%22hh_id%22%2C%20how%3D%22left%22)%0A%20%20%20%20try%3A%0A%20%20%20%20%20%20%20%20units%5BUNIT_KEY%5D.merge(households%5B%5B%22hh_id%22%2C%20%22hh_interview_minutes%22%5D%5D%2C%20on%3D%22hh_id%22%2C%20how%3D%22left%22%2C%20validate%3D%22many_to_one%22)%0A%20%20%20%20%20%20%20%20_message%20%3D%20%22no%20error%22%0A%20%20%20%20except%20pd.errors.MergeError%20as%20_error%3A%0A%20%20%20%20%20%20%20%20_message%20%3D%20f%22MergeError%3A%20%7Bstr(_error).splitlines()%5B0%5D%7D%22%0A%20%20%20%20_on_household%20%3D%20units%5BUNIT_KEY%5D.merge(households%5B%5B*HOUSEHOLD%2C%20%22hh_interview_minutes%22%5D%5D%2C%20on%3DHOUSEHOLD%2C%20how%3D%22left%22%2C%20validate%3D%22many_to_one%22)%0A%20%20%20%20mo.vstack(%5B%0A%20%20%20%20%20%20%20%20mo.md(f%22**On%20%60hh_id%60%20alone%3A**%20%7Blen(units)%3A%2C%7D%20units%20in%2C%20**%7Blen(_on_id)%3A%2C%7D%20rows%20out**.%20With%20%60validate%3D%5C%22many_to_one%5C%22%60%20the%20join%20refuses%3A%22)%2C%0A%20%20%20%20%20%20%20%20mo.md(f%22%60%60%60%5Cn%7B_message%7D%5Cn%60%60%60%22)%2C%0A%20%20%20%20%20%20%20%20mo.md(f%22**On%20the%20region%20and%20the%20id**%20(%60HOUSEHOLD%60)%3A%20%7Blen(units)%3A%2C%7D%20units%20in%2C%20%7Blen(_on_household)%3A%2C%7D%20rows%20out.%22)%2C%0A%20%20%20%20%5D)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20survey_features()%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22One%20row%20per%20fishing%20unit%20of%20the%20clean%20survey%3A%20unit_id%2C%20the%20unit's%20key%20and%20scale%20(unit_scale)%2C%20the%20FEATURES%2C%20and%0A%20%20%20%20beside%20them%2C%20not%20features%2C%20the%20household's%20interviewer%2C%20stratum%20and%20final%20weight.%22%22%22%0A%20%20%20%20%23%201.%20The%20units%2C%20each%20once%3A%20module%204%20found%20units%20entered%20twice%0A%20%20%20%20out%20%3D%20units%5B%5B*UNIT_KEY%2C%20%22unit_scale%22%5D%5D.drop_duplicates(UNIT_KEY)%0A%20%20%20%20%23%202.%20The%20interview%20and%20the%20design%20from%20the%20household%2C%20joined%20on%20the%20household%20(region%20and%20id)%0A%20%20%20%20out%20%3D%20out.merge(households%5B%5B*HOUSEHOLD%2C%20%22hh_interview_minutes%22%2C%20%22hh_interviewer%22%2C%20%22sel_stratum%22%2C%20%22sel_final_weight%22%5D%5D%2C%20on%3DHOUSEHOLD%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20how%3D%22left%22%2C%20validate%3D%22many_to_one%22)%0A%20%20%20%20%23%203.%20The%20child%20tables'%20features%3A%20boats%2C%20then%20a%20count%20of%20distinct%20species%2C%20and%20of%20gears%2C%20landing%20sites%20and%20crew%20per%20unit%0A%20%20%20%20counts%20%3D%20%5B%0A%20%20%20%20%20%20%20%20boat_features(boats)%2C%0A%20%20%20%20%20%20%20%20catch.groupby(UNIT_KEY%2C%20as_index%3DFalse).agg(n_species%3D(%22catch_species%22%2C%20%22nunique%22))%2C%0A%20%20%20%20%20%20%20%20gears.groupby(UNIT_KEY%2C%20as_index%3DFalse).agg(n_gears%3D(%22gear_type%22%2C%20%22size%22))%2C%0A%20%20%20%20%20%20%20%20landings.groupby(UNIT_KEY%2C%20as_index%3DFalse).agg(n_landings%3D(%22land_line%22%2C%20%22size%22))%2C%0A%20%20%20%20%20%20%20%20crew.groupby(UNIT_KEY%2C%20as_index%3DFalse).agg(n_crew%3D(%22crew_line%22%2C%20%22size%22))%2C%0A%20%20%20%20%5D%0A%20%20%20%20for%20part%20in%20counts%3A%0A%20%20%20%20%20%20%20%20out%20%3D%20out.merge(part%2C%20on%3DUNIT_KEY%2C%20how%3D%22left%22%2C%20validate%3D%22one_to_one%22)%0A%20%20%20%20%23%20A%20unit%20with%20no%20row%20in%20a%20child%20table%20has%20none%20of%20it%3A%20a%20missing%20count%20is%20a%20count%20of%200%0A%20%20%20%20zero%20%3D%20%5B%22n_boats%22%2C%20%22largest_tonnage%22%2C%20%22sum_tonnage%22%2C%20%22sum_engine_hp%22%2C%20%22n_species%22%2C%20%22n_gears%22%2C%20%22n_landings%22%2C%20%22n_crew%22%5D%0A%20%20%20%20out%5Bzero%5D%20%3D%20out%5Bzero%5D.fillna(0)%0A%20%20%20%20%23%204.%20The%20household's%20member%20rows%2C%20and%20the%20operator%3A%20the%20member%20whose%20roster%20line%20is%20operator_line%0A%20%20%20%20size%20%3D%20members.groupby(HOUSEHOLD%2C%20as_index%3DFalse).agg(hh_size%3D(%22mem_line%22%2C%20%22size%22))%0A%20%20%20%20operator%20%3D%20members%5B%5B*HOUSEHOLD%2C%20%22mem_line%22%2C%20%22mem_age%22%5D%5D.rename(columns%3D%7B%22mem_line%22%3A%20%22operator_line%22%2C%20%22mem_age%22%3A%20%22age_of_operator%22%7D)%0A%20%20%20%20out%20%3D%20out.merge(size%2C%20on%3DHOUSEHOLD%2C%20how%3D%22left%22%2C%20validate%3D%22many_to_one%22).merge(operator%2C%20on%3D%5B*HOUSEHOLD%2C%20%22operator_line%22%5D%2C%20how%3D%22left%22%2C%20validate%3D%22many_to_one%22)%0A%20%20%20%20%23%205.%20A%20length%20for%20every%20unit%3A%200%20with%20no%20boat%3B%20the%20scale's%20median%20where%20no%20boat%20was%20measured%20(sized%20from%20its%20papers)%0A%20%20%20%20no_length%20%3D%20out%5B%22longest_boat_m%22%5D.isna()%20%26%20(out%5B%22n_boats%22%5D%20%3E%200)%0A%20%20%20%20out%5B%22longest_boat_m%22%5D%20%3D%20out%5B%22longest_boat_m%22%5D.fillna(out.groupby(%22unit_scale%22)%5B%22longest_boat_m%22%5D.transform(%22median%22)).where(out%5B%22n_boats%22%5D%20%3E%200%2C%200.0)%0A%20%20%20%20out%5B%22length_imputed%22%5D%20%3D%20no_length%0A%20%20%20%20whole%20%3D%20%5B%22n_boats%22%2C%20%22n_species%22%2C%20%22n_gears%22%2C%20%22n_landings%22%2C%20%22n_crew%22%2C%20%22hh_size%22%2C%20%22age_of_operator%22%5D%0A%20%20%20%20out%5Bwhole%5D%20%3D%20out%5Bwhole%5D.astype(int)%0A%20%20%20%20out.insert(0%2C%20%22unit_id%22%2C%20unit_ids(out))%0A%20%20%20%20return%20out.reset_index(drop%3DTrue)%0A%0A%0A%40app.function%0Adef%20unit_ids(table%3A%20pd.DataFrame)%20-%3E%20pd.Series%3A%0A%20%20%20%20%22%22%22One%20text%20id%20per%20fishing%20unit%2C%20from%20its%20region%2C%20household%20and%20key%20parts%3A%20%2201-5012-1-1%22.%22%22%22%0A%20%20%20%20parts%20%3D%20%5Btable%5B%22region_code%22%5D.astype(str).str.zfill(2)%2C%20*(table%5Bc%5D.astype(int).astype(str)%20for%20c%20in%20UNIT_KEY%5B1%3A%5D)%5D%0A%20%20%20%20out%20%3D%20parts%5B0%5D%0A%20%20%20%20for%20part%20in%20parts%5B1%3A%5D%3A%0A%20%20%20%20%20%20%20%20out%20%3D%20out%20%2B%20%22-%22%20%2B%20part%0A%20%20%20%20return%20out.rename(%22unit_id%22)%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20The%20features%20table%3A%20one%20row%20per%20unit%2C%20the%20twelve%20features%20in%20the%20middle%2C%20the%20design%20columns%20beside%20them%0A%20%20%20%20features%20%3D%20survey_features()%0A%20%20%20%20mo.vstack(%5B%0A%20%20%20%20%20%20%20%20mo.md(f%22**%7Blen(features)%3A%2C%7D%20fishing%20units**%20(%7Blen(units)%3A%2C%7D%20rows%20in%20the%20unit%20table%2C%20of%20which%20%7Blen(units)%20-%20len(features)%7D%20are%20the%20units%20entered%20twice).%20%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20f%22%7Bint(features%5B'length_imputed'%5D.sum())%7D%20units%20had%20only%20boats%20sized%20from%20their%20papers%2C%20with%20no%20length%3A%20their%20length%20is%20the%20median%20of%20their%20scale's%2C%20since%20a%200%20would%20say%20they%20have%20no%20boat.%22)%2C%0A%20%20%20%20%20%20%20%20features.head(5)%2C%0A%20%20%20%20%5D)%0A%20%20%20%20return%20(features%2C)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%60survey_features()%60%20is%20the%20whole%20build%20in%20one%20function%2C%20with%20its%20steps%20numbered%3B%20the%20cells%20above%20show%20its%20two%20hardest%20parts.%20Section%205's%20large%20table%2C%20%60units_2025_all_regions.parquet%60%2C%20has%20these%20same%20twelve%20feature%20columns%2C%20built%20the%20same%20way%20for%20240%2C000%20units.%0A%0A%20%20%20%20%23%23%23%20What%20to%20leave%20out%0A%0A%20%20%20%20Every%20column%20a%20detector%20reads%20is%20one%20it%20can%20find%20unusual.%20A%20column%20that%20is%20not%20an%20answer%20about%20the%20unit%20turns%20the%20detector%20toward%20something%20else%3A%0A%0A%20%20%20%20%7C%20column%20%7C%20why%20it%20stays%20out%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%60unit_id%60%2C%20%60region_code%60%2C%20%60hh_id%60%2C%20the%20key%20parts%20%7C%20identifiers.%20A%20number%20that%20names%20a%20row%20says%20nothing%20about%20it%3B%20a%20detector%20cuts%20on%20it%20like%20any%20other%20column%2C%20and%20the%20flags%20then%20depend%20on%20how%20the%20households%20happened%20to%20be%20numbered%20%7C%0A%20%20%20%20%7C%20%60hh_interviewer%60%20%7C%20who%20asked%2C%20not%20what%20was%20answered.%20Module%208%20judges%20interviewers%20as%20groups%20of%20interviews%2C%20which%20is%20where%20it%20belongs%20%7C%0A%20%20%20%20%7C%20%60sel_final_weight%60%2C%20and%20every%20weight%20%7C%20the%20sample%20design%2C%20not%20the%20unit%3A%20stratum%20F's%20registered%20large%20units%20weigh%20about%201%2C%20and%20the%20households%20of%20the%20area%20strata%20A%2C%20B%20and%20C%20about%203%2C%205%20and%2016%2C%20by%20design.%20Weights%20get%20their%20own%20check%2C%20module%208's%20weight%20outliers%20%7C%0A%20%20%20%20%7C%20%60sel_stratum%60%20%7C%20the%20design%20again%20%7C%0A%0A%20%20%20%20The%20weight%20is%20the%20one%20most%20often%20left%20in%2C%20because%20it%20is%20a%20number%20and%20sits%20in%20the%20same%20table.%20The%20cell%20below%20fits%20the%20same%20detector%20(an%20Isolation%20Forest%2C%20section%202)%20on%20the%20large-scale%20units%20twice%2C%20with%20and%20without%20the%20weight%2C%20and%20counts%20where%20the%2020%20units%20it%20finds%20most%20unusual%20were%20drawn%3A%20in%20stratum%20F%2C%20or%20in%20an%20area%20stratum.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20The%20same%20detector%20with%20and%20without%20the%20weight%3A%20whose%20households%20does%20it%20find%20unusual%3F%0A%20%20%20%20_large%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%202%5D%0A%20%20%20%20_rows%20%3D%20%5B%5D%0A%20%20%20%20for%20_label%2C%20_columns%20in%20%5B(%22the%20twelve%20features%22%2C%20FEATURES)%2C%20(%22the%20twelve%20features%20and%20sel_final_weight%22%2C%20%5B*FEATURES%2C%20%22sel_final_weight%22%5D)%5D%3A%0A%20%20%20%20%20%20%20%20_scores%20%3D%20IsolationForest(n_estimators%3D200%2C%20random_state%3D0).fit(_large%5B_columns%5D).score_samples(_large%5B_columns%5D)%0A%20%20%20%20%20%20%20%20_top%20%3D%20_large.iloc%5Bnp.argsort(_scores%2C%20kind%3D%22stable%22)%5B%3A20%5D%5D%0A%20%20%20%20%20%20%20%20_rows.append(%7B%22detector%20reads%22%3A%20_label%2C%20%22stratum%20F%20among%20the%2020%22%3A%20int((_top%5B%22sel_stratum%22%5D%20%3D%3D%20%22F%22).sum())%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22an%20area%20stratum%20among%20the%2020%22%3A%20int((_top%5B%22sel_stratum%22%5D%20!%3D%20%22F%22).sum())%7D)%0A%20%20%20%20_share%20%3D%20(_large%5B%22sel_stratum%22%5D%20!%3D%20%22F%22).mean()%0A%20%20%20%20_weights%20%3D%20_large.groupby(_large%5B%22sel_stratum%22%5D%20%3D%3D%20%22F%22)%5B%22sel_final_weight%22%5D.median()%0A%20%20%20%20mo.vstack(%5B%0A%20%20%20%20%20%20%20%20pd.DataFrame(_rows)%2C%0A%20%20%20%20%20%20%20%20mo.md(f%22The%20area%20strata%20hold%20%7B_share%3A.0%25%7D%20of%20the%20large-scale%20units.%20Their%20households%20weigh%20%7B_weights%5BFalse%5D%3A.1f%7D%20at%20the%20median%20and%20stratum%20F's%20%7B_weights%5BTrue%5D%3A.1f%7D%3A%20given%20the%20weight%2C%20the%20detector%20picks%20out%20the%20area%20strata's%20households%20for%20the%20stratum%20they%20were%20drawn%20from%2C%20which%20is%20the%20design%2C%20not%20an%20anomaly.%22)%2C%0A%20%20%20%20%5D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Encoding%3A%20codes%20are%20not%20quantities%0A%0A%20%20%20%20%60unit_scale%60%20is%20an%20answer%2C%20but%20a%20code%3A%201%20means%20small-scale%20(no%20boat%2C%20or%20every%20boat%20under%205.0%20gross%20tons)%20and%202%20means%20large-scale.%20Read%20as%20a%20number%2C%20it%20says%202%20is%20twice%201%2C%20and%20a%20detector%20that%20measures%20distances%20treats%20the%20gap%20between%20the%20codes%20as%20a%20quantity.%20The%20region%20codes%20show%20the%20trap%20more%20plainly%3A%2007%20is%20not%20%22further%22%20from%2001%20than%2004%20is.%0A%0A%20%20%20%20%7C%20detector%20%7C%20reads%20a%20code%20as%20%7C%20so%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20trees%20(Isolation%20Forest%2C%20random%20forest)%20%7C%20a%20place%20to%20cut%3A%20below%20or%20above%20%7C%20a%20code%20as%20a%20number%20(**ordinal%20encoding**)%20works%3B%20with%20two%20values%20any%20cut%20separates%20them%20%7C%0A%20%20%20%20%7C%20distances%20(LOF)%20and%20per-column%20tails%20(ECOD)%20%7C%20a%20quantity%20%7C%20**one-hot%20encoding**%3A%20one%200%2F1%20column%20per%20value%2C%20so%20every%20pair%20of%20values%20is%20the%20same%20distance%20apart%20%7C%0A%0A%20%20%20%20For%20a%20code%20with%20two%20values%2C%20one%200%2F1%20column%20says%20everything%3A%20%60large_scale%60%2C%201%20when%20%60unit_scale%60%20is%202.%20scikit-learn's%20%60OneHotEncoder%60%20writes%20the%20columns%20for%20a%20code%20with%20more%20values%2C%20as%20for%20the%20region%20below.%20A%20code%20with%20few%20values%20can%20also%20split%20the%20table%20instead%20of%20joining%20the%20features%3A%20section%202%20fits%20one%20detector%20per%20scale%2C%20as%20module%208%20compared%20each%20value%20with%20its%20own%20group.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20One-hot%3A%20one%200%2F1%20column%20per%20region%20code%2C%20and%20for%20a%20code%20of%20two%20values%2C%20one%20column%20is%20enough%20(drop%3D%22if_binary%22)%0A%20%20%20%20_region%20%3D%20OneHotEncoder(sparse_output%3DFalse).set_output(transform%3D%22pandas%22).fit_transform(features%5B%5B%22region_code%22%5D%5D)%0A%20%20%20%20_scale%20%3D%20OneHotEncoder(sparse_output%3DFalse%2C%20drop%3D%22if_binary%22).set_output(transform%3D%22pandas%22).fit_transform(features%5B%5B%22unit_scale%22%5D%5D)%0A%20%20%20%20mo.hstack(%5Bfeatures%5B%5B%22unit_id%22%2C%20%22region_code%22%2C%20%22unit_scale%22%5D%5D.head(4)%2C%20_region.head(4)%2C%20_scale.head(4)%5D%2C%20justify%3D%22start%22%2C%20gap%3D1.5)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Scaling%3A%20every%20column%20on%20one%20footing%0A%0A%20%20%20%20LOF%20measures%20how%20far%20apart%20two%20units%20are%20by%20adding%20up%20their%20differences%2C%20column%20by%20column.%20%60age_of_operator%60%20runs%20over%20tens%20of%20years%20and%20%60n_boats%60%20over%200%20to%205%2C%20so%20unscaled%2C%20a%20difference%20of%20one%20boat%20counts%20as%20much%20as%20a%20difference%20of%20one%20year%2C%20and%20the%20age%20and%20the%20interview's%20minutes%20decide%20every%20distance.%20Scaling%20puts%20every%20column%20on%20one%20footing%3A%20a%20column's%20typical%20spread%20becomes%20one%20unit.%0A%0A%20%20%20%20Two%20scalers%2C%20two%20ideas%20of%20%22typical%20spread%22%3A%0A%0A%20%20%20%20%7C%20scaler%20%7C%20centers%20on%20%7C%20divides%20by%20%7C%20one%20impossible%20value%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%60StandardScaler%60%20(R's%20%60scale()%60)%20%7C%20the%20mean%20%7C%20the%20standard%20deviation%20%7C%20pulls%20the%20mean%20and%20inflates%20the%20standard%20deviation%2C%20so%20every%20other%20row%20looks%20ordinary%20%7C%0A%20%20%20%20%7C%20%60RobustScaler%60%20%7C%20the%20median%20%7C%20the%20interquartile%20range%20(IQR%3A%20the%2075th%20percentile%20less%20the%2025th)%20%7C%20moves%20neither%2C%20since%20it%20is%20one%20row%20of%20many%20%7C%0A%0A%20%20%20%20%60RobustScaler%60%20is%20module%208's%20robust%20z%20in%20matrix%20form%2C%20and%20the%20survey%20shows%20why%20it%20is%20the%20default%20here.%20Three%20units%20have%20an%20operator%20aged%20over%20110%2C%20planted%20by%20module%204%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20The%20operator's%20age%2C%20with%20and%20without%20the%20impossible%20ages%3A%20the%20standard%20deviation%20moves%2C%20the%20IQR%20does%20not%0A%20%20%20%20_age%20%3D%20features%5B%22age_of_operator%22%5D%0A%20%20%20%20_possible%20%3D%20_age%5B_age%20%3C%3D%20110%5D%0A%20%20%20%20_iqr%20%3D%20lambda%20s%3A%20s.quantile(0.75)%20-%20s.quantile(0.25)%0A%20%20%20%20pd.DataFrame(%7B%0A%20%20%20%20%20%20%20%20%22age_of_operator%22%3A%20%5B%22all%20units%22%2C%20%22without%20the%20ages%20over%20110%22%5D%2C%0A%20%20%20%20%20%20%20%20%22mean%22%3A%20%5B_age.mean()%2C%20_possible.mean()%5D%2C%0A%20%20%20%20%20%20%20%20%22standard%20deviation%22%3A%20%5B_age.std()%2C%20_possible.std()%5D%2C%0A%20%20%20%20%20%20%20%20%22median%22%3A%20%5B_age.median()%2C%20_possible.median()%5D%2C%0A%20%20%20%20%20%20%20%20%22IQR%22%3A%20%5B_iqr(_age)%2C%20_iqr(_possible)%5D%2C%0A%20%20%20%20%7D).round(2)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Exercise%209.1.%20Robust%20scaling%2C%20by%20hand%0A%0A%20%20%20%20**Why%20it%20matters%3A**%20a%20scaler%20is%20two%20numbers%20per%20column%20and%20one%20line%20of%20arithmetic.%20Written%20by%20hand%20once%2C%20it%20stops%20being%20a%20black%20box%2C%20and%20R's%20%60scale()%60%20habit%20(mean%20and%20standard%20deviation)%20shows%20itself%20as%20the%20different%20choice%20it%20is.%0A%0A%20%20%20%20**Input%20%E2%86%92%20output%3A**%20a%20table%20of%20numeric%20columns%20%E2%86%92%20a%20table%20of%20the%20same%20shape%20and%20column%20names%2C%20each%20column%20with%20its%20**median**%20subtracted%20and%20then%20divided%20by%20its%20**IQR**%20(the%2075th%20percentile%20less%20the%2025th%2C%20pandas'%20%60quantile%60%2C%20default%20interpolation).%20A%20column%20whose%20IQR%20is%200%20(most%20of%20its%20values%20the%20same)%20is%20divided%20by%20**1**%2C%20not%20by%200%3A%20scikit-learn's%20%60RobustScaler%60%20does%20the%20same%2C%20and%20the%20result%20must%20equal%20its.%0A%0A%20%20%20%20%7C%20n_boats%20%7C%20age_of_operator%20%7C%20%E2%86%92%20%7C%20n_boats%20%7C%20age_of_operator%20%7C%0A%20%20%20%20%7C--%3A%7C--%3A%7C%3A--%7C--%3A%7C--%3A%7C%0A%20%20%20%20%7C%201%20%7C%2040%20%7C%20%7C%200.0%20%7C%20-0.5%20%7C%0A%20%20%20%20%7C%201%20%7C%2050%20%7C%20%7C%200.0%20%7C%200.0%20%7C%0A%20%20%20%20%7C%202%20%7C%2060%20%7C%20%7C%201.0%20%7C%200.5%20%7C%0A%0A%20%20%20%20Here%20%60n_boats%60%20has%20a%20median%20of%201%20and%20an%20IQR%20of%200%2C%20so%20it%20is%20divided%20by%201%3B%20%60age_of_operator%60%20has%20a%20median%20of%2050%20and%20an%20IQR%20of%2020.%0A%0A%20%20%20%20**Tools%3A**%20%60table.median()%60%2C%20%60table.quantile(0.75)%60%20and%20%60table.quantile(0.25)%60%20(one%20value%20per%20column)%2C%20and%20arithmetic%20between%20a%20table%20and%20a%20Series%2C%20which%20lines%20up%20by%20column%20name.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20robust_scale(table%3A%20pd.DataFrame)%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22Each%20column%20less%20its%20median%2C%20divided%20by%20its%20IQR%20(by%201%20where%20the%20IQR%20is%200)%3A%20RobustScaler%2C%20by%20hand.%22%22%22%0A%20%20%20%20%23%20Exercise%209.1%3A%20the%20task%20and%20examples%20are%20in%20the%20text%20above%20this%20cell.%0A%20%20%20%20%23%20Step%201%3A%20each%20column's%20median%2C%20and%20its%20IQR%3A%20quantile(0.75)%20less%20quantile(0.25)%0A%20%20%20%20%23%20Step%202%3A%20where%20the%20IQR%20is%200%2C%20use%201%20instead%20(Series.replace%20or%20where)%0A%20%20%20%20%23%20Step%203%3A%20return%20the%20table%20less%20the%20medians%2C%20divided%20by%20the%20IQRs%0A%20%20%20%20raise%20NotImplementedError(%22Exercise%209.1%22)%0A%0A%0A%40app.function%0Adef%20ages_fixture()%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22Five%20units%3A%20boats%20with%20no%20spread%2C%20an%20impossible%20age%2C%20and%20a%20column%20of%20decimals.%20Used%20by%20the%20check%20of%20Exercise%209.1.%22%22%22%0A%20%20%20%20return%20pd.DataFrame(%7B%22n_boats%22%3A%20%5B1%2C%201%2C%202%2C%201%2C%201%5D%2C%20%22age_of_operator%22%3A%20%5B40%2C%2050%2C%2060%2C%2045%2C%20199%5D%2C%20%22largest_tonnage%22%3A%20%5B0.4%2C%201.2%2C%200.9%2C%202.5%2C%200.7%5D%7D)%0A%0A%0A%40app.function%0Adef%20as_numbers(result%2C%20digits%3A%20int%20%3D%204)%20-%3E%20list%3A%0A%20%20%20%20%22%22%22A%20table%20or%20array%20as%20rows%20of%20rounded%20numbers%2C%20for%20the%20checks%3A%20its%20index%20and%20type%20don't%20count.%22%22%22%0A%20%20%20%20return%20np.asarray(result%2C%20dtype%3Dfloat).round(digits).tolist()%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_(features)%3A%0A%20%20%20%20check_cases(%0A%20%20%20%20%20%20%20%20%22Exercise%209.1%22%2C%20robust_scale%2C%0A%20%20%20%20%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22five%20units%3A%20boats%20with%20no%20spread%2C%20an%20age%20of%20199%22%2C%20(ages_fixture()%2C))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20survey's%20twelve%20features%22%2C%20(features%5BFEATURES%5D%2C))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20large-scale%20units'%20features%22%2C%20(features.loc%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%202%2C%20FEATURES%5D%2C))%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20what%3D%22tables%22%2C%20summarize%3Das_numbers%2C%0A%20%20%20%20%20%20%20%20hint%3D%22Subtract%20each%20column's%20median%20and%20divide%20by%20its%20IQR%20(quantile%200.75%20less%20quantile%200.25)%3B%20divide%20by%201%20where%20the%20IQR%20is%200.%22%2C%0A%20%20%20%20)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20Try%20it%3A%20your%20scaling%20of%20the%20five%20units%2C%20then%20scikit-learn's%2C%20which%20should%20be%20the%20same%0A%20%20%20%20try_it(robust_scale%2C%20ages_fixture())%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22If%20the%20check%20is%20red%3A%20common%20causes%20for%20Exercise%209.1%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%7C%20what%20you%20see%20%7C%20the%20usual%20cause%20%7C%20look%20at%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%60inf%60%20or%20%60nan%60%20in%20the%20%60n_boats%60%20column%20%7C%20Divided%20by%20an%20IQR%20of%200.%20%7C%20%60.replace(0%2C%201)%60%20on%20the%20IQRs%20%7C%0A%20%20%20%20%7C%20Every%20value%20smaller%20than%20it%20should%20be%2C%20the%20age%20of%20199%20near%202%20%7C%20The%20mean%20and%20standard%20deviation%2C%20R's%20%60scale()%60.%20%7C%20%60table.median()%60%20and%20the%20IQR%20%7C%0A%20%20%20%20%7C%20Values%20centered%20but%20not%20scaled%2C%20or%20scaled%20but%20not%20centered%20%7C%20One%20of%20the%20two%20steps%20left%20out.%20%7C%20%60(table%20-%20median)%20%2F%20iqr%60%20%7C%0A%20%20%20%20%7C%20Close%2C%20but%20not%20equal%20%7C%20%60quantile%60%20given%20another%20%60interpolation%3D%60.%20%7C%20the%20default%2C%20linear%20%7C%0A%0A%20%20%20%20Still%20stuck%20after%20ten%20minutes%3F%20Ask%20your%20table%2C%20then%20raise%20your%20hand.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20The%20two%20matrices%20the%20detectors%20read%0A%0A%20%20%20%20The%20rest%20of%20the%20module%20builds%20its%20inputs%20with%20two%20functions.%20Trees%20get%20the%20features%20as%20they%20are%2C%20with%20the%20scale%20as%20a%200%2F1%20column.%20Distance%20and%20tail%20methods%20get%20the%20features%20scaled%20by%20scikit-learn's%20%60RobustScaler%60%2C%20which%20does%20what%20Exercise%209.1%20does%20and%20remembers%20its%20medians%20and%20IQRs%2C%20so%20it%20can%20scale%20new%20rows%20the%20same%20way%20later.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20tree_matrix(table%3A%20pd.DataFrame)%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22The%20features%20for%20trees%3A%20the%20twelve%20as%20they%20are%2C%20and%20large_scale%20(1%20when%20unit_scale%20is%202%2C%20a%20boat%20of%205.0%20gross%20tons%20or%20more).%22%22%22%0A%20%20%20%20return%20table%5BFEATURES%5D.assign(large_scale%3D(table%5B%22unit_scale%22%5D%20%3D%3D%202).astype(int))%0A%0A%0A%40app.function%0Adef%20neighbor_matrix(table%3A%20pd.DataFrame)%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22The%20features%20for%20distances%20and%20tails%3A%20the%20twelve%20scaled%20by%20their%20medians%20and%20IQRs%2C%20and%20large_scale%20as%200%20or%201.%22%22%22%0A%20%20%20%20scaled%20%3D%20RobustScaler().set_output(transform%3D%22pandas%22).fit_transform(table%5BFEATURES%5D)%0A%20%20%20%20return%20scaled.assign(large_scale%3D(table%5B%22unit_scale%22%5D%20%3D%3D%202).astype(int).to_numpy())%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%202%20%C2%B7%20Isolation%20Forest%2C%20LOF%20and%20ECOD%3A%20scores%20and%20contamination%0A%0A%20%20%20%20**The%20problem.**%20%22Unusual%22%20needs%20a%20measure%20before%20a%20computer%20can%20find%20it.%20Three%20detectors%20measure%20it%20three%20ways%3A%0A%0A%20%20%20%20%7C%20detector%20%7C%20the%20idea%20%7C%20a%20unit%20is%20unusual%20when%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20**Isolation%20Forest**%20%7C%20cut%20the%20table%20at%20random%20until%20each%20row%20stands%20alone%20%7C%20few%20cuts%20isolate%20it%20%7C%0A%20%20%20%20%7C%20**Local%20Outlier%20Factor**%20(LOF)%20%7C%20compare%20how%20crowded%20each%20row's%20neighborhood%20is%20with%20how%20crowded%20its%20neighbors'%20are%20%7C%20its%20neighborhood%20is%20sparser%20than%20theirs%20%7C%0A%20%20%20%20%7C%20**ECOD**%20%7C%20read%20each%20column's%20distribution%20on%20its%20own%20%7C%20its%20values%20sit%20in%20the%20far%20tails%20of%20several%20columns%20%7C%0A%0A%20%20%20%20Each%20gives%20every%20row%20a%20**score**.%20None%20of%20them%20knows%20what%20a%20wrong%20answer%20is%3A%20they%20find%20what%20is%20rare%20in%20this%20table%2C%20which%20is%20a%20different%20thing%2C%20as%20the%20first%20fit%20shows.%0A%0A%20%20%20%20%23%23%23%20Isolation%20Forest%0A%0A%20%20%20%20%60IsolationForest(n_estimators%3D200%2C%20random_state%3D0)%60%20grows%20200%20trees.%20Each%20tree%20draws%20256%20rows%20at%20random%20and%20cuts%20them%20on%20a%20random%20column%20at%20a%20random%20value%2C%20again%20and%20again%2C%20until%20every%20row%20is%20alone.%20A%20row%20that%20ends%20up%20alone%20after%20few%20cuts%20is%20unusual.%20%60score_samples%60%20gives%20each%20row%20its%20score%2C%20the%20shorter%20its%20average%20path%20the%20**lower**.%20%60random_state%3D0%60%20fixes%20the%20draws%3A%20without%20it%2C%20every%20run%20grows%20other%20trees%20and%20flags%20slightly%20other%20rows.%0A%0A%20%20%20%20Fitted%20on%20the%20whole%20survey%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20One%20Isolation%20Forest%20on%20every%20unit%3B%20the%2040%20lowest%20scores%20are%20the%2040%20most%20unusual%0A%20%20%20%20whole_scores%20%3D%20IsolationForest(n_estimators%3D200%2C%20random_state%3D0).fit(tree_matrix(features)).score_samples(tree_matrix(features))%0A%20%20%20%20_top%20%3D%20features.iloc%5Bnp.argsort(whole_scores%2C%20kind%3D%22stable%22)%5B%3A40%5D%5D%0A%20%20%20%20_large%20%3D%20int((_top%5B%22unit_scale%22%5D%20%3D%3D%202).sum())%0A%20%20%20%20_share%20%3D%20(features%5B%22unit_scale%22%5D%20%3D%3D%202).mean()%0A%20%20%20%20mo.md(f%22**%7B_large%7D%20of%20the%2040%20most%20unusual%20units%20are%20large-scale**%20(%60unit_scale%60%20%3D%202%2C%20a%20boat%20of%205.0%20gross%20tons%20or%20more)%2C%20though%20large-scale%20units%20are%20%7B_share%3A.0%25%7D%20of%20the%20survey.%22)%0A%20%20%20%20return%20(whole_scores%2C)%0A%0A%0A%40app.cell%0Adef%20_(features%2C%20whole_scores)%3A%0A%20%20%20%20%23%20The%20scores%20of%20the%20two%20scales%20(matplotlib)%3A%20the%20large-scale%20units%20sit%20at%20the%20unusual%20end%0A%20%20%20%20_fig%2C%20_ax%20%3D%20plt.subplots(figsize%3D(6.5%2C%203))%0A%20%20%20%20_bins%20%3D%20np.linspace(whole_scores.min()%2C%20whole_scores.max()%2C%2040)%0A%20%20%20%20for%20_code%2C%20_label%2C%20_color%20in%20%5B(1%2C%20%22small-scale%20(every%20boat%20under%205%20gross%20tons)%22%2C%20BLUE)%2C%20(2%2C%20%22large-scale%20(a%20boat%20of%205%20gross%20tons%20or%20more)%22%2C%20ORANGE)%5D%3A%0A%20%20%20%20%20%20%20%20_ax.hist(whole_scores%5Bfeatures%5B%22unit_scale%22%5D.to_numpy()%20%3D%3D%20_code%5D%2C%20bins%3D_bins%2C%20color%3D_color%2C%20alpha%3D0.75%2C%20label%3D_label)%0A%20%20%20%20_ax.set_xlabel(%22Isolation%20Forest%20score%20(lower%20is%20more%20unusual)%22)%0A%20%20%20%20_ax.set_ylabel(%22fishing%20units%22)%0A%20%20%20%20_ax.set_title(%22One%20detector%20for%20the%20whole%20survey%22)%0A%20%20%20%20_ax.legend(frameon%3DFalse%2C%20loc%3D%22upper%20left%22)%0A%20%20%20%20_ax.spines%5B%5B%22top%22%2C%20%22right%22%5D%5D.set_visible(False)%0A%20%20%20%20_fig.tight_layout()%0A%20%20%20%20_ax%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20**Unusual%20is%20not%20wrong.**%20The%20detector%20did%20its%20job%3A%20large-scale%20units%20are%20rare%20in%20this%20survey%2C%20and%20different%20in%20every%20boat%20feature.%20They%20are%20not%20errors%3B%20stratum%20F%20took%20every%20registered%20large%20unit%20on%20purpose.%20Module%208%20met%20the%20same%20problem%20with%20IQR%20and%20robust%20z%20and%20answered%20it%20the%20same%20way%3A%20**compare%20like%20with%20like**.%20Here%20that%20means%20one%20detector%20per%20scale%2C%20each%20learning%20what%20its%20own%20units%20look%20like.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20One%20Isolation%20Forest%20per%20scale%3A%20each%20unit%20scored%20against%20its%20own%20scale%0A%20%20%20%20scale_scores%20%3D%20pd.Series(np.nan%2C%20index%3Dfeatures.index)%0A%20%20%20%20for%20_code%2C%20_rows%20in%20features.groupby(%22unit_scale%22)%3A%0A%20%20%20%20%20%20%20%20_model%20%3D%20IsolationForest(n_estimators%3D200%2C%20random_state%3D0).fit(_rows%5BFEATURES%5D)%0A%20%20%20%20%20%20%20%20scale_scores%5B_rows.index%5D%20%3D%20_model.score_samples(_rows%5BFEATURES%5D)%0A%20%20%20%20_top%20%3D%20features.loc%5Bscale_scores.nsmallest(40).index%5D%0A%20%20%20%20mo.md(f%22Scored%20within%20their%20scale%2C%20%7Bint((_top%5B'unit_scale'%5D%20%3D%3D%202).sum())%7D%20of%20the%2040%20most%20unusual%20units%20are%20large-scale%3A%20the%20large%20units%20no%20longer%20fill%20the%20list%20by%20being%20large.%20Section%203%20checks%20what%20the%2040%20are.%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Contamination%3A%20how%20many%20to%20flag%0A%0A%20%20%20%20A%20score%20ranks%20the%20rows%3B%20a%20**flag**%20needs%20a%20cut.%20%60contamination%60%20is%20the%20share%20of%20rows%20you%20expect%20to%20be%20anomalies%2C%20and%20the%20detector%20sets%20its%20cut%20at%20that%20share%20of%20its%20own%20scores%3A%20with%20%60contamination%3D0.05%60%2C%20the%205%25%20lowest%20scores%20are%20flagged.%20%60predict%60%20then%20returns%20**-1**%20for%20a%20flagged%20row%20and%20**1**%20for%20the%20rest%20(scikit-learn's%20convention).%0A%0A%20%20%20%20Contamination%20moves%20only%20the%20cut.%20The%20scores%20and%20their%20order%20stay%20the%20same%2C%20so%20the%202%25%20flagged%20are%20always%20among%20the%205%25%20flagged.%20Nobody%20knows%20the%20true%20share%20of%20anomalies%20in%20advance%3B%20what%20a%20survey%20team%20knows%20is%20how%20many%20units%20its%20supervisors%20can%20review.%20That%20budget%20is%20the%20honest%20way%20to%20choose%20it.%20This%20module%20takes%205%25%2C%20a%20review%20depth%20chosen%20for%20this%20survey%3A%205%25%20of%20its%202%2C335%20small-scale%20units%20is%20117%20to%20look%20at.%20Move%20the%20slider%20to%20see%20what%20another%20depth%20flags.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20contamination%20%3D%20mo.ui.slider(start%3D0.01%2C%20stop%3D0.10%2C%20step%3D0.01%2C%20value%3D0.05%2C%20label%3D%22contamination%22%2C%20show_value%3DTrue)%0A%20%20%20%20contamination%0A%20%20%20%20return%20(contamination%2C)%0A%0A%0A%40app.cell%0Adef%20_(contamination%2C%20features)%3A%0A%20%20%20%20%23%20The%20same%20forest%2C%20the%20cut%20at%20another%20share%3A%20the%20scores%20never%20change%2C%20only%20how%20many%20fall%20below%20the%20cut%0A%20%20%20%20_small%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%201%5D%0A%20%20%20%20_forest%20%3D%20IsolationForest(n_estimators%3D200%2C%20contamination%3Dcontamination.value%2C%20random_state%3D0).fit(_small%5BFEATURES%5D)%0A%20%20%20%20_flags%20%3D%20_forest.predict(_small%5BFEATURES%5D)%0A%20%20%20%20mo.md(f%22%60contamination%3D%7Bcontamination.value%3A.2f%7D%60%3A%20the%20cut%20is%20at%20a%20score%20of%20**%7B_forest.offset_%3A.4f%7D**%2C%20and%20**%7Bint((_flags%20%3D%3D%20-1).sum())%7D%20of%20%7Blen(_small)%3A%2C%7D**%20small-scale%20units%20are%20flagged%20(%60predict%60%20gives%20-1).%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Exercise%209.2.%20The%20rows%20an%20Isolation%20Forest%20flags%0A%0A%20%20%20%20**Why%20it%20matters%3A**%20the%20list%20a%20supervisor%20gets%20is%20ids%2C%20not%20scores.%20This%20is%20the%20function%20that%20turns%20a%20table%20of%20features%20into%20that%20list%2C%20and%20it%20must%20give%20the%20same%20list%20every%20time%20it%20runs%2C%20or%20nobody%20can%20check%20last%20week's%20review%20against%20this%20week's.%0A%0A%20%20%20%20**Input%20%E2%86%92%20output%3A**%20a%20matrix%20of%20features%20%60X%60%20(a%20table)%2C%20the%20ids%20of%20its%20rows%20%60ids%60%20(a%20Series%20in%20the%20same%20order)%2C%20and%20a%20%60contamination%60%20(a%20share%2C%20such%20as%20%600.05%60)%20%E2%86%92%20the%20ids%20of%20the%20rows%20flagged%2C%20**sorted**%2C%20as%20a%20list%3A%0A%0A%20%20%20%20%60%60%60python%0A%20%20%20%20isolation_flags(X%2C%20ids%2C%200.05)%20%20%20%23%20%5B'01-5023-1-2'%2C%20'01-5051-1-1'%2C%20...%5D%0A%20%20%20%20%60%60%60%0A%0A%20%20%20%20Use%20exactly%20%60IsolationForest(n_estimators%3D200%2C%20contamination%3Dcontamination%2C%20random_state%3D0)%60%3A%20the%20check%20compares%20your%20flags%20with%20the%20ones%20those%20settings%20give.%0A%0A%20%20%20%20**Tools%3A**%20%60IsolationForest%60%2C%20%60.fit(X)%60%2C%20%60.predict(X)%60%20(-1%20is%20flagged)%2C%20a%20boolean%20mask%20on%20%60ids%60%20(module%203)%2C%20%60sorted%60.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20isolation_flags(X%3A%20pd.DataFrame%2C%20ids%3A%20pd.Series%2C%20contamination%3A%20float)%20-%3E%20list%3A%0A%20%20%20%20%22%22%22The%20ids%20of%20the%20rows%20an%20Isolation%20Forest%20flags%20at%20this%20contamination%20(200%20trees%2C%20random_state%3D0)%2C%20sorted.%22%22%22%0A%20%20%20%20%23%20Exercise%209.2%3A%20the%20task%20and%20examples%20are%20in%20the%20text%20above%20this%20cell.%0A%20%20%20%20%23%20Step%201%3A%20an%20IsolationForest%20with%20n_estimators%3D200%2C%20the%20contamination%20given%2C%20and%20random_state%3D0%0A%20%20%20%20%23%20Step%202%3A%20fit%20it%20on%20X%20and%20predict%20X%3A%20-1%20marks%20a%20flagged%20row%0A%20%20%20%20%23%20Step%203%3A%20keep%20the%20ids%20where%20the%20prediction%20is%20-1%2C%20and%20return%20them%20sorted%2C%20as%20a%20list%0A%20%20%20%20raise%20NotImplementedError(%22Exercise%209.2%22)%0A%0A%0A%40app.function%0Adef%20cloud_fixture()%20-%3E%20tuple%5Bpd.DataFrame%2C%20pd.Series%5D%3A%0A%20%20%20%20%22%22%22Forty%20points%20around%20the%20middle%20and%20three%20far%20from%20it%20(p41%20to%20p43)%2C%20with%20their%20ids.%20Used%20by%20the%20check%20of%20Exercise%209.2.%22%22%22%0A%20%20%20%20rng%20%3D%20np.random.default_rng(11)%0A%20%20%20%20points%20%3D%20np.vstack(%5Brng.normal(0%2C%201%2C%20size%3D(40%2C%202))%2C%20%5B%5B6%2C%206%5D%2C%20%5B-7%2C%205%5D%2C%20%5B8%2C%20-6%5D%5D%5D).round(3)%0A%20%20%20%20return%20pd.DataFrame(points%2C%20columns%3D%5B%22x%22%2C%20%22y%22%5D)%2C%20pd.Series(%5Bf%22p%7Bi%3A02d%7D%22%20for%20i%20in%20range(1%2C%2044)%5D)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_(features)%3A%0A%20%20%20%20_cloud%2C%20_cloud_ids%20%3D%20cloud_fixture()%0A%20%20%20%20_small%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%201%5D%0A%20%20%20%20_large%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%202%5D%0A%20%20%20%20check_cases(%0A%20%20%20%20%20%20%20%20%22Exercise%209.2%22%2C%20isolation_flags%2C%0A%20%20%20%20%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22forty%20points%20and%20three%20far%20from%20them%2C%20contamination%200.05%22%2C%20(_cloud%2C%20_cloud_ids%2C%200.05))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20small-scale%20units%2C%20contamination%200.05%22%2C%20(_small%5BFEATURES%5D%2C%20_small%5B%22unit_id%22%5D%2C%200.05))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20large-scale%20units%2C%20contamination%200.1%22%2C%20(_large%5BFEATURES%5D%2C%20_large%5B%22unit_id%22%5D%2C%200.1))%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20what%3D%22tables%22%2C%20summarize%3Dlambda%20ids%3A%20sorted(map(str%2C%20ids))%2C%0A%20%20%20%20%20%20%20%20hint%3D%22IsolationForest(n_estimators%3D200%2C%20contamination%3D...%2C%20random_state%3D0)%3B%20predict%20gives%20-1%20for%20a%20flagged%20row%3B%20return%20those%20ids%20sorted.%22%2C%0A%20%20%20%20)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20Try%20it%3A%20the%20small-scale%20units%20your%20forest%20flags%20at%205%25%0A%20%20%20%20_small%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%201%5D%0A%20%20%20%20try_it(isolation_flags%2C%20_small%5BFEATURES%5D%2C%20_small%5B%22unit_id%22%5D%2C%200.05)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22If%20the%20check%20is%20red%3A%20common%20causes%20for%20Exercise%209.2%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%7C%20what%20you%20see%20%7C%20the%20usual%20cause%20%7C%20look%20at%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20Almost%20every%20id%20%7C%20%60%3D%3D%201%60%20keeps%20the%20rows%20the%20forest%20calls%20normal.%20%7C%20%60predict(X)%20%3D%3D%20-1%60%20%7C%0A%20%20%20%20%7C%20Right%20on%20the%20small%20table%2C%20wrong%20on%20the%20survey%2C%20and%20different%20each%20time%20you%20run%20it%20%7C%20%60random_state%60%20not%20set%3A%20each%20run%20grows%20other%20trees.%20%7C%20%60random_state%3D0%60%20%7C%0A%20%20%20%20%7C%20A%20few%20ids%20differ%2C%20the%20same%20each%20run%20%7C%20Another%20number%20of%20trees%20(the%20default%20is%20100).%20%7C%20%60n_estimators%3D200%60%20%7C%0A%20%20%20%20%7C%20*ValueError%3A%20The%20'contamination'%20parameter%20...%20must%20be%20...*%20%7C%20A%20percentage%2C%20%605%60%2C%20given%20where%20a%20share%2C%20%600.05%60%2C%20belongs.%20%7C%20the%20third%20argument%20%7C%0A%20%20%20%20%7C%20Positions%20such%20as%20%60%5B3%2C%2017%2C%20...%5D%60%2C%20not%20ids%20%7C%20%60np.flatnonzero%60%20or%20%60np.where%60%20returns%20positions.%20%7C%20%60ids%5Bmask%5D%60%20%7C%0A%0A%20%20%20%20Still%20stuck%20after%20ten%20minutes%3F%20Ask%20your%20table%2C%20then%20raise%20your%20hand.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Local%20Outlier%20Factor%3A%20density%20among%20neighbors%0A%0A%20%20%20%20LOF%20looks%20at%20each%20row's%20%60n_neighbors%60%20nearest%20rows%20(by%20distance%2C%20so%20on%20the%20scaled%20matrix)%20and%20asks%20how%20crowded%20the%20row's%20neighborhood%20is%20compared%20with%20its%20neighbors'%20own.%20A%20row%20in%20a%20sparse%20spot%20among%20neighbors%20who%20sit%20in%20crowded%20ones%20is%20unusual.%20%60negative_outlier_factor_%60%20holds%20the%20result%2C%20one%20per%20row%2C%20**lower**%20for%20more%20unusual%3B%20about%20-1%20is%20ordinary.%20LOF%20draws%20nothing%20at%20random%2C%20so%20it%20has%20no%20%60random_state%60%3A%20two%20runs%20give%20the%20same%20factors.%0A%0A%20%20%20%20**%60n_neighbors%60%20decides%20what%20counts%20as%20a%20crowd.**%20Module%208%20found%20one%20interviewer%20in%20region%2007%20whose%20interviews%20took%208%20to%2013%20minutes%2C%20each%20with%20the%20same%20boat%20and%20the%20same%20three%20species%3A%2030%20units%20that%20look%20alike%20in%20those%20columns.%20Asked%20about%20only%20a%20few%20neighbors%2C%20each%20of%20them%20finds%20others%20just%20like%20it%20and%20looks%20ordinary%3A%20the%20group%20hides%20itself.%20Asked%20about%20more%20neighbors%20than%20the%20group%20has%2C%20its%20neighborhood%20reaches%20the%20rest%20of%20the%20survey%2C%20and%20the%20group%20stands%20out%20more.%20scikit-learn's%20guide%20suggests%20about%2020%2C%20and%20more%20when%20anomalies%20are%20frequent%3A%20set%20%60n_neighbors%60%20above%20the%20size%20of%20the%20largest%20group%20of%20anomalies%20you%20expect%20to%20find%20together.%20On%20this%20survey%20the%20effect%20is%20real%20but%20modest%3A%20the%2030%20differ%20in%20their%20household%20size%2C%20crew%20and%20gears%2C%20so%20they%20are%20less%20alike%20than%2030%20copies%20would%20be.%20Move%20the%20slider%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20neighbors%20%3D%20mo.ui.slider(start%3D5%2C%20stop%3D60%2C%20step%3D5%2C%20value%3D20%2C%20label%3D%22n_neighbors%22%2C%20show_value%3DTrue)%0A%20%20%20%20neighbors%0A%20%20%20%20return%20(neighbors%2C)%0A%0A%0A%40app.cell%0Adef%20_(features%2C%20neighbors)%3A%0A%20%20%20%20%23%20LOF%20on%20the%20small-scale%20units%2C%20scaled%3A%20how%20many%20of%20the%20made-up%20interviews%20are%20among%20the%205%25%20most%20unusual%3F%0A%20%20%20%20_small%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%201%5D.reset_index(drop%3DTrue)%0A%20%20%20%20_factors%20%3D%20LocalOutlierFactor(n_neighbors%3Dneighbors.value).fit(neighbor_matrix(_small)).negative_outlier_factor_%0A%20%20%20%20_review%20%3D%20round(0.05%20*%20len(_small))%0A%20%20%20%20_top%20%3D%20_small.iloc%5Bnp.argsort(_factors%2C%20kind%3D%22stable%22)%5B%3A_review%5D%5D%0A%20%20%20%20_made_up%20%3D%20_small%5B%22unit_id%22%5D.isin(made_up_units())%0A%20%20%20%20mo.md(f%22%60n_neighbors%3D%7Bneighbors.value%7D%60%3A%20**%7Bint(_top%5B'unit_id'%5D.isin(made_up_units()).sum())%7D%20of%20the%20%7Bint(_made_up.sum())%7D**%20small-scale%20units%20from%20that%20interviewer's%20made-up%20interviews%20are%20among%20the%20%7B_review%7D%20most%20unusual.%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20made_up_units()%20-%3E%20set%3A%0A%20%20%20%20%22%22%22The%20unit_ids%20of%20the%20units%20in%20the%20interviews%20module%208's%20suspect%20interviewer%20made%20up%20(planted%20kind%20made_up_interview).%22%22%22%0A%20%20%20%20rows%20%3D%20planted%5Bplanted%5B%22kind%22%5D%20%3D%3D%20%22made_up_interview%22%5D%0A%20%20%20%20return%20set(unit_ids(rows))%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Exercise%209.3.%20The%20k%20most%20unusual%20rows%20by%20LOF%0A%0A%20%20%20%20**Why%20it%20matters%3A**%20a%20review%20team%20works%20through%20a%20fixed%20number%20of%20rows.%20Taking%20the%20k%20lowest%20factors%20gives%20exactly%20that%20many%2C%20which%20a%20contamination%20share%20only%20approximates.%20Getting%20the%20direction%20right%20is%20the%20exercise%3A%20LOF%2C%20like%20the%20Isolation%20Forest%2C%20scores%20the%20unusual%20**low**.%0A%0A%20%20%20%20**Input%20%E2%86%92%20output%3A**%20a%20scaled%20matrix%20%60X%60%2C%20its%20row%20ids%20%60ids%60%2C%20%60n_neighbors%60%20and%20%60k%60%20%E2%86%92%20the%20ids%20of%20the%20%60k%60%20rows%20with%20the%20**lowest**%20%60negative_outlier_factor_%60%2C%20sorted%2C%20as%20a%20list.%20When%20two%20factors%20tie%20at%20the%20cut%2C%20the%20row%20that%20comes%20first%20in%20%60X%60%20goes%20in.%0A%0A%20%20%20%20%7C%20id%20%7C%20negative_outlier_factor_%20%7C%20k%20%3D%202%20%7C%0A%20%20%20%20%7C%3A--%7C--%3A%7C%3A--%7C%0A%20%20%20%20%7C%20r1%20%7C%20-1.02%20%7C%20%7C%0A%20%20%20%20%7C%20r2%20%7C%20-6.81%20%7C%20in%20%7C%0A%20%20%20%20%7C%20r3%20%7C%20-1.98%20%7C%20in%20%7C%0A%20%20%20%20%7C%20r4%20%7C%20-1.10%20%7C%20%7C%0A%0A%20%20%20%20**Tools%3A**%20%60LocalOutlierFactor(n_neighbors%3D...)%60%2C%20%60.fit(X)%60%2C%20%60.negative_outlier_factor_%60%2C%20and%20%60np.argsort(...%2C%20kind%3D%22stable%22)%60%20or%20%60Series.nsmallest(k)%60.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20lof_top(X%3A%20pd.DataFrame%2C%20ids%3A%20pd.Series%2C%20n_neighbors%3A%20int%2C%20k%3A%20int)%20-%3E%20list%3A%0A%20%20%20%20%22%22%22The%20ids%20of%20the%20k%20rows%20with%20the%20lowest%20LOF%20factor%20(the%20most%20unusual)%2C%20sorted.%22%22%22%0A%20%20%20%20%23%20Exercise%209.3%3A%20the%20task%20and%20examples%20are%20in%20the%20text%20above%20this%20cell.%0A%20%20%20%20%23%20Step%201%3A%20fit%20LocalOutlierFactor(n_neighbors%3Dn_neighbors)%20on%20X%0A%20%20%20%20%23%20Step%202%3A%20the%20positions%20of%20the%20k%20lowest%20negative_outlier_factor_%20values%20(a%20stable%20sort%2C%20so%20a%20tie%20keeps%20X's%20order)%0A%20%20%20%20%23%20Step%203%3A%20return%20the%20ids%20at%20those%20positions%2C%20sorted%2C%20as%20a%20list%0A%20%20%20%20raise%20NotImplementedError(%22Exercise%209.3%22)%0A%0A%0A%40app.function%0Adef%20cluster_fixture()%20-%3E%20tuple%5Bpd.DataFrame%2C%20pd.Series%5D%3A%0A%20%20%20%20%22%22%22Twenty%20points%20spread%20around%20the%20middle%20(r01%20to%20r20)%2C%20five%20almost%20on%20top%20of%20one%20another%20far%20away%20(r21%20to%20r25)%2C%20and%0A%20%20%20%20one%20alone%20(r26)%2C%20with%20their%20ids.%20Used%20by%20the%20check%20of%20Exercise%209.3.%22%22%22%0A%20%20%20%20rng%20%3D%20np.random.default_rng(7)%0A%20%20%20%20spread%20%3D%20rng.normal(0%2C%202%2C%20size%3D(20%2C%202))%0A%20%20%20%20group%20%3D%20np.array(%5B12.0%2C%2012.0%5D)%20%2B%20rng.normal(0%2C%200.05%2C%20size%3D(5%2C%202))%0A%20%20%20%20points%20%3D%20np.vstack(%5Bspread%2C%20group%2C%20%5B%5B-9.0%2C%209.0%5D%5D%5D).round(3)%0A%20%20%20%20return%20pd.DataFrame(points%2C%20columns%3D%5B%22x%22%2C%20%22y%22%5D)%2C%20pd.Series(%5Bf%22r%7Bi%3A02d%7D%22%20for%20i%20in%20range(1%2C%2027)%5D)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_(features)%3A%0A%20%20%20%20_points%2C%20_point_ids%20%3D%20cluster_fixture()%0A%20%20%20%20_small%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%201%5D%0A%20%20%20%20check_cases(%0A%20%20%20%20%20%20%20%20%22Exercise%209.3%22%2C%20lof_top%2C%0A%20%20%20%20%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20(%2226%20points%2C%20a%20group%20of%20five%20close%20together%2C%203%20neighbors%2C%20k%20%3D%203%22%2C%20(_points%2C%20_point_ids%2C%203%2C%203))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20same%2026%20points%2C%206%20neighbors%2C%20k%20%3D%206%22%2C%20(_points%2C%20_point_ids%2C%206%2C%206))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20small-scale%20units%20scaled%2C%2035%20neighbors%2C%20k%20%3D%20117%22%2C%20(neighbor_matrix(_small)%2C%20_small%5B%22unit_id%22%5D%2C%2035%2C%20117))%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20what%3D%22sets%20of%20rows%22%2C%20summarize%3Dlambda%20ids%3A%20sorted(map(str%2C%20ids))%2C%0A%20%20%20%20%20%20%20%20hint%3D%22Fit%20LocalOutlierFactor(n_neighbors%3D...)%2C%20take%20the%20k%20LOWEST%20negative_outlier_factor_%20values%2C%20return%20their%20ids%20sorted.%22%2C%0A%20%20%20%20)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20Try%20it%3A%20the%20six%20most%20unusual%20of%20the%2026%20points%20with%206%20neighbors%3B%20r21%20to%20r25%20are%20the%20group%2C%20r26%20the%20lone%20point%0A%20%20%20%20_points%2C%20_point_ids%20%3D%20cluster_fixture()%0A%20%20%20%20try_it(lof_top%2C%20_points%2C%20_point_ids%2C%206%2C%206)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22If%20the%20check%20is%20red%3A%20common%20causes%20for%20Exercise%209.3%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%7C%20what%20you%20see%20%7C%20the%20usual%20cause%20%7C%20look%20at%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20Ordinary%20points%20such%20as%20r03%20and%20r07%2C%20not%20r26%20%7C%20The%20k%20highest%20factors%3A%20the%20most%20ordinary%20rows.%20%7C%20the%20k%20**lowest**%20%60negative_outlier_factor_%60%20%7C%0A%20%20%20%20%7C%20One%20id%20too%20many%20or%20too%20few%20%7C%20%60%5B%3Ak%2B1%5D%60%20or%20%60%5B1%3Ak%5D%60.%20%7C%20%60%5B%3Ak%5D%60%20%7C%0A%20%20%20%20%7C%20Right%20on%20the%20small%20table%2C%20a%20few%20ids%20off%20on%20the%20survey%20%7C%20%60fit_predict%60%20with%20a%20contamination%3A%20that%20flags%20a%20share%2C%20not%20k%20rows.%20%7C%20the%20k%20lowest%20factors%20%7C%0A%20%20%20%20%7C%20*AttributeError%3A%20...%20has%20no%20attribute%20'negative_outlier_factor_'*%20%7C%20The%20detector%20was%20not%20fitted%20first.%20%7C%20%60.fit(X)%60%20%7C%0A%0A%20%20%20%20Still%20stuck%20after%20ten%20minutes%3F%20Ask%20your%20table%2C%20then%20raise%20your%20hand.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20ECOD%3A%20the%20tails%20of%20each%20column%0A%0A%20%20%20%20PyOD's%20**ECOD**%20(empirical%20cumulative%20distribution%20outlier%20detection)%20reads%20each%20column%20on%20its%20own.%20For%20every%20value%20it%20asks%20how%20far%20into%20its%20column's%20tail%20the%20value%20sits%3A%20the%20share%20of%20units%20with%20a%20value%20at%20least%20as%20extreme%2C%20on%20either%20side.%20A%20value%20in%20the%20far%20tail%20gets%20a%20large%20number%3B%20the%20unit's%20score%20is%20the%20sum%20over%20its%20columns.%20ECOD%20has%20no%20setting%20to%20choose%20but%20%60contamination%60%2C%20draws%20nothing%20at%20random%2C%20and%20its%20per-column%20numbers%20say%20why%20a%20row%20scored%20high%20(section%203%20uses%20them).%0A%0A%20%20%20%20Its%20convention%20is%20the%20opposite%20of%20scikit-learn's%2C%20a%20trap%20for%20anyone%20using%20both%3A%0A%0A%20%20%20%20%7C%20detector%20%7C%20the%20score%20%7C%20more%20unusual%20is%20%7C%20a%20flag%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%60IsolationForest%60%20(scikit-learn)%20%7C%20%60score_samples(X)%60%20%7C%20**lower**%20%7C%20%60predict(X)%20%3D%3D%20-1%60%20%7C%0A%20%20%20%20%7C%20%60LocalOutlierFactor%60%20(scikit-learn)%20%7C%20%60negative_outlier_factor_%60%20%7C%20**lower**%20%7C%20%60fit_predict(X)%20%3D%3D%20-1%60%20%7C%0A%20%20%20%20%7C%20%60ECOD%60%20(PyOD)%20%7C%20%60decision_scores_%60%20%7C%20**higher**%20%7C%20%60labels_%20%3D%3D%201%60%20%7C%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20ECOD%20on%20the%20small-scale%20units%3A%20decision_scores_%20high%20is%20unusual%3B%20labels_%20is%201%20for%20the%20flagged%205%25%0A%20%20%20%20_small%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%201%5D.reset_index(drop%3DTrue)%0A%20%20%20%20_ecod%20%3D%20ECOD(contamination%3D0.05).fit(neighbor_matrix(_small)%5BFEATURES%5D)%20%20%23%20one%20scale%3A%20large_scale%20is%200%20in%20every%20row%0A%20%20%20%20_shown%20%3D%20_small%5B%5B%22unit_id%22%2C%20*FEATURES%5D%5D.assign(ecod_score%3D_ecod.decision_scores_%2C%20flagged%3D_ecod.labels_)%0A%20%20%20%20mo.vstack(%5B%0A%20%20%20%20%20%20%20%20mo.md(f%22**%7Bint(_ecod.labels_.sum())%7D%20of%20%7Blen(_small)%3A%2C%7D**%20small-scale%20units%20flagged%20(%60labels_%60%20%3D%201).%20The%20five%20highest%20scores%3A%22)%2C%0A%20%20%20%20%20%20%20%20_shown.nlargest(5%2C%20%22ecod_score%22).round(2)%2C%0A%20%20%20%20%5D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22The%20R%20way%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20The%20same%20methods%20exist%20in%20R%3A%20the%20isotree%20package's%20%60isolation.forest()%60%20and%20the%20dbscan%20package's%20%60lof()%60.%20Their%20settings%20have%20other%20names%20and%20their%20scores%20other%20directions%2C%20so%20read%20each%20one's%20help%20page%20for%20which%20end%20is%20unusual%20before%20you%20compare%20its%20flags%20with%20Python's.%20The%20steps%20around%20them%20are%20the%20same%20in%20both%20languages%3A%20one%20row%20per%20unit%2C%20the%20features%20chosen%2C%20codes%20encoded%2C%20columns%20scaled%2C%20and%20a%20fixed%20seed.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%203%20%C2%B7%20Judging%20detectors%20against%20known%20anomalies%20and%20rules%3B%20explaining%20a%20flag%0A%0A%20%20%20%20**The%20problem.**%20A%20detector%20always%20returns%20flags%2C%20wrong%20ones%20included.%20Whether%20its%20list%20is%20worth%20a%20supervisor's%20afternoon%20comes%20down%20to%20two%20numbers%3A%0A%0A%20%20%20%20-%20**precision**%3A%20of%20the%20units%20flagged%2C%20the%20share%20that%20are%20real%20anomalies.%20Low%20precision%20wastes%20the%20review.%0A%20%20%20%20-%20**recall**%3A%20of%20the%20real%20anomalies%2C%20the%20share%20flagged.%20Low%20recall%20leaves%20errors%20in%20the%20published%20tables.%0A%0A%20%20%20%20Both%20need%20the%20truth%2C%20which%20in%20this%20course%20is%20the%20list%20of%20planted%20defects.%20Not%20every%20planted%20defect%20can%20show%20in%20a%20unit's%20features%3A%20a%20sex%20code%20outside%20its%20list%20is%20in%20the%20member%20table%2C%20a%20weight%20was%20left%20out%20on%20purpose%2C%20and%20a%20unit%20entered%20twice%20was%20dropped%20in%20step%201.%20The%20judging%20uses%20the%20kinds%20that%20change%20at%20least%20one%20feature%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20shown_by_features()%20-%3E%20dict%3A%0A%20%20%20%20%22%22%22The%20planted%20kinds%20that%20change%20at%20least%20one%20of%20a%20unit's%20features%2C%20and%20which%20feature.%22%22%22%0A%20%20%20%20return%20%7B%0A%20%20%20%20%20%20%20%20%22age_out_of_range%22%3A%20%22age_of_operator%3A%20the%20head%2C%20who%20runs%20the%20household's%20first%20unit%2C%20is%20over%20110%22%2C%0A%20%20%20%20%20%20%20%20%22operator_too_young%22%3A%20%22age_of_operator%3A%20the%20operator%20is%20under%2010%22%2C%0A%20%20%20%20%20%20%20%20%22scale_contradicts_boats%22%3A%20%22largest_tonnage%3A%20a%20boat%20of%205.0%20gross%20tons%20or%20more%20in%20a%20small-scale%20unit%22%2C%0A%20%20%20%20%20%20%20%20%22no_engine_large_boat%22%3A%20%22largest_tonnage%3A%20an%20outrigger%20boat%20with%20no%20engine%2C%20of%205.0%20gross%20tons%20or%20more%22%2C%0A%20%20%20%20%20%20%20%20%22stored_tonnage_wrong%22%3A%20%22largest_tonnage%2C%20sum_tonnage%3A%20the%20stored%20tonnage%20is%20the%20dimensions%20multiplied%20without%20the%20factor%22%2C%0A%20%20%20%20%20%20%20%20%22feet_recorded_as_meters%22%3A%20%22largest_tonnage%2C%20longest_boat_m%3A%20feet%20recorded%20as%20meters%2C%20a%20small%20boat%20of%20many%20tons%22%2C%0A%20%20%20%20%20%20%20%20%22made_up_interview%22%3A%20%22hh_interview_minutes%2C%20age_of_operator%3A%208%20to%2013%20minutes%2C%20ages%20rounded%20to%20fives%2C%20the%20same%20boat%20and%20catch%22%2C%0A%20%20%20%20%20%20%20%20%22unit_without_catch%22%3A%20%22n_species%3A%20no%20catch%20rows%22%2C%0A%20%20%20%20%20%20%20%20%22catch_rows_all_astray%22%3A%20%22n_species%3A%20every%20catch%20row%20keyed%20to%20another%20unit%2C%20so%20none%20matched%22%2C%0A%20%20%20%20%7D%0A%0A%0A%40app.function%0Adef%20truth_units(features%3A%20pd.DataFrame)%20-%3E%20set%3A%0A%20%20%20%20%22%22%22The%20unit_ids%20of%20the%20units%20a%20planted%20defect%20of%20a%20kind%20in%20shown_by_features()%20changed.%20A%20defect%20recorded%20on%20a%20unit's%0A%20%20%20%20key%20names%20that%20unit%3B%20one%20recorded%20on%20a%20member%20names%20every%20unit%20of%20the%20household.%22%22%22%0A%20%20%20%20kinds%20%3D%20planted%5Bplanted%5B%22kind%22%5D.isin(shown_by_features())%5D%0A%20%20%20%20on_unit%20%3D%20kinds%5Bkinds%5B%22operator_line%22%5D.notna()%5D%0A%20%20%20%20on_household%20%3D%20kinds%5Bkinds%5B%22operator_line%22%5D.isna()%5D%0A%20%20%20%20named%20%3D%20set(unit_ids(on_unit))%0A%20%20%20%20in_household%20%3D%20set(features.merge(on_household%5BHOUSEHOLD%5D.drop_duplicates()%2C%20on%3DHOUSEHOLD)%5B%22unit_id%22%5D)%0A%20%20%20%20return%20(named%20%7C%20in_household)%20%26%20set(features%5B%22unit_id%22%5D)%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20The%20planted%20kinds%20a%20unit's%20features%20can%20show%2C%20and%20how%20many%20units%20each%20changed%0A%20%20%20%20truth%20%3D%20truth_units(features)%0A%20%20%20%20_rows%20%3D%20%5B%5D%0A%20%20%20%20for%20_name%2C%20_why%20in%20shown_by_features().items()%3A%0A%20%20%20%20%20%20%20%20_households%20%3D%20planted.loc%5Bplanted%5B%22kind%22%5D%20%3D%3D%20_name%2C%20HOUSEHOLD%5D.drop_duplicates()%0A%20%20%20%20%20%20%20%20_units%20%3D%20set(features.merge(_households%2C%20on%3DHOUSEHOLD)%5B%22unit_id%22%5D)%20%26%20truth%0A%20%20%20%20%20%20%20%20_rows.append(%7B%22kind%22%3A%20_name%2C%20%22units%22%3A%20len(_units)%2C%20%22what%20the%20features%20show%22%3A%20_why%7D)%0A%20%20%20%20mo.vstack(%5Bpd.DataFrame(_rows)%2C%20mo.md(f%22**%7Blen(truth)%7D%20units**%20carry%20a%20defect%20their%20features%20can%20show.%20They%20are%20the%20truth%20this%20section%20judges%20by.%22)%5D)%0A%20%20%20%20return%20(truth%2C)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Exercise%209.4.%20Precision%20and%20recall%20from%20two%20lists%20of%20ids%0A%0A%20%20%20%20**Why%20it%20matters%3A**%20every%20detector%2C%20rule%20and%20model%20in%20this%20module%20is%20judged%20with%20these%20two%20numbers%2C%20and%20so%20is%20any%20list%20a%20supervisor%20is%20handed.%20Computed%20from%20ids%20rather%20than%20from%20a%20library's%20arrays%2C%20they%20work%20on%20any%20two%20lists%3A%20this%20week's%20flags%20against%20last%20week's%20confirmed%20errors%2C%20a%20rule's%20failures%20against%20a%20reinterview.%0A%0A%20%20%20%20**Input%20%E2%86%92%20output%3A**%20%60flagged%60%20(a%20list%20of%20ids%3B%20a%20detector%20run%20twice%20may%20list%20an%20id%20twice)%20and%20%60truth%60%20(a%20set%20of%20ids)%20%E2%86%92%20a%20dictionary%3A%0A%0A%20%20%20%20%7C%20key%20%7C%20value%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%60%22flagged%22%60%20%7C%20how%20many%20**different**%20ids%20are%20flagged%20%7C%0A%20%20%20%20%7C%20%60%22found%22%60%20%7C%20how%20many%20of%20them%20are%20in%20%60truth%60%20%7C%0A%20%20%20%20%7C%20%60%22precision%22%60%20%7C%20found%20%2F%20flagged%3B%20%60None%60%20when%20nothing%20is%20flagged%20%7C%0A%20%20%20%20%7C%20%60%22recall%22%60%20%7C%20found%20%2F%20the%20size%20of%20%60truth%60%3B%20%60None%60%20when%20%60truth%60%20is%20empty%20%7C%0A%0A%20%20%20%20Flagged%20%60%5B%22a%22%2C%20%22b%22%2C%20%22b%22%2C%20%22c%22%5D%60%20against%20truth%20%60%7B%22b%22%2C%20%22c%22%2C%20%22d%22%2C%20%22e%22%7D%60%3A%203%20flagged%2C%202%20found%2C%20precision%202%2F3%2C%20recall%202%2F4.%20Don't%20round%3A%20the%20check%20compares%20to%20six%20decimals.%0A%0A%20%20%20%20**Tools%3A**%20%60set(...)%60%2C%20%60%26%60%20(the%20ids%20in%20both%20sets)%2C%20%60len%60%2C%20a%20conditional%20expression%20%60x%20if%20...%20else%20None%60%20(Python%20Essentials).%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20precision_recall(flagged%3A%20list%2C%20truth%3A%20set)%20-%3E%20dict%3A%0A%20%20%20%20%22%22%22flagged%20(distinct%20ids)%2C%20found%20(in%20truth)%2C%20precision%20(found%20%2F%20flagged)%20and%20recall%20(found%20%2F%20truth).%22%22%22%0A%20%20%20%20%23%20Exercise%209.4%3A%20the%20task%20and%20examples%20are%20in%20the%20text%20above%20this%20cell.%0A%20%20%20%20%23%20Step%201%3A%20the%20flagged%20ids%20as%20a%20set%20(an%20id%20listed%20twice%20counts%20once)%2C%20and%20the%20ones%20also%20in%20truth%0A%20%20%20%20%23%20Step%202%3A%20precision%20%3D%20found%20%2F%20flagged%2C%20or%20None%20when%20nothing%20is%20flagged%0A%20%20%20%20%23%20Step%203%3A%20recall%20%3D%20found%20%2F%20len(truth)%2C%20or%20None%20when%20truth%20is%20empty%0A%20%20%20%20%23%20Step%204%3A%20return%20the%20four%20numbers%20in%20a%20dictionary%20with%20the%20keys%20flagged%2C%20found%2C%20precision%2C%20recall%0A%20%20%20%20raise%20NotImplementedError(%22Exercise%209.4%22)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_(features%2C%20truth)%3A%0A%20%20%20%20_small%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%201%5D%0A%20%20%20%20_forest%20%3D%20IsolationForest(n_estimators%3D200%2C%20contamination%3D0.05%2C%20random_state%3D0).fit(_small%5BFEATURES%5D)%0A%20%20%20%20_forest_flags%20%3D%20_small.loc%5B_forest.predict(_small%5BFEATURES%5D)%20%3D%3D%20-1%2C%20%22unit_id%22%5D.tolist()%0A%20%20%20%20check_cases(%0A%20%20%20%20%20%20%20%20%22Exercise%209.4%22%2C%20precision_recall%2C%0A%20%20%20%20%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22flagged%20a%2C%20b%2C%20b%2C%20c%20against%20truth%20b%2C%20c%2C%20d%2C%20e%22%2C%20(%5B%22a%22%2C%20%22b%22%2C%20%22b%22%2C%20%22c%22%5D%2C%20%7B%22b%22%2C%20%22c%22%2C%20%22d%22%2C%20%22e%22%7D))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22nothing%20flagged%22%2C%20(%5B%5D%2C%20%7B%22b%22%2C%20%22c%22%7D))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22one%20id%20in%20two%20regions%3A%2001-5201-1-1%20flagged%2C%2007-5201-1-1%20the%20anomaly%22%2C%20(%5B%2201-5201-1-1%22%5D%2C%20%7B%2207-5201-1-1%22%7D))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20small-scale%20Isolation%20Forest's%20flags%20against%20the%20survey's%20truth%22%2C%20(_forest_flags%2C%20truth))%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20what%3D%22pairs%20of%20lists%22%2C%0A%20%20%20%20%20%20%20%20hint%3D%22Make%20flagged%20a%20set%3B%20found%20%3D%20how%20many%20are%20in%20truth%3B%20precision%20%3D%20found%20%2F%20flagged%20(None%20if%20none)%3B%20recall%20%3D%20found%20%2F%20truth.%22%2C%0A%20%20%20%20)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20Try%20it%3A%20three%20flagged%20(one%20listed%20twice)%2C%20two%20of%20them%20right%2C%20out%20of%20four%20to%20find%0A%20%20%20%20try_it(precision_recall%2C%20%5B%22a%22%2C%20%22b%22%2C%20%22b%22%2C%20%22c%22%5D%2C%20%7B%22b%22%2C%20%22c%22%2C%20%22d%22%2C%20%22e%22%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22If%20the%20check%20is%20red%3A%20common%20causes%20for%20Exercise%209.4%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%7C%20what%20you%20see%20%7C%20the%20usual%20cause%20%7C%20look%20at%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%60'flagged'%3A%204%60%20for%20the%20first%20case%20%7C%20The%20list's%20length%2C%20so%20the%20id%20listed%20twice%20counts%20twice.%20%7C%20%60set(flagged)%60%20%7C%0A%20%20%20%20%7C%20precision%20and%20recall%20swapped%20%7C%20The%20two%20denominators%20exchanged.%20%7C%20precision%20over%20flagged%2C%20recall%20over%20truth%20%7C%0A%20%20%20%20%7C%20*ZeroDivisionError%3A%20division%20by%20zero*%20%7C%20Nothing%20flagged%2C%20and%20precision%20divided%20by%200.%20%7C%20%60None%60%20when%20nothing%20is%20flagged%20%7C%0A%20%20%20%20%7C%20%60'precision'%3A%200.6667%60%20%7C%20Rounded%3A%20the%20check%20compares%20to%20six%20decimals.%20%7C%20return%20the%20fraction%20as%20it%20is%20%7C%0A%20%20%20%20%7C%20%60'found'%3A%201%60%20for%20the%20third%20case%20%7C%20The%20ids%20were%20cut%20to%20%60hh_id%60%20and%20the%20key%20parts%2C%20which%20repeat%20across%20regions.%20%7C%20compare%20the%20whole%20ids%20%7C%0A%0A%20%20%20%20Still%20stuck%20after%20ten%20minutes%3F%20Ask%20your%20table%2C%20then%20raise%20your%20hand.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20The%20detectors%20beside%20the%20rules%0A%0A%20%20%20%20Module%204%20and%20module%208%20wrote%20checks%20for%20most%20of%20these%20defects.%20The%20function%20below%20is%20a%20simpler%20rule%20set%20of%20its%20own%2C%20so%20this%20notebook%20runs%20on%20its%20own%3A%20it%20takes%20the%20rules%20that%20look%20at%20one%20unit%20from%20%60codebook_rules.csv%60%20(the%20operator's%20age%2C%20M2%20and%20M4%3B%20the%20scale%20against%20the%20largest%20boat%2C%20U3%3B%20a%20boat%20with%20no%20engine%20and%20its%20stored%20tonnage%2C%20B2%20and%20B3%3B%20no%20catch%2C%20C3)%20and%20adds%20three%20cruder%20versions%20of%20module%208's%20statistics%3A%20a%20boat%20far%20longer%20than%20others%20of%20its%20hull%20(a%20robust%20z%20within%20groups)%2C%20an%20interview%20under%2020%20minutes%2C%20and%20a%20weight%20over%20three%20times%20its%20stratum's%20median.%20Its%20thresholds%20are%20its%20own%2C%20not%20module%208's%3A%20the%20comparison%20asks%20whether%20the%20detectors%20find%20anything%20a%20plain%20rule%20misses%2C%20not%20which%20rule%20is%20best.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20rule_flags(features%3A%20pd.DataFrame)%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22One%20column%20per%20rule%2C%20True%20where%20the%20unit%20fails%20it%2C%20in%20the%20features'%20row%20order%3A%20modules%204%20and%208's%20checks%20on%20one%0A%20%20%20%20unit%2C%20written%20on%20the%20survey's%20tables.%22%22%22%0A%20%20%20%20measured%20%3D%20boats%5B%22boat_measured_in%22%5D%0A%20%20%20%20volume%20%3D%20boats%5B%22boat_length%22%5D%20*%20boats%5B%22boat_beam%22%5D%20*%20boats%5B%22boat_depth%22%5D%0A%20%20%20%20computed%20%3D%20np.select(%5Bmeasured%20%3D%3D%202%2C%20measured%20%3D%3D%203%5D%2C%20%5Bvolume%20*%200.212%2C%20volume%20*%200.006%5D%2C%20default%3Dboats%5B%22boat_tonnage_reported%22%5D)%0A%20%20%20%20length%20%3D%20pd.Series(np.select(%5Bmeasured%20%3D%3D%202%2C%20measured%20%3D%3D%203%5D%2C%20%5Bboats%5B%22boat_length%22%5D%2C%20boats%5B%22boat_length%22%5D%20%2F%203.281%5D%2C%20default%3Dnp.nan)%2C%20index%3Dboats.index)%0A%20%20%20%20median%20%3D%20length.groupby(boats%5B%22boat_hull%22%5D).transform(%22median%22)%0A%20%20%20%20mad%20%3D%20(length%20-%20median).abs().groupby(boats%5B%22boat_hull%22%5D).transform(%22median%22)%0A%20%20%20%20per_boat%20%3D%20boats%5BUNIT_KEY%5D.assign(%0A%20%20%20%20%20%20%20%20boat%3D((boats%5B%22boat_engine%22%5D%20%3D%3D%200)%20%26%20(boats%5B%22boat_tonnage%22%5D%20%3E%3D%205))%20%7C%20((boats%5B%22boat_tonnage%22%5D%20-%20computed).abs()%20%3E%200.01%20%2B%201e-9)%2C%20%20%23%20B2%2C%20B3%0A%20%20%20%20%20%20%20%20boat_length%3D((length%20-%20median).abs()%20%2F%20(1.4826%20*%20mad))%20%3E%203.5%2C%20%20%23%20module%208's%20robust%20z%2C%20within%20the%20boat's%20hull%0A%20%20%20%20)%0A%20%20%20%20per_unit%20%3D%20per_boat.groupby(UNIT_KEY%2C%20as_index%3DFalse)%5B%5B%22boat%22%2C%20%22boat_length%22%5D%5D.any()%0A%20%20%20%20joined%20%3D%20features%5BUNIT_KEY%5D.merge(per_unit%2C%20on%3DUNIT_KEY%2C%20how%3D%22left%22).fillna(%7B%22boat%22%3A%20False%2C%20%22boat_length%22%3A%20False%7D)%0A%20%20%20%20stratum_median%20%3D%20features.groupby(%5B%22region_code%22%2C%20%22sel_stratum%22%5D)%5B%22sel_final_weight%22%5D.transform(%22median%22)%0A%20%20%20%20return%20pd.DataFrame(%7B%0A%20%20%20%20%20%20%20%20%22operator%20age%22%3A%20(features%5B%22age_of_operator%22%5D%20%3C%2016)%20%7C%20(features%5B%22age_of_operator%22%5D%20%3E%20110)%2C%0A%20%20%20%20%20%20%20%20%22scale%22%3A%20((features%5B%22unit_scale%22%5D%20%3D%3D%201)%20%26%20(features%5B%22largest_tonnage%22%5D%20%3E%3D%205))%20%7C%20((features%5B%22unit_scale%22%5D%20%3D%3D%202)%20%26%20(features%5B%22largest_tonnage%22%5D%20%3C%205))%2C%0A%20%20%20%20%20%20%20%20%22boat%20engine%20or%20tonnage%22%3A%20joined%5B%22boat%22%5D.astype(bool).to_numpy()%2C%0A%20%20%20%20%20%20%20%20%22boat%20length%22%3A%20joined%5B%22boat_length%22%5D.astype(bool).to_numpy()%2C%0A%20%20%20%20%20%20%20%20%22no%20catch%22%3A%20features%5B%22n_species%22%5D%20%3D%3D%200%2C%0A%20%20%20%20%20%20%20%20%22short%20interview%22%3A%20features%5B%22hh_interview_minutes%22%5D%20%3C%2020%2C%0A%20%20%20%20%20%20%20%20%22weight%22%3A%20features%5B%22sel_final_weight%22%5D%20%3E%203%20*%20stratum_median%2C%0A%20%20%20%20%7D%2C%20index%3Dfeatures.index)%0A%0A%0A%40app.function%0Adef%20detector_flags(features%3A%20pd.DataFrame%2C%20contamination%3A%20float%20%3D%200.05)%20-%3E%20dict%3A%0A%20%20%20%20%22%22%22The%20unit_ids%20each%20detector%20flags%20when%20one%20is%20fitted%20per%20scale%20at%20this%20contamination%3A%20Isolation%20Forest%20(200%0A%20%20%20%20trees%2C%20random_state%3D0)%20on%20the%20features%2C%20LOF%20(35%20neighbors)%20and%20ECOD%20on%20the%20features%20scaled.%22%22%22%0A%20%20%20%20found%20%3D%20%7B%22Isolation%20Forest%22%3A%20set()%2C%20%22LOF%22%3A%20set()%2C%20%22ECOD%22%3A%20set()%7D%0A%20%20%20%20for%20_%2C%20rows%20in%20features.groupby(%22unit_scale%22)%3A%0A%20%20%20%20%20%20%20%20scaled%20%3D%20neighbor_matrix(rows)%0A%20%20%20%20%20%20%20%20forest%20%3D%20IsolationForest(n_estimators%3D200%2C%20contamination%3Dcontamination%2C%20random_state%3D0).fit(rows%5BFEATURES%5D)%0A%20%20%20%20%20%20%20%20found%5B%22Isolation%20Forest%22%5D%20%7C%3D%20set(rows.loc%5Bforest.predict(rows%5BFEATURES%5D)%20%3D%3D%20-1%2C%20%22unit_id%22%5D)%0A%20%20%20%20%20%20%20%20found%5B%22LOF%22%5D%20%7C%3D%20set(rows.loc%5BLocalOutlierFactor(n_neighbors%3D35%2C%20contamination%3Dcontamination).fit_predict(scaled)%20%3D%3D%20-1%2C%20%22unit_id%22%5D)%0A%20%20%20%20%20%20%20%20found%5B%22ECOD%22%5D%20%7C%3D%20set(rows.loc%5BECOD(contamination%3Dcontamination).fit(scaled%5BFEATURES%5D).labels_%20%3D%3D%201%2C%20%22unit_id%22%5D)%20%20%23%20large_scale%20is%20constant%20here%0A%20%20%20%20return%20found%0A%0A%0A%40app.cell%0Adef%20_(features%2C%20truth)%3A%0A%20%20%20%20%23%20Every%20planted%20kind%20the%20features%20show%3A%20how%20many%20units%20the%20rules%20and%20each%20detector%20(per%20scale%2C%205%25)%20flag%0A%20%20%20%20rules%20%3D%20rule_flags(features)%0A%20%20%20%20rule_units%20%3D%20set(features.loc%5Brules.any(axis%3D1)%2C%20%22unit_id%22%5D)%0A%20%20%20%20detected%20%3D%20detector_flags(features)%0A%20%20%20%20_lists%20%3D%20%7B%22rules%22%3A%20rule_units%2C%20**detected%7D%0A%20%20%20%20_rows%20%3D%20%5B%5D%0A%20%20%20%20for%20_name%20in%20shown_by_features()%3A%0A%20%20%20%20%20%20%20%20_households%20%3D%20planted.loc%5Bplanted%5B%22kind%22%5D%20%3D%3D%20_name%2C%20HOUSEHOLD%5D.drop_duplicates()%0A%20%20%20%20%20%20%20%20_units%20%3D%20set(features.merge(_households%2C%20on%3DHOUSEHOLD)%5B%22unit_id%22%5D)%20%26%20truth%0A%20%20%20%20%20%20%20%20_rows.append(%7B%22kind%22%3A%20_name%2C%20%22units%22%3A%20len(_units)%2C%20**%7B_who%3A%20len(_units%20%26%20_ids)%20for%20_who%2C%20_ids%20in%20_lists.items()%7D%7D)%0A%20%20%20%20_table%20%3D%20pd.DataFrame(_rows)%0A%20%20%20%20_summary%20%3D%20pd.DataFrame(%5B%0A%20%20%20%20%20%20%20%20%7B%22kind%22%3A%20%22flagged%22%2C%20%22units%22%3A%20None%2C%20**%7B_who%3A%20len(_ids)%20for%20_who%2C%20_ids%20in%20_lists.items()%7D%7D%2C%0A%20%20%20%20%20%20%20%20%7B%22kind%22%3A%20%22precision%22%2C%20%22units%22%3A%20None%2C%20**%7B_who%3A%20round(len(_ids%20%26%20truth)%20%2F%20len(_ids)%2C%202)%20for%20_who%2C%20_ids%20in%20_lists.items()%7D%7D%2C%0A%20%20%20%20%20%20%20%20%7B%22kind%22%3A%20%22recall%22%2C%20%22units%22%3A%20len(truth)%2C%20**%7B_who%3A%20round(len(_ids%20%26%20truth)%20%2F%20len(truth)%2C%202)%20for%20_who%2C%20_ids%20in%20_lists.items()%7D%7D%2C%0A%20%20%20%20%5D)%0A%20%20%20%20pd.concat(%5B_table%2C%20_summary%5D%2C%20ignore_index%3DTrue)%0A%20%20%20%20return%20detected%2C%20rule_units%0A%0A%0A%40app.cell%0Adef%20_(detected%2C%20rule_units%2C%20truth)%3A%0A%20%20%20%20%23%20What%20the%20detectors%20add%3A%20anomalies%20a%20detector%20flagged%20that%20no%20rule%20did%0A%20%20%20%20_any_detector%20%3D%20set().union(*detected.values())%0A%20%20%20%20_added%20%3D%20(_any_detector%20%26%20truth)%20-%20rule_units%0A%20%20%20%20_by_rules%20%3D%20len(rule_units%20%26%20truth)%0A%20%20%20%20_verdict%20%3D%20(f%22**On%20this%20survey%2C%20machine%20learning%20adds%20nothing.**%20The%20rules%20find%20%7B_by_rules%7D%20of%20the%20%7Blen(truth)%7D%20units%20with%20a%20defect%20their%20features%20show%3B%20%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20f%22every%20one%20a%20detector%20found%2C%20a%20rule%20had%20found%20too.%20The%20detectors%20also%20flag%20%7Blen(_any_detector%20-%20truth)%7D%20units%20with%20no%20such%20defect%2C%20which%20a%20supervisor%20would%20review%20for%20nothing.%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20not%20_added%20else%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20f%22**The%20detectors%20add%20%7Blen(_added)%7D%20units%20the%20rules%20missed**%20(%7B'%2C%20'.join(sorted(_added))%7D)%2C%20against%20%7Blen(_any_detector%20-%20truth)%7D%20units%20they%20flag%20with%20no%20such%20defect.%22)%0A%20%20%20%20mo.md(_verdict)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20That%20is%20the%20expected%20result%20whenever%20the%20rules%20were%20written%20by%20someone%20who%20knew%20the%20defects%2C%20as%20module%208's%20were.%20A%20detector%20earns%20its%20place%20in%20three%20situations%2C%20and%20the%20rest%20of%20this%20module%20shows%20the%20first%20two%3A%0A%0A%20%20%20%20-%20**Nobody%20wrote%20the%20rule.**%20A%20new%20kind%20of%20error%2C%20or%20a%20table%20nobody%20has%20rules%20for%20yet%20(section%205's%20large%20table%20has%20no%20boat%20rows%20to%20check).%0A%20%20%20%20-%20**The%20rule%20needs%20many%20columns%20at%20once.**%20A%20combination%20of%20answers%20that%20is%20rare%20though%20each%20answer%20is%20common%2C%20which%20no%20single-column%20check%20catches.%0A%20%20%20%20-%20**Ranking%20within%20what%20the%20rules%20pass.**%20When%20the%20rules%20leave%20thousands%20of%20rows%20and%20the%20review%20can%20take%20a%20hundred%2C%20a%20score%20orders%20them.%0A%0A%20%20%20%20Read%20the%20precision%20row%20before%20using%20a%20detector%20to%20replace%20a%20rule%3A%20at%205%25%2C%20most%20of%20what%20the%20detectors%20flag%20is%20ordinary.%0A%0A%20%20%20%20%23%23%23%20Explaining%20a%20flag%0A%0A%20%20%20%20A%20supervisor%20handed%20a%20unit%20needs%20to%20know%20**what**%20made%20it%20unusual%2C%20or%20they%20will%20check%20every%20answer.%20Two%20ways%20to%20say%20it%3A%0A%0A%20%20%20%20-%20**ECOD's%20own%20numbers.**%20ECOD's%20score%20is%20a%20sum%20over%20the%20columns%2C%20and%20the%20fitted%20detector%20keeps%20the%20parts%3A%20%60ecod.O%60%20holds%20one%20number%20per%20row%20and%20column%2C%20and%20the%20largest%20says%20which%20column's%20tail%20the%20row%20sits%20in.%20Nothing%20else%20is%20needed.%0A%20%20%20%20-%20**shap's%20%60TreeExplainer%60**%20on%20the%20Isolation%20Forest.%20shap%20splits%20a%20model's%20output%20for%20one%20row%20among%20its%20features.%20For%20an%20Isolation%20Forest%20the%20output%20is%20the%20row's%20average%20path%20length%2C%20so%20a%20feature%20with%20a%20**negative**%20value%20shortened%20the%20path%3A%20it%20made%20the%20row%20easier%20to%20isolate.%0A%0A%20%20%20%20The%20same%20unit%2C%20the%20small-scale%20units'%20highest%20ECOD%20score%2C%20both%20ways%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features)%3A%0A%20%20%20%20%23%20One%20flagged%20unit%20explained%20twice%3A%20ECOD's%20per-column%20numbers%20and%20shap's%20values%20on%20the%20Isolation%20Forest%0A%20%20%20%20_small%20%3D%20features%5Bfeatures%5B%22unit_scale%22%5D%20%3D%3D%201%5D.reset_index(drop%3DTrue)%0A%20%20%20%20_scaled%20%3D%20neighbor_matrix(_small)%5BFEATURES%5D%0A%20%20%20%20ecod_small%20%3D%20ECOD(contamination%3D0.05).fit(_scaled)%0A%20%20%20%20_row%20%3D%20int(np.argmax(ecod_small.decision_scores_))%0A%20%20%20%20_ecod_parts%20%3D%20pd.Series(ecod_small.O%5B_row%5D%2C%20index%3DFEATURES)%0A%20%20%20%20_forest%20%3D%20IsolationForest(n_estimators%3D200%2C%20random_state%3D0).fit(_small%5BFEATURES%5D)%0A%20%20%20%20_shap_parts%20%3D%20pd.Series(shap.TreeExplainer(_forest).shap_values(_small%5BFEATURES%5D.iloc%5B%5B_row%5D%5D)%5B0%5D%2C%20index%3DFEATURES)%0A%20%20%20%20_fig%2C%20(_left%2C%20_right)%20%3D%20plt.subplots(1%2C%202%2C%20figsize%3D(9%2C%203.6)%2C%20sharey%3DTrue)%0A%20%20%20%20_left.barh(FEATURES%2C%20_ecod_parts%5BFEATURES%5D%2C%20color%3DORANGE)%0A%20%20%20%20_left.set_xlabel(%22ECOD%3A%20tail%20score%20of%20the%20column%20(higher%20is%20more%20unusual)%22)%0A%20%20%20%20_right.barh(FEATURES%2C%20_shap_parts%5BFEATURES%5D%2C%20color%3DBLUE)%0A%20%20%20%20_right.axvline(0%2C%20color%3DGREY%2C%20linewidth%3D0.8)%0A%20%20%20%20_right.set_xlabel(%22shap%20on%20the%20Isolation%20Forest%3A%20path%20length%20(negative%20is%20more%20unusual)%22)%0A%20%20%20%20for%20_ax%20in%20(_left%2C%20_right)%3A%0A%20%20%20%20%20%20%20%20_ax.spines%5B%5B%22top%22%2C%20%22right%22%5D%5D.set_visible(False)%0A%20%20%20%20_left.invert_yaxis()%0A%20%20%20%20_fig.suptitle(f%22Why%20unit%20%7B_small.loc%5B_row%2C%20'unit_id'%5D%7D%20was%20flagged%22)%0A%20%20%20%20_fig.tight_layout()%0A%20%20%20%20mo.vstack(%5B%0A%20%20%20%20%20%20%20%20_fig%2C%0A%20%20%20%20%20%20%20%20mo.md(f%22ECOD's%20largest%20part%20is%20**%7B_ecod_parts.idxmax()%7D**%3B%20shap's%20most%20negative%20value%20is%20**%7B_shap_parts.idxmin()%7D**.%20The%20unit's%20answers%3A%22)%2C%0A%20%20%20%20%20%20%20%20_small.loc%5B%5B_row%5D%2C%20%5B%22unit_id%22%2C%20*FEATURES%5D%5D%2C%0A%20%20%20%20%5D)%0A%20%20%20%20return%20(ecod_small%2C)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20The%20two%20methods%20need%20not%20agree%3A%20ECOD%20reads%20each%20column%20alone%2C%20the%20forest%20cuts%20on%20combinations.%20When%20they%20name%20the%20same%20column%2C%20the%20supervisor%20starts%20there.%0A%0A%20%20%20%20%23%23%23%20Exercise%209.5.%20The%20reasons%20for%20each%20flag%2C%20in%20words%0A%0A%20%20%20%20**Why%20it%20matters%3A**%20a%20review%20table%20with%20a%20column%20%22look%20at%3A%20largest_tonnage%2C%20sum_tonnage%22%20saves%20the%20supervisor%20from%20reading%20every%20answer%20of%20every%20flagged%20unit.%20One%20line%20per%20flag%2C%20from%20any%20table%20of%20per-feature%20contributions.%0A%0A%20%20%20%20**Input%20%E2%86%92%20output%3A**%20a%20table%20of%20contributions%20(one%20row%20per%20unit%2C%20one%20column%20per%20feature%2C%20**higher%20meaning%20more%20unusual**%2C%20as%20ECOD's%20%60O%60)%20and%20%60k%60%20%E2%86%92%20a%20Series%20with%2C%20for%20each%20row%2C%20the%20names%20of%20its%20%60k%60%20columns%20with%20the%20largest%20contributions%2C%20largest%20first%2C%20joined%20by%20%60%22%2C%20%22%60.%20When%20two%20contributions%20are%20equal%2C%20the%20column%20further%20left%20comes%20first.%0A%0A%20%20%20%20%7C%20%7C%20n_boats%20%7C%20largest_tonnage%20%7C%20n_species%20%7C%20k%20%3D%202%20%7C%0A%20%20%20%20%7C%3A--%7C--%3A%7C--%3A%7C--%3A%7C%3A--%7C%0A%20%20%20%20%7C%20row%200%20%7C%200.1%20%7C%204.2%20%7C%201.3%20%7C%20%60%22largest_tonnage%2C%20n_species%22%60%20%7C%0A%20%20%20%20%7C%20row%201%20%7C%202.0%20%7C%200.5%20%7C%202.0%20%7C%20%60%22n_boats%2C%20n_species%22%60%20%7C%0A%0A%20%20%20%20**Tools%3A**%20%60table.apply(...%2C%20axis%3D1)%60%20(one%20call%20per%20row)%2C%20%60Series.sort_values(ascending%3DFalse%2C%20kind%3D%22stable%22)%60%2C%20%60.index%5B%3Ak%5D%60%2C%20%60%22%2C%20%22.join(...)%60.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20top_reasons(contributions%3A%20pd.DataFrame%2C%20k%3A%20int)%20-%3E%20pd.Series%3A%0A%20%20%20%20%22%22%22For%20each%20row%2C%20its%20k%20columns%20with%20the%20largest%20contributions%2C%20largest%20first%2C%20joined%20by%20%22%2C%20%22%20(ties%3A%20the%20left%20one%20first).%22%22%22%0A%20%20%20%20%23%20Exercise%209.5%3A%20the%20task%20and%20examples%20are%20in%20the%20text%20above%20this%20cell.%0A%20%20%20%20%23%20Step%201%3A%20write%20a%20function%20for%20one%20row%3A%20sort%20its%20values%20from%20the%20largest%2C%20keeping%20the%20column%20order%20among%20ties%0A%20%20%20%20%23%20Step%202%3A%20take%20the%20first%20k%20column%20names%20and%20join%20them%20with%20%22%2C%20%22%0A%20%20%20%20%23%20Step%203%3A%20apply%20it%20to%20every%20row%20(axis%3D1)%20and%20return%20the%20Series%0A%20%20%20%20raise%20NotImplementedError(%22Exercise%209.5%22)%0A%0A%0A%40app.function%0Adef%20reasons_fixture()%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22Three%20units'%20contributions%2C%20with%20ties%20in%20the%20second%20row.%20Used%20by%20the%20check%20of%20Exercise%209.5.%22%22%22%0A%20%20%20%20return%20pd.DataFrame(%7B%22n_boats%22%3A%20%5B0.1%2C%202.0%2C%200.3%5D%2C%20%22largest_tonnage%22%3A%20%5B4.2%2C%200.5%2C%200.3%5D%2C%20%22n_species%22%3A%20%5B1.3%2C%202.0%2C%200.3%5D%2C%20%22age_of_operator%22%3A%20%5B0.0%2C%201.9%2C%205.0%5D%7D)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_(ecod_small)%3A%0A%20%20%20%20_parts%20%3D%20pd.DataFrame(ecod_small.O%2C%20columns%3DFEATURES)%0A%20%20%20%20_flagged%20%3D%20_parts%5Becod_small.labels_%20%3D%3D%201%5D%0A%20%20%20%20check_cases(%0A%20%20%20%20%20%20%20%20%22Exercise%209.5%22%2C%20top_reasons%2C%0A%20%20%20%20%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22three%20rows%20with%20ties%2C%20k%20%3D%202%22%2C%20(reasons_fixture()%2C%202))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20same%20three%20rows%2C%20k%20%3D%201%22%2C%20(reasons_fixture()%2C%201))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22ECOD's%20parts%20for%20the%20small-scale%20units%20it%20flags%2C%20k%20%3D%203%22%2C%20(_flagged%2C%203))%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20what%3D%22tables%22%2C%20summarize%3Dlambda%20reasons%3A%20%5Bstr(r)%20for%20r%20in%20reasons%5D%2C%0A%20%20%20%20%20%20%20%20hint%3D%22For%20each%20row%3A%20sort_values(ascending%3DFalse%2C%20kind%3D'stable')%2C%20take%20the%20first%20k%20column%20names%2C%20join%20them%20with%20'%2C%20'.%22%2C%0A%20%20%20%20)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20Try%20it%3A%20the%20two%20largest%20contributions%20of%20each%20of%20the%20three%20rows%0A%20%20%20%20try_it(top_reasons%2C%20reasons_fixture()%2C%202)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22If%20the%20check%20is%20red%3A%20common%20causes%20for%20Exercise%209.5%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%7C%20what%20you%20see%20%7C%20the%20usual%20cause%20%7C%20look%20at%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%60%22age_of_operator%2C%20n_boats%22%60%20for%20row%200%20%7C%20The%20smallest%20contributions%3A%20%60sort_values()%60%20sorts%20up%20by%20default.%20%7C%20%60ascending%3DFalse%60%20%7C%0A%20%20%20%20%7C%20%60%22n_species%2C%20n_boats%22%60%20for%20row%201%20%7C%20A%20sort%20that%20is%20not%20stable%20put%20the%20tied%20columns%20the%20other%20way%20round.%20%7C%20%60kind%3D%22stable%22%60%20%7C%0A%20%20%20%20%7C%20The%20numbers%2C%20not%20the%20column%20names%20%7C%20%60.values%5B%3Ak%5D%60%20instead%20of%20%60.index%5B%3Ak%5D%60.%20%7C%20%60.index%5B%3Ak%5D%60%20%7C%0A%20%20%20%20%7C%20One%20long%20text%20for%20the%20whole%20table%20%7C%20%60axis%3D1%60%20missing%2C%20so%20apply%20ran%20on%20columns.%20%7C%20%60apply(...%2C%20axis%3D1)%60%20%7C%0A%0A%20%20%20%20Still%20stuck%20after%20ten%20minutes%3F%20Ask%20your%20table%2C%20then%20raise%20your%20hand.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%204%20%C2%B7%20When%20you%20have%20labels%3A%20a%20random%20forest%20on%20last%20round's%20edits%0A%0A%20%20%20%20**The%20problem.**%20The%20detectors%20above%20learn%20only%20what%20is%20common.%20A%20survey%20team%20has%20more%20than%20that%3A%20in%20the%20survey's%202021%20round%2C%20editors%20went%20through%20the%20units%20and%20changed%20the%20ones%20they%20found%20wrong%2C%20and%20the%20edit%20log%20says%20which%20and%20why.%20Those%20decisions%20are%20**labels**%3A%20a%20known%20answer%2C%20%22edited%22%20or%20not%2C%20for%20each%20unit.%20A%20model%20that%20learns%20from%20labels%20is%20**supervised**%2C%20and%20it%20learns%20what%20the%20editors%20corrected%2C%20not%20what%20is%20rare.%0A%0A%20%20%20%20%60units_2021_edit_decisions.parquet%60%20holds%20the%202021%20round's%209%2C000%20units%20with%20the%20same%20features%20as%20section%205's%20large%20table%2C%20%60was_edited%60%20(1%20or%200)%20and%20%60edit_kind%60%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20The%202021%20round%3A%20features%2C%20and%20what%20its%20editors%20decided%0A%20%20%20%20past%20%3D%20pd.read_parquet(PATHS.edits_2021)%0A%20%20%20%20past%5B%22unit_id%22%5D%20%3D%20unit_ids(past)%0A%20%20%20%20_kinds%20%3D%20past%5B%22edit_kind%22%5D.replace(%22%22%2C%20%22(not%20edited)%22).value_counts().rename(%22units%22)%0A%20%20%20%20mo.hstack(%5B_kinds%2C%20mo.md(f%22**%7Bint(past%5B'was_edited'%5D.sum())%7D%20of%20%7Blen(past)%3A%2C%7D%20units%20were%20edited**%2C%20%7Bpast%5B'was_edited'%5D.mean()%3A.1%25%7D.%20Three%20kinds%3A%20a%20boat's%20dimensions%20recorded%20in%20the%20wrong%20unit%20(%60wrong_unit_of_measure%60)%2C%20a%20scale%20that%20contradicts%20the%20boats%20(%60scale_class_wrong%60)%2C%20and%20a%20weight%20inflated%20in%20the%20weighting%20(%60weight_inflated%60).%22)%5D%2C%20justify%3D%22start%22%2C%20gap%3D2)%0A%20%20%20%20return%20(past%2C)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20The%20workflow%20of%20a%20supervised%20model%0A%0A%20%20%20%20If%20you%20took%20the%20geospatial%20machine%20learning%20training%2C%20this%20is%20the%20same%20workflow%20on%20another%20table.%20There%2C%20each%20pixel%20had%20band%20values%20and%20a%20land-cover%20class%20someone%20had%20marked%3B%20here%2C%20each%20unit%20has%20its%20answers%20and%20the%20editors'%20decision.%0A%0A%20%20%20%20%7C%20step%20%7C%20land%20cover%20from%20imagery%20%7C%20edits%20in%20a%20survey%20round%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20**features**%20%7C%20the%20pixel's%20bands%20and%20indices%20%7C%20the%20unit's%20twelve%20features%20and%20%60large_scale%60%20(%60tree_matrix%60)%20%7C%0A%20%20%20%20%7C%20**labels**%20%7C%20the%20marked%20land-cover%20class%20%7C%20%60was_edited%60%3A%201%20or%200%20%7C%0A%20%20%20%20%7C%20**split**%20%7C%20training%20pixels%20and%20test%20pixels%20%7C%20training%20units%20and%20**held-out**%20units%2C%20%60train_test_split%60%20%7C%0A%20%20%20%20%7C%20**fit**%20%7C%20%60RandomForestClassifier().fit(X_train%2C%20y_train)%60%20%7C%20the%20same%20%7C%0A%20%20%20%20%7C%20**predict**%20%7C%20a%20class%20for%20every%20pixel%20of%20a%20new%20scene%20%7C%20edited%20or%20not%2C%20for%20every%20unit%20of%20a%20new%20round%20%7C%0A%20%20%20%20%7C%20**evaluate**%20%7C%20accuracy%20and%20a%20confusion%20matrix%20on%20the%20test%20pixels%20%7C%20precision%20and%20recall%20on%20the%20held-out%20units%20%7C%0A%0A%20%20%20%20A%20**random%20forest**%20grows%20many%20decision%20trees%2C%20each%20on%20a%20random%20draw%20of%20the%20training%20rows%2C%20and%20lets%20them%20vote.%20%60random_state%60%20fixes%20the%20draws%2C%20as%20it%20does%20for%20the%20Isolation%20Forest.%0A%0A%20%20%20%20**Accuracy%20misleads%20when%20one%20answer%20is%20rare.**%20With%201.7%25%20of%20units%20edited%2C%20a%20model%20that%20answers%20%22not%20edited%22%20for%20every%20unit%20is%2098.3%25%20accurate%20and%20finds%20nothing.%20Precision%20and%20recall%20on%20the%20edited%20class%20say%20what%20accuracy%20hides.%0A%0A%20%20%20%20**A%20model%20graded%20on%20its%20own%20homework.**%20Fit%20on%20every%20row%20and%20judged%20on%20the%20same%20rows%2C%20a%20forest%20remembers%20the%20answers%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(past)%3A%0A%20%20%20%20%23%20Fitted%20and%20judged%20on%20the%20same%20rows%3A%20the%20figures%20look%20perfect%20and%20mean%20nothing%0A%20%20%20%20_forest%20%3D%20RandomForestClassifier(n_estimators%3D200%2C%20random_state%3D0).fit(tree_matrix(past)%2C%20past%5B%22was_edited%22%5D)%0A%20%20%20%20_said%20%3D%20_forest.predict(tree_matrix(past))%0A%20%20%20%20mo.md(f%22On%20its%20own%20training%20rows%3A%20precision%20**%7Bprecision_score(past%5B'was_edited'%5D%2C%20_said)%3A.2f%7D**%2C%20recall%20**%7Brecall_score(past%5B'was_edited'%5D%2C%20_said)%3A.2f%7D**.%20%22%0A%20%20%20%20%20%20%20%20%20%20f%22A%20model%20that%20answers%20%5C%22not%20edited%5C%22%20every%20time%20would%20be%20%7B1%20-%20past%5B'was_edited'%5D.mean()%3A.1%25%7D%20accurate.%20Neither%20figure%20says%20how%20the%20model%20does%20on%20a%20round%20it%20has%20not%20seen.%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20**Held-out%20rows%20answer%20that.**%20%60train_test_split(X%2C%20y%2C%20test_size%3D0.3%2C%20stratify%3Dy%2C%20random_state%3D0)%60%20keeps%2030%25%20of%20the%20units%20aside%3B%20the%20forest%20never%20sees%20them%20while%20it%20learns%2C%20and%20its%20predictions%20for%20them%20are%20the%20honest%20figures.%20%60stratify%3Dy%60%20keeps%20the%20share%20of%20edited%20units%20the%20same%20in%20both%20parts%2C%20which%20matters%20when%20there%20are%20only%20115%20of%20them%20to%20split%3A%20without%20it%2C%20how%20many%20edits%20land%20in%20the%20held-out%20part%20is%20left%20to%20chance.%0A%0A%20%20%20%20**A%20label%20the%20features%20cannot%20show%20is%20noise.**%20Thirty-five%20units%20were%20edited%20for%20a%20weight%20inflated%20in%20the%20weighting.%20Their%20answers%20are%20ordinary%2C%20and%20the%20weight%20is%20not%20a%20feature%20(section%201).%20Labeled%201%2C%20they%20teach%20the%20forest%20that%20ordinary%20units%20are%20sometimes%20edited%2C%20and%20it%20learns%20to%20flag%20a%20few%20ordinary%20ones%3B%20labeled%200%2C%20they%20would%20say%20those%20units%20were%20right.%20They%20stay%20out%20of%20the%20training%20rows.%20Their%20kind%20of%20error%20is%20the%20weight%20rule's.%0A%0A%20%20%20%20%23%23%23%20Exercise%209.6.%20Held-out%20precision%20and%20recall%0A%0A%20%20%20%20**Why%20it%20matters%3A**%20these%20two%20figures%20are%20what%20a%20supervisor%20hears%20before%20trusting%20a%20model%20with%20next%20round's%20review.%20Computed%20on%20the%20training%20rows%2C%20they%20would%20promise%20everything.%0A%0A%20%20%20%20**Input%20%E2%86%92%20output%3A**%20the%202021%20round's%20table%20and%20a%20%60seed%60%20%E2%86%92%20a%20dictionary%20%60%7B%22precision%22%3A%20...%2C%20%22recall%22%3A%20...%7D%60%20for%20the%20**held-out**%20units%2C%20unrounded.%20Exactly%3A%0A%0A%20%20%20%201.%20leave%20out%20the%20units%20whose%20%60edit_kind%60%20is%20%60%22weight_inflated%22%60%3B%0A%20%20%20%202.%20%60X%20%3D%20tree_matrix(rows)%60%2C%20%60y%20%3D%20rows%5B%22was_edited%22%5D%60%3B%0A%20%20%20%203.%20%60train_test_split(X%2C%20y%2C%20test_size%3D0.3%2C%20stratify%3Dy%2C%20random_state%3Dseed)%60%3B%0A%20%20%20%204.%20%60RandomForestClassifier(n_estimators%3D200%2C%20random_state%3Dseed)%60%2C%20fitted%20on%20the%20training%20part%3B%0A%20%20%20%205.%20%60precision_score%60%20and%20%60recall_score%60%20of%20its%20%60predict%60%20on%20the%20held-out%20part.%0A%0A%20%20%20%20**Tools%3A**%20a%20boolean%20filter%20(module%203)%2C%20and%20the%20scikit-learn%20functions%20above%2C%20all%20imported%20in%20the%20setup%20cell.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20held_out_scores(past%3A%20pd.DataFrame%2C%20seed%3A%20int)%20-%3E%20dict%3A%0A%20%20%20%20%22%22%22The%20forest's%20precision%20and%20recall%20on%20the%20held-out%2030%25%20of%20the%202021%20round%2C%20the%20weight%20edits%20left%20out.%22%22%22%0A%20%20%20%20%23%20Exercise%209.6%3A%20the%20task%20and%20examples%20are%20in%20the%20text%20above%20this%20cell.%0A%20%20%20%20%23%20Step%201%3A%20the%20training%20rows%3A%20leave%20out%20edit_kind%20%3D%3D%20%22weight_inflated%22%0A%20%20%20%20%23%20Step%202%3A%20X%20%3D%20tree_matrix(rows)%2C%20y%20%3D%20rows%5B%22was_edited%22%5D%3B%20split%2030%25%20off%2C%20stratify%3Dy%2C%20random_state%3Dseed%0A%20%20%20%20%23%20Step%203%3A%20fit%20RandomForestClassifier(n_estimators%3D200%2C%20random_state%3Dseed)%20on%20the%20training%20part%0A%20%20%20%20%23%20Step%204%3A%20predict%20the%20held-out%20part%2C%20and%20return%20its%20precision%20and%20recall%20in%20a%20dictionary%0A%20%20%20%20raise%20NotImplementedError(%22Exercise%209.6%22)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_(past)%3A%0A%20%20%20%20check_cases(%0A%20%20%20%20%20%20%20%20%22Exercise%209.6%22%2C%20held_out_scores%2C%0A%20%20%20%20%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%202021%20round%2C%20seed%200%22%2C%20(past%2C%200))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%202021%20round%2C%20seed%201%22%2C%20(past%2C%201))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%202021%20round's%20first%204%2C500%20units%2C%20seed%200%22%2C%20(past.head(4500)%2C%200))%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20what%3D%22rounds%20and%20seeds%22%2C%20summarize%3Dlambda%20scores%3A%20%7Bk%3A%20round(float(v)%2C%204)%20for%20k%2C%20v%20in%20scores.items()%7D%2C%0A%20%20%20%20%20%20%20%20hint%3D%22Leave%20out%20the%20weight_inflated%20rows%3B%20split%2030%25%20with%20stratify%3Dy%20and%20random_state%3Dseed%3B%20fit%20200%20trees%20with%20random_state%3Dseed%3B%20score%20the%20held-out%20part.%22%2C%0A%20%20%20%20)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(past)%3A%0A%20%20%20%20%23%20Try%20it%3A%20your%20forest's%20held-out%20figures%20for%20seed%200%0A%20%20%20%20try_it(held_out_scores%2C%20past%2C%200)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22If%20the%20check%20is%20red%3A%20common%20causes%20for%20Exercise%209.6%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%7C%20what%20you%20see%20%7C%20the%20usual%20cause%20%7C%20look%20at%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20%601.0%60%20and%20%601.0%60%20%7C%20Judged%20on%20the%20training%20rows.%20%7C%20%60predict(X_test)%60%20against%20%60y_test%60%20%7C%0A%20%20%20%20%7C%20A%20lower%20recall%20than%20expected%20%7C%20The%20weight%20edits%20are%20still%20in%20the%20training%20rows.%20%7C%20%60edit_kind%20!%3D%20%22weight_inflated%22%60%20%7C%0A%20%20%20%20%7C%20Figures%20that%20change%20each%20run%20%7C%20A%20%60random_state%60%20missing%20from%20the%20split%20or%20the%20forest.%20%7C%20%60random_state%3Dseed%60%20in%20both%20%7C%0A%20%20%20%20%7C%20Close%2C%20but%20not%20equal%20%7C%20%60stratify%3D%60%20missing%2C%20or%20another%20%60test_size%60%20or%20number%20of%20trees.%20%7C%20%60test_size%3D0.3%2C%20stratify%3Dy%60%2C%20%60n_estimators%3D200%60%20%7C%0A%20%20%20%20%7C%20*ValueError%3A%20Classification%20metrics%20can't%20handle%20a%20mix%20of%20...*%20%7C%20The%20arguments%20to%20%60precision_score%60%20reversed%2C%20or%20the%20probabilities%20passed.%20%7C%20%60precision_score(y_test%2C%20said)%60%20%7C%0A%0A%20%20%20%20Still%20stuck%20after%20ten%20minutes%3F%20Ask%20your%20table%2C%20then%20raise%20your%20hand.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(past)%3A%0A%20%20%20%20%23%20The%20held-out%20figures%20beside%20the%20detectors'%20(they%20need%20Exercise%209.6)%0A%20%20%20%20_scores%20%3D%20attempt(held_out_scores%2C%20past%2C%200)%0A%20%20%20%20mo.stop(_scores%20is%20NOT_YET%2C%20waiting_for(%22Exercise%209.6%22))%0A%20%20%20%20_rows%20%3D%20past%5Bpast%5B%22edit_kind%22%5D%20!%3D%20%22weight_inflated%22%5D%0A%20%20%20%20_held%20%3D%20int(train_test_split(_rows%5B%22was_edited%22%5D%2C%20test_size%3D0.3%2C%20stratify%3D_rows%5B%22was_edited%22%5D%2C%20random_state%3D0)%5B1%5D.sum())%0A%20%20%20%20mo.md(f%22With%20seed%200%2C%20the%20forest's%20held-out%20precision%20is%20**%7B_scores%5B'precision'%5D%3A.2f%7D**%20and%20its%20recall%20**%7B_scores%5B'recall'%5D%3A.2f%7D**%2C%20on%20%7B_held%7D%20held-out%20edits%3A%20one%20edit%20more%20or%20less%20found%20moves%20the%20recall%20by%20%7B1%20%2F%20_held%3A.2f%7D.%20%22%0A%20%20%20%20%20%20%20%20%20%20%22Set%20these%20beside%20the%20detectors'%20precision%20in%20section%203's%20table%3A%20a%20model%20that%20learned%20from%20labels%20is%20far%20more%20precise%20on%20the%20kinds%20it%20was%20shown.%20The%20next%20cells%20test%20it%20on%20a%20round%20with%20a%20kind%20it%20was%20not%20shown.%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Scoring%20a%20new%20round%2C%20and%20choosing%20the%20threshold%0A%0A%20%20%20%20For%20use%2C%20the%20forest%20learns%20from%20every%20training%20row%3A%20the%20held-out%20split%20was%20only%20for%20judging%20it.%20%60predict%60%20answers%20%22edited%22%20when%20more%20than%20half%20the%20trees%20vote%20for%20it%3B%20%60predict_proba(X)%5B%3A%2C%201%5D%60%20gives%20the%20share%20of%20trees%20that%20do%2C%20between%200%20and%201%2C%20and%20the%20**threshold**%20on%20it%20is%20the%20same%20lever%20as%20contamination%20was%20for%20the%20detectors.%20A%20lower%20threshold%20flags%20more%20rows%2C%20finds%20more%20of%20the%20anomalies%2C%20and%20wastes%20more%20reviews.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20fit_forest(past%3A%20pd.DataFrame)%20-%3E%20RandomForestClassifier%3A%0A%20%20%20%20%22%22%22The%20forest%20for%20use%3A%20200%20trees%2C%20random_state%3D0%2C%20fitted%20on%20every%20unit%20of%20the%202021%20round%20but%20the%20weight%20edits.%22%22%22%0A%20%20%20%20rows%20%3D%20past%5Bpast%5B%22edit_kind%22%5D%20!%3D%20%22weight_inflated%22%5D%0A%20%20%20%20return%20RandomForestClassifier(n_estimators%3D200%2C%20random_state%3D0).fit(tree_matrix(rows)%2C%20rows%5B%22was_edited%22%5D)%0A%0A%0A%40app.cell%0Adef%20_(past)%3A%0A%20%20%20%20forest%20%3D%20fit_forest(past)%0A%20%20%20%20threshold%20%3D%20mo.ui.slider(start%3D0.1%2C%20stop%3D0.9%2C%20step%3D0.1%2C%20value%3D0.5%2C%20label%3D%22threshold%22%2C%20show_value%3DTrue)%0A%20%20%20%20threshold%0A%20%20%20%20return%20forest%2C%20threshold%0A%0A%0A%40app.cell%0Adef%20_(features%2C%20forest%2C%20threshold%2C%20truth)%3A%0A%20%20%20%20%23%20The%20survey%20scored%20by%20the%202021%20round's%20forest%3A%20how%20many%20flagged%2C%20and%20how%20many%20of%20them%20carry%20a%20defect%0A%20%20%20%20_share%20%3D%20forest.predict_proba(tree_matrix(features))%5B%3A%2C%201%5D%0A%20%20%20%20_flagged%20%3D%20set(features.loc%5B_share%20%3E%3D%20threshold.value%2C%20%22unit_id%22%5D)%0A%20%20%20%20mo.md(f%22At%20a%20threshold%20of%20%7Bthreshold.value%3A.1f%7D%2C%20the%20forest%20flags%20**%7Blen(_flagged)%7D**%20of%20the%20survey's%20%7Blen(features)%3A%2C%7D%20units%3B%20**%7Blen(_flagged%20%26%20truth)%7D**%20of%20them%20carry%20a%20defect%20their%20features%20show.%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Exercise%209.7.%20The%20units%20a%20forest%20flags%20at%20a%20threshold%0A%0A%20%20%20%20**Why%20it%20matters%3A**%20the%20threshold%20is%20the%20survey%20team's%20decision%2C%20not%20the%20model's.%20This%20function%20turns%20a%20fitted%20forest%2C%20a%20table%20and%20that%20decision%20into%20the%20review%20list.%0A%0A%20%20%20%20**Input%20%E2%86%92%20output%3A**%20a%20fitted%20forest%20%60model%60%2C%20a%20table%20of%20units%20%60table%60%20(with%20%60unit_id%60%2C%20the%20features%20and%20%60unit_scale%60)%20and%20a%20%60threshold%60%20%E2%86%92%20the%20sorted%20list%20of%20%60unit_id%60s%20whose%20probability%20of%20%22edited%22%2C%20%60model.predict_proba(tree_matrix(table))%5B%3A%2C%201%5D%60%2C%20is%20**at%20least**%20the%20threshold.%0A%0A%20%20%20%20**Tools%3A**%20%60tree_matrix%60%20(section%201)%2C%20%60predict_proba%60%2C%20column%201%20of%20its%20result%20(%60%5B%3A%2C%201%5D%60)%2C%20%60%3E%3D%60%2C%20a%20boolean%20mask%2C%20%60sorted%60.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20edit_flags(model%3A%20RandomForestClassifier%2C%20table%3A%20pd.DataFrame%2C%20threshold%3A%20float)%20-%3E%20list%3A%0A%20%20%20%20%22%22%22The%20unit_ids%20whose%20probability%20of%20being%20edited%2C%20by%20this%20forest%2C%20is%20at%20least%20the%20threshold%2C%20sorted.%22%22%22%0A%20%20%20%20%23%20Exercise%209.7%3A%20the%20task%20and%20examples%20are%20in%20the%20text%20above%20this%20cell.%0A%20%20%20%20%23%20Step%201%3A%20the%20probability%20of%20%22edited%22%20for%20every%20row%3A%20predict_proba%20of%20tree_matrix(table)%2C%20column%201%0A%20%20%20%20%23%20Step%202%3A%20the%20rows%20where%20it%20is%20at%20least%20the%20threshold%0A%20%20%20%20%23%20Step%203%3A%20return%20their%20unit_id%20values%2C%20sorted%2C%20as%20a%20list%0A%20%20%20%20raise%20NotImplementedError(%22Exercise%209.7%22)%0A%0A%0A%40app.function%0Adef%20round_fixture()%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22Four%20units%20of%20a%20new%20round%3A%20a%20small%20boat%2C%20a%20small%20boat%20whose%20dimensions%20look%20like%20feet%20recorded%20as%20meters%2C%20a%0A%20%20%20%20large%20boat%20in%20a%20small-scale%20unit%2C%20and%20a%20large-scale%20unit.%20Used%20by%20the%20check%20of%20Exercise%209.7.%22%22%22%0A%20%20%20%20rows%20%3D%20%5B%0A%20%20%20%20%20%20%20%20%23%20unit_id%2C%20unit_scale%2C%20n_boats%2C%20largest_tonnage%2C%20longest_boat_m%2C%20sum_tonnage%2C%20sum_engine_hp%2C%20n_species%2C%20n_gears%2C%20n_landings%2C%20n_crew%2C%20hh_size%2C%20age_of_operator%2C%20hh_interview_minutes%0A%20%20%20%20%20%20%20%20(%2201-1-1-1%22%2C%201%2C%201%2C%200.9%2C%207.5%2C%200.9%2C%209.0%2C%204%2C%201%2C%201%2C%200%2C%204%2C%2045%2C%2050)%2C%0A%20%20%20%20%20%20%20%20(%2201-2-1-1%22%2C%202%2C%201%2C%2031.8%2C%2024.6%2C%2031.8%2C%209.0%2C%204%2C%201%2C%201%2C%200%2C%205%2C%2051%2C%2047)%2C%0A%20%20%20%20%20%20%20%20(%2204-3-1-1%22%2C%201%2C%201%2C%209.9%2C%2014.0%2C%209.9%2C%2030.0%2C%203%2C%202%2C%201%2C%201%2C%203%2C%2038%2C%2055)%2C%0A%20%20%20%20%20%20%20%20(%2207-4-1-1%22%2C%202%2C%203%2C%2058.0%2C%2022.0%2C%20140.0%2C%20900.0%2C%207%2C%202%2C%202%2C%208%2C%206%2C%2049%2C%2061)%2C%0A%20%20%20%20%5D%0A%20%20%20%20return%20pd.DataFrame(rows%2C%20columns%3D%5B%22unit_id%22%2C%20%22unit_scale%22%2C%20*FEATURES%5D)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_(features%2C%20forest)%3A%0A%20%20%20%20check_cases(%0A%20%20%20%20%20%20%20%20%22Exercise%209.7%22%2C%20edit_flags%2C%0A%20%20%20%20%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22four%20units%20of%20a%20new%20round%2C%20threshold%200.5%22%2C%20(forest%2C%20round_fixture()%2C%200.5))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20survey%2C%20threshold%200.5%22%2C%20(forest%2C%20features%2C%200.5))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20survey%2C%20threshold%200.2%22%2C%20(forest%2C%20features%2C%200.2))%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20what%3D%22tables%20and%20thresholds%22%2C%20summarize%3Dlambda%20ids%3A%20sorted(map(str%2C%20ids))%2C%0A%20%20%20%20%20%20%20%20hint%3D%22predict_proba(tree_matrix(table))%5B%3A%2C%201%5D%20is%20the%20probability%20of%20'edited'%3B%20keep%20the%20unit_id%20where%20it%20is%20%3E%3D%20threshold%3B%20sort.%22%2C%0A%20%20%20%20)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(forest)%3A%0A%20%20%20%20%23%20Try%20it%3A%20the%20four%20units%20of%20the%20new%20round%20at%20a%20threshold%20of%200.5%0A%20%20%20%20try_it(edit_flags%2C%20forest%2C%20round_fixture()%2C%200.5)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22If%20the%20check%20is%20red%3A%20common%20causes%20for%20Exercise%209.7%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%7C%20what%20you%20see%20%7C%20the%20usual%20cause%20%7C%20look%20at%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20Almost%20every%20unit_id%20%7C%20Column%200%2C%20the%20probability%20of%20%22not%20edited%22.%20%7C%20%60%5B%3A%2C%201%5D%60%20%7C%0A%20%20%20%20%7C%20Right%20at%200.5%2C%20wrong%20at%200.2%20%7C%20%60predict%60%20used%3A%20it%20always%20cuts%20at%20one%20half.%20%7C%20%60predict_proba%60%20and%20the%20threshold%20%7C%0A%20%20%20%20%7C%20One%20or%20two%20ids%20missing%20%7C%20%60%3E%60%20where%20the%20task%20says%20at%20least.%20%7C%20%60%3E%3D%60%20%7C%0A%20%20%20%20%7C%20*KeyError*%20or%20*ValueError*%20naming%20feature%20names%20%7C%20The%20table%20passed%20as%20it%20is%2C%20with%20its%20ids%20and%20codes.%20%7C%20%60tree_matrix(table)%60%20%7C%0A%0A%20%20%20%20Still%20stuck%20after%20ten%20minutes%3F%20Ask%20your%20table%2C%20then%20raise%20your%20hand.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20What%20last%20round's%20labels%20find%20this%20round%2C%20and%20what%20they%20miss%0A%0A%20%20%20%20The%20survey%20is%20this%20round.%20The%202021%20round's%20editors%20corrected%20three%20kinds%20of%20error%3B%20this%20round%20holds%20those%20kinds%20and%20others.%20The%20forest%2C%20at%20its%20default%20threshold%2C%20beside%20the%20rules%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(features%2C%20forest%2C%20rule_units%2C%20truth)%3A%0A%20%20%20%20%23%20The%20forest's%20flags%20on%20the%20survey%2C%20kind%20by%20kind%2C%20beside%20the%20rules'%0A%20%20%20%20_forest_units%20%3D%20set(features.loc%5Bforest.predict(tree_matrix(features))%20%3D%3D%201%2C%20%22unit_id%22%5D)%0A%20%20%20%20_rows%20%3D%20%5B%5D%0A%20%20%20%20for%20_name%20in%20shown_by_features()%3A%0A%20%20%20%20%20%20%20%20_households%20%3D%20planted.loc%5Bplanted%5B%22kind%22%5D%20%3D%3D%20_name%2C%20HOUSEHOLD%5D.drop_duplicates()%0A%20%20%20%20%20%20%20%20_units%20%3D%20set(features.merge(_households%2C%20on%3DHOUSEHOLD)%5B%22unit_id%22%5D)%20%26%20truth%0A%20%20%20%20%20%20%20%20_rows.append(%7B%22kind%22%3A%20_name%2C%20%22units%22%3A%20len(_units)%2C%20%22the%20forest%20finds%22%3A%20len(_units%20%26%20_forest_units)%2C%20%22the%20rules%20find%22%3A%20len(_units%20%26%20rule_units)%7D)%0A%20%20%20%20_table%20%3D%20pd.DataFrame(_rows)%0A%20%20%20%20_area_large%20%3D%20set(features.merge(planted.loc%5Bplanted%5B%22kind%22%5D%20%3D%3D%20%22large_unit_in_area_stratum%22%2C%20HOUSEHOLD%5D%2C%20on%3DHOUSEHOLD)%5B%22unit_id%22%5D)%0A%20%20%20%20_missed%20%3D%20_table.loc%5B_table%5B%22the%20forest%20finds%22%5D%20%3D%3D%200%2C%20%22kind%22%5D.tolist()%0A%20%20%20%20mo.vstack(%5B%0A%20%20%20%20%20%20%20%20_table%2C%0A%20%20%20%20%20%20%20%20mo.md(f%22The%20forest%20flags%20**%7Blen(_forest_units)%7D**%20units%3B%20%7Blen(_forest_units%20%26%20truth)%7D%20carry%20a%20defect%2C%20and%20%7Blen(_forest_units%20%26%20_area_large%20-%20truth)%7D%20of%20the%20rest%20belong%20to%20households%20of%20an%20area%20stratum%20that%20run%20a%20large-scale%20unit%3A%20large%20boats%20sampled%20in%20the%20areas%2C%20which%20are%20real%20and%20look%20like%20the%202021%20round's%20wrong%20units%20of%20measure.%20%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20f%22It%20finds%20none%20of%20these%20kinds%3A%20**%7B'%2C%20'.join(_missed)%7D**.%20%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20f%22The%20made-up%20interviews%20(%60made_up_interview%60)%20are%20new%20this%20round%3A%20the%202021%20round's%20editors%20never%20labeled%20one%2C%20so%20the%20forest%20never%20learned%20what%20one%20looks%20like.%20The%20rules%20find%20%7Blen(rule_units%20%26%20truth)%7D%20of%20the%20%7Blen(truth)%7D%2C%20and%20**the%20forest%20adds%20%7Blen((_forest_units%20%26%20truth)%20-%20rule_units)%7D**%20to%20them.%22)%2C%0A%20%20%20%20%5D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20A%20supervised%20model%20finds%20what%20it%20was%20shown.%20Its%20precision%20on%20those%20kinds%20is%20what%20makes%20it%20worth%20training%3A%20section%205%20shows%20it%20on%20a%20table%20where%20no%20rule%20catches%20the%20wrong%20units%20of%20measure.%20Its%20blind%20spot%20is%20everything%20else%2C%20which%20is%20why%20it%20runs%20**beside**%20the%20rules%20and%20a%20detector%2C%20never%20instead%20of%20them.%20Retrain%20it%20each%20round%2C%20on%20that%20round's%20edits%2C%20so%20the%20kinds%20it%20knows%20keep%20up%20with%20the%20kinds%20that%20occur.%0A%0A%20%20%20%20**Pretrained%20deep%20models%2C%20as%20of%20November%202026.**%20The%20geospatial%20training's%20last%20part%20used%20deep%20models%20pretrained%20on%20millions%20of%20images%2C%20then%20adapted%20to%20land%20cover%20with%20a%20few%20labels.%20That%20works%20because%20a%20pixel%20means%20the%20same%20in%20every%20scene%3A%20edges%2C%20textures%20and%20shapes%20learned%20elsewhere%20carry%20over%20to%20a%20new%20image.%20A%20coded%20survey%20row%20has%20no%20such%20shared%20meaning.%20%60unit_scale%20%3D%201%60%20means%20%22small-scale%22%20only%20in%20this%20survey's%20codebook%2C%20and%20%60mem_education%20%3D%2031%60%20means%20%22upper%20secondary%20completed%22%20only%20in%20this%20course's%20list.%20A%20model%20pretrained%20on%20other%20data%20has%20learned%20nothing%20about%20these%20codes%2C%20so%20it%20has%20nothing%20to%20transfer%3B%20adapted%20with%20the%20editors'%20labels%2C%20it%20would%20learn%20from%20the%20same%20labels%20as%20the%20forest%20and%20be%20judged%20on%20the%20same%20held-out%20rows.%20This%20course%20therefore%20stops%20at%20the%20forest.%20Reading%20rows%20together%20with%20their%20codebook%20is%20what%20a%20language%20model%20does%3B%20the%20stretch%20S4%20(%6086_stretch_agents.py%60)%20shows%20one%20run%20locally%20on%20the%20survey%2C%20and%20what%20each%20path%20sends%20away.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%205%20%C2%B7%20Scoring%20a%20large%20table%20with%20polars%2C%20DuckDB%20and%20Parquet%0A%0A%20%20%20%20**The%20problem.**%20The%20survey%20has%20about%202%2C500%20fishing%20units.%20%60units_2025_all_regions.parquet%60%20has%20240%2C000%2C%20one%20row%20each%2C%20with%20the%20features%20section%201%20built%2C%20from%20all%20eighteen%20regions%3B%20a%20national%20survey%20can%20have%20millions.%20Reading%20every%20column%20of%20every%20row%20into%20pandas%2C%20fitting%20on%20all%20of%20it%20and%20scoring%20all%20of%20it%20at%20once%20works%20here%20and%20stops%20working%20as%20the%20table%20grows.%20Three%20habits%20keep%20the%20work%20proportional%20to%20what%20is%20needed%3A%0A%0A%20%20%20%20%7C%20habit%20%7C%20the%20tool%20%7C%20what%20it%20saves%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20read%20only%20the%20columns%20and%20rows%20you%20need%20%7C%20polars'%20%60scan_parquet%60%20(lazy)%2C%20DuckDB's%20SQL%20on%20the%20file%20%7C%20memory%20and%20time%3A%20the%20file%20is%20read%20once%2C%20and%20only%20in%20part%20%7C%0A%20%20%20%20%7C%20fit%20on%20a%20sample%20%7C%20%60polars%60%20%60.sample(n%2C%20seed%3D...)%60%20%7C%20a%20detector%20learns%20what%20is%20common%20from%2020%2C000%20rows%20as%20well%20as%20from%20240%2C000%20%7C%0A%20%20%20%20%7C%20score%20in%20chunks%20%7C%20%60pyarrow%60's%20%60iter_batches%60%2C%20polars'%20%60iter_slices%60%2C%20DuckDB's%20%60to_arrow_reader%60%20%7C%20memory%3A%20one%20chunk%20at%20a%20time%2C%20every%20row%20scored%20%7C%0A%0A%20%20%20%20%23%23%23%20Reading%20only%20what%20is%20needed%0A%0A%20%20%20%20%60pl.scan_parquet%60%20reads%20nothing%20yet%3A%20it%20plans.%20%60select%60%2C%20%60filter%60%20and%20%60group_by%60%20add%20to%20the%20plan%2C%20and%20%60collect()%60%20runs%20it%2C%20reading%20only%20the%20columns%20the%20plan%20uses%20(projection%20pushdown)%20and%20skipping%20rows%20where%20the%20file's%20statistics%20allow%20(predicate%20pushdown).%20DuckDB%20does%20the%20same%20from%20SQL%2C%20on%20the%20file%20itself.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20polars%2C%20lazy%3A%20the%20plan%20reads%20three%20columns%20of%20the%20file%20and%20returns%20one%20row%20per%20scale%0A%20%20%20%20_plan%20%3D%20(pl.scan_parquet(PATHS.all_regions)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20.select(%22unit_scale%22%2C%20%22largest_tonnage%22%2C%20%22hh_interview_minutes%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20.group_by(%22unit_scale%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20.agg(units%3Dpl.len()%2C%20median_tonnage%3Dpl.col(%22largest_tonnage%22).median()%2C%20median_minutes%3Dpl.col(%22hh_interview_minutes%22).median())%0A%20%20%20%20%20%20%20%20%20%20%20%20%20.sort(%22unit_scale%22))%0A%20%20%20%20_plan.collect()%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20DuckDB%3A%20the%20same%20question%20in%20SQL%2C%20on%20the%20file%20itself%2C%20returned%20as%20a%20polars%20table%0A%20%20%20%20with%20duckdb.connect()%20as%20_con%3A%0A%20%20%20%20%20%20%20%20_answer%20%3D%20_con.sql(f%22%22%22%0A%20%20%20%20%20%20%20%20%20%20%20%20SELECT%20unit_scale%2C%20count(*)%20AS%20units%2C%20median(largest_tonnage)%20AS%20median_tonnage%2C%20median(hh_interview_minutes)%20AS%20median_minutes%0A%20%20%20%20%20%20%20%20%20%20%20%20FROM%20read_parquet('%7BPATHS.all_regions.as_posix()%7D')%0A%20%20%20%20%20%20%20%20%20%20%20%20GROUP%20BY%20unit_scale%20ORDER%20BY%20unit_scale%0A%20%20%20%20%20%20%20%20%22%22%22).pl()%0A%20%20%20%20_answer%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Fit%20on%20a%20sample%2C%20one%20detector%20per%20scale%0A%0A%20%20%20%20An%20Isolation%20Forest%20draws%20256%20rows%20for%20each%20tree%20whatever%20the%20table's%20size%2C%20so%20a%20seeded%20sample%20of%2020%2C000%20units%20teaches%20it%20what%20is%20common%20as%20well%20as%20all%20240%2C000%20would%2C%20and%20a%20table%20that%20does%20not%20fit%20in%20memory%20can%20still%20be%20fitted.%20The%20forests%20below%20are%20fitted%20per%20scale%2C%20as%20in%20section%202%2C%20and%20%60score_by_scale%60%20scores%20any%20chunk%20with%20the%20forest%20of%20each%20row's%20scale.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20A%20seeded%20sample%20of%20the%20large%20table%2C%20read%20with%20polars%20and%20handed%20to%20scikit-learn%20as%20pandas%0A%20%20%20%20_sample%20%3D%20pl.read_parquet(PATHS.all_regions%2C%20columns%3D%5B%22unit_scale%22%2C%20*FEATURES%5D).sample(n%3D20_000%2C%20seed%3D0).to_pandas()%0A%20%20%20%20large_table_forests%20%3D%20%7Bcode%3A%20IsolationForest(n_estimators%3D200%2C%20random_state%3D0).fit(rows%5BFEATURES%5D)%20for%20code%2C%20rows%20in%20_sample.groupby(%22unit_scale%22)%7D%0A%20%20%20%20mo.md(f%22Fitted%20on%20%7Blen(_sample)%3A%2C%7D%20sampled%20units%3A%20%7B'%2C%20'.join(f'%7B(_sample%5B'unit_scale'%5D%20%3D%3D%20c).sum()%3A%2C%7D%20of%20scale%20%7Bc%7D'%20for%20c%20in%20large_table_forests)%7D.%22)%0A%20%20%20%20return%20(large_table_forests%2C)%0A%0A%0A%40app.cell%0Adef%20_(large_table_forests)%3A%0A%20%20%20%20def%20score_by_scale(chunk%3A%20pd.DataFrame)%20-%3E%20np.ndarray%3A%0A%20%20%20%20%20%20%20%20%22%22%22The%20Isolation%20Forest%20score%20of%20every%20row%20of%20a%20chunk%2C%20each%20by%20the%20forest%20of%20its%20scale%20(lower%20is%20more%20unusual).%22%22%22%0A%20%20%20%20%20%20%20%20out%20%3D%20np.empty(len(chunk))%0A%20%20%20%20%20%20%20%20for%20code%2C%20model%20in%20large_table_forests.items()%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20mask%20%3D%20(chunk%5B%22unit_scale%22%5D%20%3D%3D%20code).to_numpy()%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20mask.any()%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20out%5Bmask%5D%20%3D%20model.score_samples(chunk.loc%5Bmask%2C%20FEATURES%5D)%0A%20%20%20%20%20%20%20%20return%20out%0A%0A%20%20%20%20return%20(score_by_scale%2C)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Scoring%20in%20chunks%3A%20exact%20for%20some%20detectors%2C%20not%20for%20others%0A%0A%20%20%20%20A%20fitted%20Isolation%20Forest%20scores%20each%20row%20on%20its%20own%3A%20a%20row's%20path%20through%20a%20tree%20depends%20on%20the%20row%20and%20the%20tree%2C%20nothing%20else.%20Score%20the%20table%20at%20once%20or%20in%20chunks%20of%20any%20size%2C%20and%20every%20row%20gets%20the%20same%20score.%20A%20random%20forest's%20probability%20is%20the%20same%20kind%20of%20thing.%20Three%20readers%20hand%20out%20the%20chunks%3A%0A%0A%20%20%20%20%60%60%60python%0A%20%20%20%20for%20batch%20in%20pq.ParquetFile(path).iter_batches(batch_size%3D50_000)%3A%20%20%20%20%20%20%20%20%23%20pyarrow%0A%20%20%20%20%20%20%20%20chunk%20%3D%20batch.to_pandas()%0A%20%20%20%20for%20chunk%20in%20pl.read_parquet(path).iter_slices(n_rows%3D50_000)%3A%20%20%20%20%20%20%20%20%20%20%20%20%23%20polars%20(the%20table%20is%20read%2C%20then%20sliced)%0A%20%20%20%20%20%20%20%20chunk%20%3D%20chunk.to_pandas()%0A%20%20%20%20with%20duckdb.connect()%20as%20con%3A%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%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20DuckDB%2C%20from%20SQL%0A%20%20%20%20%20%20%20%20for%20batch%20in%20con.sql(f%22SELECT%20*%20FROM%20read_parquet('%7Bpath%7D')%22).to_arrow_reader(50_000)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20chunk%20%3D%20batch.to_pandas()%0A%20%20%20%20%60%60%60%0A%0A%20%20%20%20pyarrow's%20and%20DuckDB's%20read%20the%20file%20a%20batch%20at%20a%20time%3B%20polars'%20slices%20a%20table%20already%20in%20memory%2C%20so%20it%20saves%20nothing%20when%20the%20file%20is%20too%20large%20to%20read%20whole.%0A%0A%20%20%20%20%23%23%23%20Exercise%209.8.%20Scores%2C%20chunk%20by%20chunk%0A%0A%20%20%20%20**Why%20it%20matters%3A**%20this%20is%20the%20loop%20that%20lets%20a%20model%20fitted%20on%20a%20sample%20score%20a%20table%20of%20every%20region%20on%20a%20laptop.%20It%20must%20give%20every%20row%20its%20score%2C%20in%20the%20file's%20order%2C%20whatever%20the%20chunk%20size%2C%20or%20the%20review%20list%20depends%20on%20a%20setting%20nobody%20thinks%20about.%0A%0A%20%20%20%20**Input%20%E2%86%92%20output%3A**%20%60score%60%20(a%20function%20that%20takes%20a%20pandas%20table%2C%20one%20chunk%2C%20and%20returns%20one%20number%20per%20row)%2C%20the%20Parquet%20file's%20%60path%60%20and%20%60chunk_rows%60%20%E2%86%92%20one%20NumPy%20array%20with%20every%20row's%20score%2C%20in%20the%20file's%20order%3A%0A%0A%20%20%20%20%60%60%60python%0A%20%20%20%20score_in_chunks(score_by_scale%2C%20PATHS.all_regions%2C%2050_000)%20%20%20%23%20array(%5B-0.43%2C%20-0.41%2C%20...%5D)%2C%20240%2C000%20values%0A%20%20%20%20%60%60%60%0A%0A%20%20%20%20**Tools%3A**%20any%20of%20the%20three%20readers%20above%2C%20%60.to_pandas()%60%2C%20a%20list%20of%20the%20chunks'%20scores%2C%20and%20%60np.concatenate%60.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20score_in_chunks(score%2C%20path%2C%20chunk_rows%3A%20int)%20-%3E%20np.ndarray%3A%0A%20%20%20%20%22%22%22Every%20row's%20score%2C%20reading%20the%20Parquet%20file%20chunk_rows%20rows%20at%20a%20time%2C%20in%20the%20file's%20order.%22%22%22%0A%20%20%20%20%23%20Exercise%209.8%3A%20the%20task%20and%20examples%20are%20in%20the%20text%20above%20this%20cell.%0A%20%20%20%20%23%20Step%201%3A%20read%20the%20file%20in%20batches%20of%20chunk_rows%20rows%20(pq.ParquetFile(path).iter_batches(batch_size%3D...))%0A%20%20%20%20%23%20Step%202%3A%20turn%20each%20batch%20into%20a%20pandas%20table%20and%20score%20it%3B%20keep%20each%20chunk's%20scores%20in%20a%20list%0A%20%20%20%20%23%20Step%203%3A%20join%20the%20list%20into%20one%20array%20with%20np.concatenate%2C%20and%20return%20it%0A%20%20%20%20raise%20NotImplementedError(%22Exercise%209.8%22)%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_(forest%2C%20score_by_scale)%3A%0A%20%20%20%20def%20_edited_share(chunk%3A%20pd.DataFrame)%20-%3E%20np.ndarray%3A%0A%20%20%20%20%20%20%20%20return%20forest.predict_proba(tree_matrix(chunk))%5B%3A%2C%201%5D%0A%0A%20%20%20%20check_cases(%0A%20%20%20%20%20%20%20%20%22Exercise%209.8%22%2C%20score_in_chunks%2C%0A%20%20%20%20%20%20%20%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20large%20table%2C%20Isolation%20Forests%20per%20scale%2C%20chunks%20of%2060%2C000%22%2C%20(score_by_scale%2C%20PATHS.all_regions%2C%2060_000))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20large%20table%2C%20the%20same%20forests%2C%20chunks%20of%2070%2C000%20(the%20last%20is%2030%2C000)%22%2C%20(score_by_scale%2C%20PATHS.all_regions%2C%2070_000))%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20(%22the%20large%20table%2C%20the%202021%20round's%20random%20forest%2C%20chunks%20of%2064%2C000%22%2C%20(_edited_share%2C%20PATHS.all_regions%2C%2064_000))%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20what%3D%22ways%20of%20chunking%20the%20table%22%2C%20summarize%3Dlambda%20scores%3A%20np.round(np.asarray(scores%2C%20dtype%3Dfloat)%2C%204)%2C%0A%20%20%20%20%20%20%20%20hint%3D%22Read%20the%20file%20in%20batches%20of%20chunk_rows%2C%20score%20each%20batch%20as%20a%20pandas%20table%2C%20and%20np.concatenate%20the%20scores%20in%20order.%22%2C%0A%20%20%20%20)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_(score_by_scale)%3A%0A%20%20%20%20%23%20Try%20it%3A%20every%20unit's%20score%20in%20the%20large%20table%2C%20read%2050%2C000%20rows%20at%20a%20time%0A%20%20%20%20try_it(score_in_chunks%2C%20score_by_scale%2C%20PATHS.all_regions%2C%2050_000)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.accordion(%7B%22If%20the%20check%20is%20red%3A%20common%20causes%20for%20Exercise%209.8%22%3A%20mo.md(r%22%22%22%0A%20%20%20%20%7C%20what%20you%20see%20%7C%20the%20usual%20cause%20%7C%20look%20at%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20An%20array%20of%2060%2C000%20or%2030%2C000%20values%20%7C%20Only%20the%20last%20chunk's%20scores%20returned.%20%7C%20collect%20every%20chunk's%20scores%20in%20a%20list%20%7C%0A%20%20%20%20%7C%20Right%20for%20chunks%20of%2060%2C000%2C%20wrong%20for%2070%2C000%20%7C%20The%20last%2C%20shorter%20chunk%20left%20out%20(a%20%60range%60%20that%20stops%20early).%20%7C%20let%20the%20reader%20hand%20out%20every%20batch%20%7C%0A%20%20%20%20%7C%20*AttributeError%3A%20'RecordBatch'%20object%20has%20no%20attribute%20'loc'*%20%7C%20The%20batch%20given%20to%20%60score%60%20as%20it%20is%2C%20not%20as%20pandas.%20%7C%20%60batch.to_pandas()%60%20%7C%0A%20%20%20%20%7C%20*ValueError%3A%20need%20at%20least%20one%20array%20to%20concatenate*%20%7C%20The%20loop%20never%20ran%3A%20the%20file's%20path%20or%20the%20batch%20size%20is%20wrong.%20%7C%20%60iter_batches(batch_size%3Dchunk_rows)%60%20%7C%0A%0A%20%20%20%20Still%20stuck%20after%20ten%20minutes%3F%20Ask%20your%20table%2C%20then%20raise%20your%20hand.%0A%20%20%20%20%22%22%22)%7D)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20**ECOD%20is%20not%20exact%20in%20chunks.**%20ECOD's%20tails%20are%20the%20tails%20of%20the%20table%20it%20is%20shown.%20Asked%20to%20score%20new%20rows%2C%20PyOD's%20ECOD%20joins%20them%20to%20its%20training%20rows%20and%20computes%20the%20tails%20again%2C%20so%20a%20row's%20score%20depends%20on%20which%20other%20rows%20came%20in%20the%20same%20call.%20Fitted%20on%20the%20same%20sample%20and%20asked%20about%20the%20same%20rows%2C%20once%20whole%20and%20once%20in%20chunks%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20ECOD%20fitted%20on%20a%20sample%2C%20then%20scoring%2060%2C000%20units%20at%20once%20and%20in%20three%20chunks%3A%20the%20scores%20differ%0A%20%20%20%20_sample%20%3D%20pl.read_parquet(PATHS.all_regions%2C%20columns%3DFEATURES).sample(n%3D20_000%2C%20seed%3D0).to_pandas()%0A%20%20%20%20_scaler%20%3D%20RobustScaler().fit(_sample)%0A%20%20%20%20_ecod%20%3D%20ECOD().fit(_scaler.transform(_sample))%0A%20%20%20%20_new%20%3D%20_scaler.transform(pl.read_parquet(PATHS.all_regions%2C%20columns%3DFEATURES).head(60_000).to_pandas())%0A%20%20%20%20_whole%20%3D%20_ecod.decision_function(_new)%0A%20%20%20%20_chunked%20%3D%20np.concatenate(%5B_ecod.decision_function(_new%5B_start%3A_start%20%2B%2020_000%5D)%20for%20_start%20in%20range(0%2C%2060_000%2C%2020_000)%5D)%0A%20%20%20%20_top_whole%20%3D%20set(np.argsort(-_whole%2C%20kind%3D%22stable%22)%5B%3A600%5D)%0A%20%20%20%20_top_chunked%20%3D%20set(np.argsort(-_chunked%2C%20kind%3D%22stable%22)%5B%3A600%5D)%0A%20%20%20%20mo.md(f%22The%20largest%20difference%20in%20a%20row's%20score%20is%20**%7Bnp.abs(_whole%20-%20_chunked).max()%3A.3f%7D**%2C%20and%20**%7Blen(_top_whole%20-%20_top_chunked)%7D%20of%20the%20600**%20highest-scored%20rows%20change%20between%20the%20two%20runs.%20%22%0A%20%20%20%20%20%20%20%20%20%20%22For%20ECOD%20on%20a%20large%20table%2C%20fit%20on%20the%20whole%20table%20and%20read%20its%20training%20scores%20(%60decision_scores_%60)%2C%20which%20are%20exact%2C%20or%20score%20in%20chunks%20of%20one%20fixed%20size%20and%20say%20so%20beside%20the%20results.%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20%23%23%23%20Judging%20on%20the%20large%20table%0A%0A%20%20%20%20The%20large%20table%20has%20its%20own%20list%20of%20planted%20defects%3A%20wrong%20units%20of%20measure%20(a%20boat's%20dimensions%20in%20feet%20recorded%20as%20meters)%2C%20scales%20that%20contradict%20the%20boats%2C%20inflated%20weights%2C%20and%20a%20block%20of%20interviews%20one%20interviewer%20made%20up.%20It%20has%20no%20boat%20rows%20and%20no%20stratum%2C%20so%20module%204's%20boat%20rules%20and%20a%20weight%20check%20within%20the%20stratum%20cannot%20run%3B%20three%20checks%20can.%20The%20weight%20check%20is%20chosen%20again%20for%20this%20table%3A%20with%20no%20stratum%2C%20the%20median%20of%20all%20its%20weights%20is%20the%20one%20comparison%20left%2C%20and%20its%20cut%20is%20set%20where%20the%20weights'%20own%20distribution%20allows%20(the%20cell%20under%20the%20table%20shows%20the%20gap).%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.function%0Adef%20all_regions_rules(table%3A%20pd.DataFrame)%20-%3E%20pd.DataFrame%3A%0A%20%20%20%20%22%22%22The%20checks%20the%20large%20table's%20columns%20allow%2C%20one%20column%20each%2C%20True%20where%20a%20unit%20fails%20it%3A%20the%20scale%20against%20the%0A%20%20%20%20largest%20boat%20(U3)%2C%20an%20interview%20under%2020%20minutes%2C%20a%20weight%20over%205%20times%20the%20median%20weight.%20The%20table%20has%20no%20stratum%2C%0A%20%20%20%20and%20its%20weights%20run%20from%20about%201%20to%20about%2018%20by%20design%2C%20so%20the%20cut%20is%205%20times%20the%20median%20of%20all%20weights.%22%22%22%0A%20%20%20%20return%20pd.DataFrame(%7B%0A%20%20%20%20%20%20%20%20%22scale%22%3A%20((table%5B%22unit_scale%22%5D%20%3D%3D%201)%20%26%20(table%5B%22largest_tonnage%22%5D%20%3E%3D%205))%20%7C%20((table%5B%22unit_scale%22%5D%20%3D%3D%202)%20%26%20(table%5B%22largest_tonnage%22%5D%20%3C%205))%2C%0A%20%20%20%20%20%20%20%20%22short%20interview%22%3A%20table%5B%22hh_interview_minutes%22%5D%20%3C%2020%2C%0A%20%20%20%20%20%20%20%20%22weight%22%3A%20table%5B%22sel_final_weight%22%5D%20%3E%205%20*%20table%5B%22sel_final_weight%22%5D.median()%2C%0A%20%20%20%20%7D%2C%20index%3Dtable.index)%0A%0A%0A%40app.cell%0Adef%20_(forest%2C%20score_by_scale)%3A%0A%20%20%20%20%23%20Rules%2C%20the%202021%20round's%20forest%20and%20the%20Isolation%20Forests%20on%20all%20240%2C000%20units%2C%20kind%20by%20kind%0A%20%20%20%20all_regions%20%3D%20pd.read_parquet(PATHS.all_regions)%0A%20%20%20%20_defects%20%3D%20pd.read_csv(PATHS.all_regions_defects)%0A%20%20%20%20all_regions%5B%22kind%22%5D%20%3D%20all_regions.merge(_defects%2C%20on%3DUNIT_KEY%2C%20how%3D%22left%22)%5B%22kind%22%5D.fillna(%22%22).to_numpy()%0A%20%20%20%20_budget%20%3D%20len(_defects)%0A%20%20%20%20_iso_scores%20%3D%20score_by_scale(all_regions)%0A%20%20%20%20_flags%20%3D%20%7B%0A%20%20%20%20%20%20%20%20%22rules%22%3A%20all_regions_rules(all_regions).any(axis%3D1).to_numpy()%2C%0A%20%20%20%20%20%20%20%20%22random%20forest%22%3A%20forest.predict(tree_matrix(all_regions))%20%3D%3D%201%2C%0A%20%20%20%20%20%20%20%20f%22Isolation%20Forest%2C%20lowest%20%7B_budget%3A%2C%7D%22%3A%20np.isin(np.arange(len(all_regions))%2C%20np.argsort(_iso_scores%2C%20kind%3D%22stable%22)%5B%3A_budget%5D)%2C%0A%20%20%20%20%7D%0A%20%20%20%20_rows%20%3D%20%5B%7B%22kind%22%3A%20_kind%2C%20%22units%22%3A%20int((all_regions%5B%22kind%22%5D%20%3D%3D%20_kind).sum())%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20**%7B_who%3A%20int((_flag%20%26%20(all_regions%5B%22kind%22%5D%20%3D%3D%20_kind).to_numpy()).sum())%20for%20_who%2C%20_flag%20in%20_flags.items()%7D%7D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20for%20_kind%20in%20sorted(_defects%5B%22kind%22%5D.unique())%5D%0A%20%20%20%20_real%20%3D%20(all_regions%5B%22kind%22%5D%20!%3D%20%22%22).to_numpy()%0A%20%20%20%20_rows.append(%7B%22kind%22%3A%20%22flagged%22%2C%20%22units%22%3A%20None%2C%20**%7B_who%3A%20int(_flag.sum())%20for%20_who%2C%20_flag%20in%20_flags.items()%7D%7D)%0A%20%20%20%20_rows.append(%7B%22kind%22%3A%20%22precision%22%2C%20%22units%22%3A%20None%2C%20**%7B_who%3A%20round(float((_flag%20%26%20_real).sum()%20%2F%20_flag.sum())%2C%203)%20for%20_who%2C%20_flag%20in%20_flags.items()%7D%7D)%0A%20%20%20%20large_table_judged%20%3D%20pd.DataFrame(_rows)%0A%20%20%20%20large_table_judged%0A%20%20%20%20return%20all_regions%2C%20large_table_judged%0A%0A%0A%40app.cell%0Adef%20_(all_regions%2C%20large_table_judged)%3A%0A%20%20%20%20%23%20What%20each%20found%2C%20in%20words%2C%20from%20the%20table%20above%2C%20and%20where%20the%20weight%20cut%20sits%0A%20%20%20%20_row%20%3D%20large_table_judged.set_index(%22kind%22)%0A%20%20%20%20_n%20%3D%20lambda%20kind%2C%20who%3A%20int(_row.loc%5Bkind%2C%20who%5D)%0A%20%20%20%20_iso%20%3D%20%5Bc%20for%20c%20in%20large_table_judged.columns%20if%20c.startswith(%22Isolation%22)%5D%5B0%5D%0A%20%20%20%20_weights%20%3D%20all_regions%5B%22sel_final_weight%22%5D%0A%20%20%20%20mo.md(f%22%22%22%0A%20%20%20%20-%20**The%20weights.**%20Their%20median%20is%20%7B_weights.median()%3A.2f%7D%2C%20and%2099.9%25%20of%20them%20are%20at%20most%20%7B_weights.quantile(0.999)%3A.1f%7D%2C%20%7B_weights.quantile(0.999)%20%2F%20_weights.median()%3A.1f%7D%20times%20the%20median%3B%20the%20next%20weights%20jump%20to%20%7B_weights%5B_weights%20%3E%205%20*%20_weights.median()%5D.min()%3A.0f%7D%20and%20more.%20A%20cut%20at%205%20times%20the%20median%20sits%20in%20that%20gap.%0A%20%20%20%20-%20**The%20rules**%20find%20every%20scale%20error%20(%7B_n('scale_class_wrong'%2C%20'rules')%7D%20of%20%7B_n('scale_class_wrong'%2C%20'units')%7D)%2C%20every%20made-up%20interview%20(%7B_n('made_up'%2C%20'rules')%7D)%20and%20every%20inflated%20weight%20(%7B_n('weight_inflated'%2C%20'rules')%7D)%2C%20with%20a%20precision%20of%20%7B_row.loc%5B'precision'%2C%20'rules'%5D%7D.%20They%20find%20%7B_n('wrong_unit_of_measure'%2C%20'rules')%7D%20of%20the%20%7B_n('wrong_unit_of_measure'%2C%20'units')%7D%20wrong%20units%20of%20measure%2C%20those%20whose%20tonnage%2C%20multiplied%2C%20stayed%20under%205%20gross%20tons%20and%20so%20contradicts%20the%20large-scale%20class%20the%20error%20gave%20them.%20The%20rest%20look%20like%20real%20large%20boats%2C%20so%20no%20rule%20on%20these%20columns%20sees%20them.%0A%20%20%20%20-%20**The%20random%20forest**%20trained%20on%20the%202021%20round's%20edits%20finds%20**%7B_n('wrong_unit_of_measure'%2C%20'random%20forest')%7D%20of%20the%20%7B_n('wrong_unit_of_measure'%2C%20'units')%7D%20wrong%20units%20of%20measure**%2C%20the%20kind%20no%20rule%20here%20catches%2C%20at%20a%20precision%20of%20%7B_row.loc%5B'precision'%2C%20'random%20forest'%5D%7D.%20It%20finds%20%7B_n('made_up'%2C%20'random%20forest')%7D%20made-up%20interviews%2C%20the%20kind%20the%202021%20round%20never%20had.%0A%20%20%20%20-%20**The%20Isolation%20Forests**%20flag%20%7B_n('flagged'%2C%20_iso)%3A%2C%7D%20units%2C%20of%20which%20%7Bround(_row.loc%5B'precision'%2C%20_iso%5D%20*%20_row.loc%5B'flagged'%2C%20_iso%5D)%3A%2C%7D%20are%20anomalies%3A%20in%20this%20table%2C%20rare%20and%20wrong%20are%20mostly%20different%20rows.%0A%0A%20%20%20%20The%20useful%20pipeline%20is%20the%20rules%20plus%20the%202021%20round's%20forest%3B%20the%20detector%20adds%20little%20here.%20That%20is%20a%20finding%20about%20this%20table%2C%20not%20about%20detectors%3A%20it%20is%20what%20judging%20against%20known%20anomalies%20is%20for.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20**An%20interviewer%20is%20a%20group%2C%20not%20a%20row.**%20The%20made-up%20interviews%20are%20a%20pattern%20across%20one%20interviewer's%20work%3A%20short%2C%20alike%2C%20many%20in%20a%20day.%20A%20row-by-row%20detector%20sees%20one%20short%20interview%20at%20a%20time.%20One%20query%20over%20the%20file%2C%20grouped%20by%20interviewer%2C%20sees%20the%20pattern%2C%20as%20module%208's%20interviewer%20indicators%20did%3A%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell%0Adef%20_()%3A%0A%20%20%20%20%23%20DuckDB%20on%20the%20file%3A%20each%20interviewer's%20interviews%2C%20median%20length%20and%20the%20share%20of%20ages%20ending%20in%200%20or%205%0A%20%20%20%20with%20duckdb.connect()%20as%20_con%3A%0A%20%20%20%20%20%20%20%20_interviewers%20%3D%20_con.sql(f%22%22%22%0A%20%20%20%20%20%20%20%20%20%20%20%20SELECT%20hh_interviewer%2C%20count(*)%20AS%20interviews%2C%20median(hh_interview_minutes)%20AS%20median_minutes%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20avg(CASE%20WHEN%20age_of_operator%20%25%205%20%3D%200%20THEN%201%20ELSE%200%20END)%20AS%20ages_ending_0_or_5%0A%20%20%20%20%20%20%20%20%20%20%20%20FROM%20read_parquet('%7BPATHS.all_regions.as_posix()%7D')%0A%20%20%20%20%20%20%20%20%20%20%20%20GROUP%20BY%20hh_interviewer%20HAVING%20count(*)%20%3E%3D%2030%0A%20%20%20%20%20%20%20%20%20%20%20%20ORDER%20BY%20median_minutes%2C%20hh_interviewer%20LIMIT%205%0A%20%20%20%20%20%20%20%20%22%22%22).pl()%0A%20%20%20%20_interviewers%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20mo.md(r%22%22%22%0A%20%20%20%20One%20interviewer%20stands%20apart%3A%20every%20interview%20in%20about%20ten%20minutes%2C%20every%20age%20a%20multiple%20of%20five%2C%20where%20an%20honest%20interviewer's%20ages%20end%20in%200%20or%205%20about%20a%20fifth%20of%20the%20time.%20No%20model%20was%20needed.%20When%20the%20anomaly%20is%20a%20pattern%20across%20rows%2C%20the%20unit%20of%20the%20check%20is%20the%20group%20that%20makes%20the%20pattern.%0A%0A%20%20%20%20%23%23%20What%20you%20can%20do%20now%0A%0A%20%20%20%20%7C%20to%20%7C%20use%20%7C%20and%20check%20%7C%0A%20%20%20%20%7C%3A--%7C%3A--%7C%3A--%7C%0A%20%20%20%20%7C%20build%20features%20from%20survey%20tables%20%7C%20one%20row%20per%20unit%3B%20counts%20with%20%60size%60%20and%20%60nunique%60%3B%20joins%20on%20the%20region%20and%20the%20id%20%7C%20a%20missing%20count%20is%200%3B%20ids%2C%20design%20columns%20and%20weights%20stay%20out%20%7C%0A%20%20%20%20%7C%20encode%20and%20scale%20%7C%20one-hot%20or%20a%200%2F1%20column%20for%20codes%3B%20%60RobustScaler%60%20(median%20and%20IQR)%20%7C%20trees%20take%20codes%20as%20they%20are%3B%20distances%20need%20both%20%7C%0A%20%20%20%20%7C%20detect%20without%20labels%20%7C%20%60IsolationForest%60%20(with%20%60random_state%60)%2C%20%60LocalOutlierFactor%60%2C%20PyOD's%20%60ECOD%60%20%7C%20which%20end%20of%20each%20score%20is%20unusual%3B%20fit%20within%20groups%3B%20%60n_neighbors%60%20above%20the%20largest%20group%20of%20anomalies%20%7C%0A%20%20%20%20%7C%20judge%20a%20detector%20%7C%20precision%20and%20recall%20against%20known%20anomalies%2C%20beside%20the%20rules%20%7C%20what%20the%20detector%20adds%20that%20the%20rules%20do%20not%20%7C%0A%20%20%20%20%7C%20explain%20a%20flag%20%7C%20ECOD's%20%60O%60%2C%20shap's%20%60TreeExplainer%60%20%7C%20the%20direction%20of%20each%20method's%20numbers%20%7C%0A%20%20%20%20%7C%20learn%20from%20last%20round's%20edits%20%7C%20%60RandomForestClassifier%60%2C%20%60train_test_split(...%2C%20stratify%3Dy)%60%20%7C%20held-out%20figures%20only%3B%20labels%20the%20features%20can%20show%3B%20what%20kinds%20the%20labels%20never%20had%20%7C%0A%20%20%20%20%7C%20score%20a%20large%20table%20%7C%20polars%20%60scan_parquet%60%2C%20DuckDB%20on%20the%20file%2C%20a%20sample%20to%20fit%2C%20chunks%20to%20score%20%7C%20chunks%20are%20exact%20for%20a%20fitted%20forest%2C%20not%20for%20ECOD%20%7C%0A%0A%20%20%20%20Next%3A%20the%20debugging%20drill%20D2%20(%6085_debugging_drill.py%60)%20hands%20you%20a%20detector%20that%20flags%20the%20wrong%20rows%2C%20broken%20in%20six%20of%20the%20ways%20this%20module%20warned%20about.%20After%20it%2C%20the%20stretch%20exercises%20S3%20(%6081_stretch_detection.py%60)%20take%20detection%20further%2C%20and%20the%20stretch%20S4%20(%6086_stretch_agents.py%60)%20shows%20what%20AI%20agents%20can%20do%20for%20such%20a%20pipeline%20and%20what%20each%20kind%20sends%20away.%0A%20%20%20%20%22%22%22)%0A%20%20%20%20return%0A%0A%0A%40app.cell(hide_code%3DTrue)%0Adef%20_()%3A%0A%20%20%20%20course.quizzes_at(%229.5%22)%0A%20%20%20%20return%0A%0A%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20app.run()%0A
b8debd412f05b7b5428ac326bb62b580