├── .pre-commit-config.yaml ├── LICENSE ├── README.md ├── __init__.py └── fiftyone.yaml /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/asottile/blacken-docs 3 | rev: v1.12.0 4 | hooks: 5 | - id: blacken-docs 6 | additional_dependencies: [black==21.12b0] 7 | args: ["-l 79"] 8 | exclude: index.umd.js 9 | - repo: https://github.com/ambv/black 10 | rev: 22.3.0 11 | hooks: 12 | - id: black 13 | language_version: python3 14 | args: ["-l 79"] 15 | exclude: index.umd.js 16 | - repo: local 17 | hooks: 18 | - id: pylint 19 | name: pylint 20 | language: system 21 | files: \.py$ 22 | entry: pylint 23 | args: ["--errors-only"] 24 | exclude: index.umd.js 25 | - repo: local 26 | hooks: 27 | - id: ipynb-strip 28 | name: ipynb-strip 29 | language: system 30 | files: \.ipynb$ 31 | entry: jupyter nbconvert --clear-output --ClearOutputPreprocessor.enabled=True 32 | args: ["--log-level=ERROR"] 33 | - repo: https://github.com/pre-commit/mirrors-prettier 34 | rev: v2.6.2 35 | hooks: 36 | - id: prettier 37 | exclude: index.umd.js 38 | language_version: system 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Model Comparison Plugin 2 | 3 | A [FiftyOne plugin](https://docs.voxel51.com/plugins/index.html) for comparing two object 4 | detection models. 5 | 6 | https://github.com/allenleetc/model-comparison/assets/5833306/ba51e51b-a592-4411-8101-208a30c3713f 7 | 8 | (Dataset: [Sama Drives California](https://huggingface.co/datasets/SamaAI/sama-drives-california)) 9 | 10 | ### Installation 11 | 12 | If you haven't already, 13 | [install FiftyOne](https://docs.voxel51.com/getting_started/install.html): 14 | 15 | ```shell 16 | pip install fiftyone 17 | ``` 18 | 19 | Then install the plugin and its dependencies: 20 | 21 | ```shell 22 | fiftyone plugins download https://github.com/allenleetc/model-comparison 23 | ``` 24 | 25 | ### Usage 26 | 27 | 28 | 29 | 30 | 1. Load your dataset. Here we use the [COCO-2017](https://docs.voxel51.com/user_guide/dataset_zoo/datasets.html#coco-2017) from the [FiftyOne Dataset Zoo](https://docs.voxel51.com/user_guide/dataset_zoo/index.html#fiftyone-dataset-zoo): 31 | 32 | ```py 33 | import fiftyone as fo 34 | import fiftyone.zoo as foz 35 | 36 | dataset = foz.load_zoo_dataset( 37 | "coco-2017", 38 | split="validation", 39 | max_samples=5000, 40 | ) 41 | 42 | # Simplify dataset to three classes 43 | classes = ['car','person','traffic light'] 44 | three_classes = (F('label').is_in(classes)) 45 | not_crowd = (F('iscrowd')==0) 46 | view = dataset.filter_labels('ground_truth',three_classes & not_crowd).take(200) 47 | 48 | dataset = view.clone() 49 | dataset.name = 'coco-simple' 50 | dataset.persistent = True 51 | ``` 52 | 53 | 2. Generate model predictions using two object detection models (your dataset may already have predictions!) 54 | 55 | ```py 56 | model_frcnn = foz.load_zoo_model('faster-rcnn-resnet50-fpn-coco-torch') 57 | model_yolo = foz.load_zoo_model('yolov5s-coco-torch') 58 | 59 | dataset.apply_model(model_frcnn, label_field="frcnn") 60 | dataset.apply_model(model_yolo, label_field="yolo") 61 | ``` 62 | 63 | 3. Run single-model evaluations for each model 64 | 65 | ```py 66 | dataset.evaluate_detections('frcnn','ground_truth',eval_key='eval_frcnn',classes=classes) 67 | dataset.evaluate_detections('yolo','ground_truth',eval_key='eval_yolo',classes=classes) 68 | ``` 69 | 70 | 4. Launch the App! 71 | 72 | ```py 73 | session = fo.launch_app(dataset) 74 | ``` 75 | 76 | 5. Press `` ` `` or click the `Browse operations` icon above the grid. 77 | 78 | 6. Run the `Compute Model Differences` operator. Select your ground-truth, model1 predictions, model2 predictions, and model1/model2 (single-model) evaluation keys. 79 | 80 | This will populate new sample- and label-level fields containing statistics and metadata comparing how performance of the two models against ground truth has changed. 81 | 82 | Labels are classified into six groups based on how they compare to ground truth for model1 compared to model2: 83 | 84 | - **hithit**: model1 successful detection, model2 successful detection 85 | - **hitmiss**: model1 successful detection, model2 missed detection (FN) 86 | - **misshit**: model1 missed detection (FN), model2 successful detection 87 | - **missmiss**: both models missed detections (FN) 88 | - **hithit+**: model1 and model2 successful, but localization improved in model2 89 | - **hithit-**: model1 and model2 successful, but localization regressed in model2 90 | 91 | 7. Run the `View Model Differences` operator. 92 | 93 | This operator enables viewing the groups of labels listed above with the ability to filter by class. Model improvements or regressions across all classes, or for particular classes, can be visualized. 94 | 95 | Tip: in the sample modal, selecting a label and using the 'z' (Crop to content) hotkey will zoom quickly to the relevant ground-truth and prediction labels. 96 | 97 | ### Implementation 98 | 99 | FiftyOne's builtin [single-model evaluation](https://docs.voxel51.com/user_guide/evaluation.html#detections) matches ground-truth and predicted detections, storing match status (TP, FN, FP) and associated IOUs on each label. 100 | 101 | In the `Compute Model Differences` operator, these matches are analyzed and compared across the two models. As in single-model evaluation, comparison statistics are populated at the sample and label level. 102 | 103 | The `Visualize Model Differences` operator simpifies viewing the various types of model improvements/regressions by appropriately filtering labels. 104 | 105 | The `Delete Model Comparison` operator deletes a model comparison run along with its sample- and label-level fields. 106 | 107 | Metadata for comparison runs are stored in the `dataset.info` dictionary. 108 | 109 | ### Todo 110 | 111 | - Add tallies/counts of false positives from each prediction to include predicted detections not matched with a GT detection 112 | - In `Visualize Model Differences`, if there are no samples/labels in a selected view, the entire dataset is shown. 113 | - In `Compute Model Differences`, add the ability to specify the IOU threshold defining hithit vs hithit+ and hithit- 114 | - Prettier icons for the operator pallete 115 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | import fiftyone.operators as foo 2 | import fiftyone.operators.types as types 3 | import fiftyone as fo 4 | from fiftyone import ViewField as F 5 | 6 | 7 | CMP_KEY_INFO_DICT_KEY = "model_differences" 8 | ALL_CLASSES = "" 9 | 10 | 11 | def _get_label_fields(sample_collection, label_types): 12 | schema = sample_collection.get_field_schema(embedded_doc_type=label_types) 13 | return list(schema.keys()) 14 | 15 | 16 | def save_label(label_ids_to_vals, _id, case): 17 | assert _id not in label_ids_to_vals 18 | label_ids_to_vals[_id] = case 19 | 20 | 21 | def set_label_cmp(samples, det_fld, label_id, val, cmp_key="cmp"): 22 | view = samples.select_labels(ids=label_id) 23 | sample = view.first() 24 | assert len(sample[det_fld].detections) == 1 25 | sample[det_fld].detections[0][cmp_key] = val 26 | sample.save() 27 | 28 | 29 | def analyze_match_delta( 30 | ctx, 31 | samples, 32 | gtfld, 33 | fld0, 34 | fld1, 35 | ekey0, 36 | ekey1, 37 | iou_thresh=0.2, 38 | cmp_key="cmp", 39 | ): 40 | # real dets 41 | # for pred0 and pred1: 42 | # * these are either fn (miss), or hit 43 | # 44 | # so for any det the options are 45 | # 1. miss -> miss 46 | # 2. miss -> hit IMPROVE 47 | # 3. hit -> miss REGRESS 48 | # 4a. hit -> hit, similar iou. SAME 49 | # 4b. hit -> hit, worse iou. REGRESS 50 | # 4c. hit -> hit, better iou. IMPROVE 51 | 52 | fld_match0 = ekey0 53 | fld_match1 = ekey1 54 | fld_id0 = ekey0 + "_id" 55 | fld_id1 = ekey1 + "_id" 56 | fld_iou0 = ekey0 + "_iou" 57 | fld_iou1 = ekey1 + "_iou" 58 | 59 | fld_cmp = cmp_key 60 | fld_cmp_id0 = cmp_key + "_id0" 61 | fld_cmp_id1 = cmp_key + "_id1" 62 | 63 | label_ids_to_vals_0 = {} 64 | label_ids_to_vals_1 = {} 65 | label_cmpfld_0 = f"{fld0}.detections.{cmp_key}" 66 | label_cmpfld_1 = f"{fld1}.detections.{cmp_key}" 67 | 68 | num_total = len(samples) 69 | for idx, sample in enumerate( 70 | samples.iter_samples(progress=True, autosave=True) 71 | ): 72 | det_map = {} 73 | cnt_map = {"missmiss": 0, "misshit": 0, "hitmiss": 0, "hithit": 0} 74 | if sample[gtfld] is not None: 75 | dets = sample[gtfld].detections 76 | for didx, d in enumerate(dets): 77 | _id = d["id"] 78 | match0 = d[fld_match0] 79 | match1 = d[fld_match1] 80 | if match0 == "fn" and match1 == "fn": 81 | case = "missmiss" 82 | res = (case,) 83 | d[fld_cmp] = case 84 | elif match0 == "fn" and match1 == "tp": 85 | case = "misshit" 86 | id1 = d[fld_id1] 87 | res = (case, id1) 88 | d[fld_cmp] = case 89 | d[fld_cmp_id1] = id1 90 | 91 | save_label(label_ids_to_vals_1, id1, case) 92 | elif match0 == "tp" and match1 == "fn": 93 | case = "hitmiss" 94 | id0 = d[fld_id0] 95 | res = (case, id0) 96 | d[fld_cmp] = case 97 | d[fld_cmp_id0] = id0 98 | save_label(label_ids_to_vals_0, id0, case) 99 | 100 | else: 101 | assert match0 == "tp" and match1 == "tp" 102 | id0 = d[fld_id0] 103 | id1 = d[fld_id1] 104 | iou0 = d[fld_iou0] 105 | iou1 = d[fld_iou1] 106 | 107 | if iou1 - iou0 > iou_thresh: 108 | case = "hithit+" 109 | elif iou0 - iou1 > iou_thresh: 110 | case = "hithit-" 111 | else: 112 | case = "hithit" 113 | 114 | res = (case, id0, id1) 115 | d[fld_cmp] = case 116 | d[fld_cmp_id0] = id0 117 | d[fld_cmp_id1] = id1 118 | 119 | save_label(label_ids_to_vals_0, id0, case) 120 | save_label(label_ids_to_vals_1, id1, case) 121 | 122 | assert _id not in det_map 123 | det_map[_id] = res 124 | case_base = case.rstrip("+-") 125 | cnt_map[case_base] += 1 126 | 127 | sample[gtfld].detections[didx] = d 128 | 129 | for d in sample[gtfld].detections: 130 | assert d[fld_cmp] is not None 131 | 132 | for k, v in cnt_map.items(): 133 | k = cmp_key + "_" + k 134 | sample[k] = v 135 | 136 | progress = idx / num_total 137 | label = f"Loaded {idx} of {num_total}" 138 | yield _set_progress(ctx, progress, label=label) 139 | 140 | samples.set_label_values(label_cmpfld_0, label_ids_to_vals_0) 141 | samples.set_label_values(label_cmpfld_1, label_ids_to_vals_1) 142 | 143 | # Todo: false positives 144 | # these dont get matched. so at sample level can count 145 | 146 | yield 147 | 148 | 149 | class ComputeChanges(foo.Operator): 150 | 151 | LABEL = "Compute Model Differences" 152 | 153 | @property 154 | def config(self): 155 | return foo.OperatorConfig( 156 | name="compute_changes", 157 | label=self.LABEL, 158 | dynamic=True, 159 | execute_as_generator=True, 160 | ) 161 | 162 | def resolve_input(self, ctx): 163 | inputs = types.Object() 164 | 165 | ready = _compute_changes_inputs(ctx, inputs) 166 | if ready: 167 | _execution_mode(ctx, inputs) 168 | 169 | return types.Property(inputs, view=types.View(label=self.LABEL)) 170 | 171 | def resolve_delegation(self, ctx): 172 | return ctx.params.get("delegate", False) 173 | 174 | def execute(self, ctx): 175 | 176 | samples = ctx.dataset 177 | samples.reload() 178 | 179 | cmp_key = ctx.params.get("cmp_key", "cmp") 180 | gt_field = ctx.params.get("gt_field", "ground_truth") 181 | pd0_field = ctx.params.get("p0_field", "predictions0") 182 | pd1_field = ctx.params.get("p1_field", "predictions1") 183 | eval_key0 = ctx.params.get("ekey0", "evaluation0") 184 | eval_key1 = ctx.params.get("ekey1", "evlauation1") 185 | 186 | info_dict = samples.info 187 | if CMP_KEY_INFO_DICT_KEY not in info_dict: 188 | info_dict[CMP_KEY_INFO_DICT_KEY] = {} 189 | 190 | info_dict[CMP_KEY_INFO_DICT_KEY][cmp_key] = { 191 | "gt_field": gt_field, 192 | "pd0_field": pd0_field, 193 | "pd1_field": pd1_field, 194 | "eval_key0": eval_key0, 195 | "eval_key1": eval_key1, 196 | } 197 | samples.save() 198 | 199 | for update in analyze_match_delta( 200 | ctx, 201 | samples, 202 | gt_field, 203 | pd0_field, 204 | pd1_field, 205 | eval_key0, 206 | eval_key1, 207 | iou_thresh=0.1, 208 | cmp_key=cmp_key, 209 | ): 210 | yield update 211 | 212 | yield samples.add_dynamic_sample_fields() 213 | yield ctx.trigger("reload_dataset") 214 | 215 | 216 | def add_menu(ctx, inputs, input_name, choices_view, label, description=None): 217 | inputs.enum( 218 | input_name, 219 | choices_view.values(), 220 | required=True, 221 | label=label, 222 | description=description, 223 | view=choices_view, 224 | ) 225 | input_val = ctx.params.get(input_name, None) 226 | return input_val is not None 227 | 228 | 229 | def _compute_changes_inputs(ctx, inputs): 230 | 231 | dataset = ctx.dataset 232 | label_fields = _get_label_fields(dataset, (fo.Detections,)) 233 | label_field_choices = types.DropdownView() 234 | for field_name in sorted(label_fields): 235 | label_field_choices.add_choice(field_name, label=field_name) 236 | 237 | if not add_menu( 238 | ctx, 239 | inputs, 240 | "gt_field", 241 | label_field_choices, 242 | "Ground Truth Field", 243 | "The label field containing ground truth detections", 244 | ): 245 | return False 246 | 247 | if not add_menu( 248 | ctx, 249 | inputs, 250 | "p0_field", 251 | label_field_choices, 252 | "First Model Field", 253 | "The label field containing the first model predictions", 254 | ): 255 | return False 256 | 257 | if not add_menu( 258 | ctx, 259 | inputs, 260 | "p1_field", 261 | label_field_choices, 262 | "Second Model Field", 263 | "The label field containing the second model predictions", 264 | ): 265 | return False 266 | 267 | evals = dataset.list_evaluations() 268 | eval_field_choices = types.DropdownView() 269 | for eval in sorted(evals): 270 | eval_field_choices.add_choice(eval, label=eval) 271 | 272 | if not add_menu( 273 | ctx, 274 | inputs, 275 | "ekey0", 276 | eval_field_choices, 277 | "Evaluation Key for First Model", 278 | ): 279 | return False 280 | 281 | if not add_menu( 282 | ctx, 283 | inputs, 284 | "ekey1", 285 | eval_field_choices, 286 | "Evaluation Key for Second Model", 287 | ): 288 | return False 289 | 290 | inputs.str( 291 | "cmp_key", 292 | required=True, 293 | label="Model Comparison Key", 294 | description="Supply a key for this model comparison", 295 | ) 296 | 297 | cmp_key = ctx.params.get("cmp_key", None) 298 | if cmp_key is None: 299 | return False 300 | 301 | return types.Property( 302 | inputs, view=types.View(label="Compute Model Differences") 303 | ) 304 | 305 | 306 | def _execution_mode(ctx, inputs): 307 | delegate = ctx.params.get("delegate", False) 308 | 309 | if delegate: 310 | description = "Uncheck this box to execute the operation immediately" 311 | else: 312 | description = "Check this box to delegate execution of this task" 313 | 314 | inputs.bool( 315 | "delegate", 316 | default=False, 317 | required=True, 318 | label="Delegate execution?", 319 | description=description, 320 | view=types.CheckboxView(), 321 | ) 322 | 323 | if delegate: 324 | inputs.view( 325 | "notice", 326 | types.Notice( 327 | label=( 328 | "You've chosen delegated execution. Note that you must " 329 | "have a delegated operation service running in order for " 330 | "this task to be processed. See " 331 | "https://docs.voxel51.com/plugins/using_plugins.html#delegated-operations " 332 | "for more information" 333 | ) 334 | ), 335 | ) 336 | 337 | 338 | def _set_progress(ctx, progress, label=None): 339 | # https://github.com/voxel51/fiftyone/pull/3516 340 | # return ctx.trigger("set_progress", dict(progress=progress, label=label)) 341 | 342 | loading = types.Object() 343 | loading.float("progress", view=types.ProgressView(label=label)) 344 | return ctx.trigger( 345 | "show_output", 346 | dict( 347 | outputs=types.Property(loading).to_json(), 348 | results={"progress": progress}, 349 | ), 350 | ) 351 | 352 | 353 | def _view_changes_menu(ctx, inputs): 354 | 355 | dataset = ctx.dataset 356 | info_dict = dataset.info 357 | if CMP_KEY_INFO_DICT_KEY not in info_dict: 358 | return False 359 | 360 | label_fields = list(info_dict[CMP_KEY_INFO_DICT_KEY].keys()) 361 | label_field_choices = types.DropdownView() 362 | for field_name in sorted(label_fields): 363 | label_field_choices.add_choice(field_name, label=field_name) 364 | 365 | if not add_menu( 366 | ctx, 367 | inputs, 368 | "cmp_key", 369 | label_field_choices, 370 | "Comparison Key", 371 | "The comparison key used when Computing Model Differences", 372 | ): 373 | return False 374 | 375 | cmp_key = ctx.params.get("cmp_key", None) 376 | cmp_dict = dataset.info[CMP_KEY_INFO_DICT_KEY][cmp_key] 377 | gt_field = cmp_dict["gt_field"] 378 | gt_det_cmp_field = f"{gt_field}.detections.{cmp_key}" 379 | type_vals = dataset.distinct(gt_det_cmp_field) 380 | type_selector = types.AutocompleteView() 381 | for ty in type_vals: 382 | type_selector.add_choice(ty, label=ty) 383 | 384 | if not add_menu( 385 | ctx, 386 | inputs, 387 | "type", 388 | type_selector, 389 | "Type of change to view", # "type desc" 390 | ): 391 | return False 392 | 393 | gt_cls_field = f"{gt_field}.detections.label" 394 | gt_classes = dataset.distinct(gt_cls_field) 395 | gt_classes = [ 396 | ALL_CLASSES, 397 | ] + gt_classes 398 | class_selector = types.AutocompleteView() 399 | for cl in gt_classes: 400 | class_selector.add_choice(cl, label=cl) 401 | 402 | if not add_menu( 403 | ctx, 404 | inputs, 405 | "class", 406 | class_selector, 407 | "Class to view", 408 | ): 409 | return False 410 | 411 | return types.Property( 412 | inputs, view=types.View(label="View Model Differences") 413 | ) 414 | 415 | 416 | def _delete_comparison_menu(ctx, inputs): 417 | 418 | dataset = ctx.dataset 419 | info_dict = dataset.info 420 | if CMP_KEY_INFO_DICT_KEY not in info_dict: 421 | return False 422 | 423 | label_fields = list(info_dict[CMP_KEY_INFO_DICT_KEY].keys()) 424 | label_field_choices = types.DropdownView() 425 | for field_name in sorted(label_fields): 426 | label_field_choices.add_choice(field_name, label=field_name) 427 | 428 | if not add_menu( 429 | ctx, inputs, "cmp_key", label_field_choices, "Comparison Key" 430 | ): 431 | return False 432 | 433 | return types.Property( 434 | inputs, view=types.View(label="View Model Differences") 435 | ) 436 | 437 | 438 | class ViewChanges(foo.Operator): 439 | 440 | LABEL = "View Model Differences" 441 | 442 | @property 443 | def config(self): 444 | return foo.OperatorConfig( 445 | name="view_changes", 446 | label=ViewChanges.LABEL, 447 | dynamic=True, # execute_as_generator=True, 448 | ) 449 | 450 | def resolve_delegation(self, ctx): 451 | return ctx.params.get("delegate", False) 452 | 453 | def resolve_input(self, ctx): 454 | inputs = types.Object() 455 | 456 | ready = _view_changes_menu(ctx, inputs) 457 | # if ready: 458 | # inputs.bool( 459 | # "groupby_scene", 460 | # default=False, 461 | # required=True, 462 | # label="Group by scene?", 463 | # view=types.CheckboxView(), 464 | # ) 465 | # groupby_scene = ctx.params.get("groupby_scene", False) 466 | 467 | return types.Property(inputs, view=types.View(label=self.LABEL)) 468 | 469 | def execute(self, ctx): 470 | dataset = ctx.dataset 471 | 472 | cmp_key = ctx.params.get("cmp_key", None) 473 | type = ctx.params.get("type", None) 474 | label_class = ctx.params.get("class", None) 475 | cmp_dict = dataset.info[CMP_KEY_INFO_DICT_KEY][cmp_key] 476 | gt_field = cmp_dict["gt_field"] 477 | pd0_field = cmp_dict["pd0_field"] 478 | pd1_field = cmp_dict["pd1_field"] 479 | if label_class == ALL_CLASSES: 480 | view_expr = F(cmp_key) == type 481 | else: 482 | view_expr = (F(cmp_key) == type) & (F("label") == label_class) 483 | 484 | if type == "misshit": 485 | view = ( 486 | dataset.filter_labels(gt_field, view_expr) 487 | .filter_labels(pd1_field, view_expr) 488 | .filter_labels(pd0_field, view_expr, only_matches=False) 489 | ) 490 | elif type == "hitmiss": 491 | view = ( 492 | dataset.filter_labels(gt_field, view_expr) 493 | .filter_labels(pd0_field, view_expr) 494 | .filter_labels(pd1_field, view_expr, only_matches=False) 495 | ) 496 | elif type == "missmiss": 497 | view = ( 498 | dataset.filter_labels(gt_field, view_expr) 499 | .filter_labels(pd0_field, view_expr, only_matches=False) 500 | .filter_labels(pd1_field, view_expr, only_matches=False) 501 | ) 502 | 503 | else: 504 | view = ( 505 | dataset.filter_labels(gt_field, view_expr) 506 | .filter_labels(pd0_field, view_expr) 507 | .filter_labels(pd1_field, view_expr) 508 | ) 509 | 510 | # groupby_scene = ctx.params.get('groupby_scene',None) 511 | # if groupby_scene: 512 | # view = view.group_by('scene',order_by='frame') 513 | 514 | ctx.trigger("set_view", {"view": view._serialize()}) 515 | 516 | def resolve_output(self, ctx): 517 | outputs = types.Object() 518 | outputs.int("updated", label="Updated") 519 | return types.Property(outputs) 520 | 521 | 522 | class DeleteComparison(foo.Operator): 523 | 524 | LABEL = "Delete Model Comparison" 525 | 526 | @property 527 | def config(self): 528 | return foo.OperatorConfig( 529 | name="delete_comparison", 530 | label=DeleteComparison.LABEL, 531 | dynamic=True, 532 | ) 533 | 534 | def resolve_delegation(self, ctx): 535 | return ctx.params.get("delegate", False) 536 | 537 | def resolve_input(self, ctx): 538 | inputs = types.Object() 539 | 540 | ready = _delete_comparison_menu(ctx, inputs) 541 | 542 | return types.Property(inputs, view=types.View(label=self.LABEL)) 543 | 544 | def execute(self, ctx): 545 | dataset = ctx.dataset 546 | 547 | fields = dataset.get_field_schema(flat=True).keys() 548 | cmp_key = ctx.params.get("cmp_key", None) 549 | fields_rm = [ 550 | x for x in fields if cmp_key in x 551 | ] # Assumes unique-ish cmp_key! 552 | 553 | dataset.delete_sample_fields(fields_rm) 554 | 555 | info_dict = dataset.info 556 | info_dict[CMP_KEY_INFO_DICT_KEY].pop(cmp_key, None) 557 | 558 | ctx.trigger("reload_dataset") 559 | 560 | def resolve_output(self, ctx): 561 | outputs = types.Object() 562 | outputs.int("Success", label="Success") 563 | return types.Property(outputs) 564 | 565 | 566 | def register(p): 567 | p.register(ViewChanges) 568 | p.register(ComputeChanges) 569 | p.register(DeleteComparison) 570 | -------------------------------------------------------------------------------- /fiftyone.yaml: -------------------------------------------------------------------------------- 1 | fiftyone: 2 | version: "*" 3 | name: "@allenleetc/model_comparison" 4 | version: "1.0.0" 5 | description: Compare performance of two object detection models 6 | operators: 7 | - compute_changes 8 | - view_changes 9 | - delete_comparison 10 | --------------------------------------------------------------------------------