├── .gitignore ├── LICENSE ├── README.md ├── __pycache__ ├── resnet.cpython-37.pyc ├── resnet.cpython-38.pyc ├── vgg.cpython-37.pyc ├── vgg.cpython-38.pyc ├── wrn.cpython-37.pyc └── wrn.cpython-38.pyc ├── conf ├── cifar10.json └── imagenet.json ├── eval.py ├── eval_imagenet.py ├── figure ├── POSTER.png ├── a ├── figure_intro.png └── pptTemplate.png ├── normratio.py ├── normratio_imagenet.py ├── resnet.py ├── train.py ├── utils ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-37.pyc │ ├── __init__.cpython-38.pyc │ ├── dataset.cpython-37.pyc │ ├── dataset.cpython-38.pyc │ ├── metric.cpython-37.pyc │ └── metric.cpython-38.pyc ├── dataset.py └── metric.py ├── vgg.py └── wrn.py /.gitignore: -------------------------------------------------------------------------------- 1 | OOD_for_ImageNet/* 2 | *.txt -------------------------------------------------------------------------------- /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 | # Block Selection Method for Using Feature Norm in Out-of-distribution Detection (FeatureNorm) 2 | Official Implementation of the **"Block Selection Method for Using Feature Norm in Out-of-distribution Detection (CVPR 2023)"** by Yeonguk Yu, Sungho Shin, Seongju Lee, Changhyun Jun, and Kyoobin Lee. 3 | 4 | In this study, we propose a block selection method that utilizes the L2-norm of the activation map to detect out-of-distribution (OOD) samples. We were inspired to develop this method because we observed that the last block of neural networks can sometimes be overconfident, which can lead to deterioration in OOD detection performance. To select the block for OOD detection, we use NormRatio, which is a ratio of FeatureNorm for ID and pseudo-OOD. This ratio measures the OOD detection performance of each block. Specifically, we create Jigsaw puzzle images from ID training samples to simulate pseudo-OOD and calculate NormRatio. We choose the block with the largest value of NormRatio, which provides the biggest difference between FeatureNorm of ID and FeatureNorm of pseudo-OOD. 5 | 6 | ![concept.png](/figure/pptTemplate.png) 7 | 8 | 9 | [[ArXiv]](https://arxiv.org/abs/2212.02295) [[Presentation]](https://www.youtube.com/watch?v=prgocfj5hnc) 10 | 11 | --- 12 | Currently, this code supports for the CIFAR10 benchmark with ResNet18, WideResNet, and VGG architectures 13 | 14 | # Updates & TODO Lists 15 | - [x] FeatureNorm has been released 16 | - [ ] pretrained checkpoints 17 | - [x] Environment settings and Train & Evaluation Readme 18 | - [x] Code for all architectures 19 | 20 | 21 | # Getting Started 22 | ## Environment Setup 23 | This code is tested under Linux 20.04 and Python 3.7.7 environment, and the code requires following packages to be installed: 24 | 25 | - [Pytorch](https://pytorch.org/): Tested under 1.11.0 version of Pytorch-GPU. 26 | - [torchvision](https://pytorch.org/vision/stable/index.html): which will be installed along Pytorch. Tested under 0.6.0 version. 27 | - [timm](https://github.com/rwightman/pytorch-image-models): Tested under 0.4.12 version. 28 | - [scipy](https://www.scipy.org/): Tested under 1.4.1 version. 29 | - [scikit-learn](https://scikit-learn.org/stable/): Tested under 0.22.1 version. 30 | 31 | 32 | ## Dataset Preparation 33 | Some public datasets are required to be downloaded for running evaluation. Required dataset can be downloaded in following links as in https://github.com/wetliu/energy_ood: 34 | - [Textures](https://www.robots.ox.ac.uk/~vgg/data/dtd/) 35 | - [LSUN-C](https://www.dropbox.com/s/fhtsw1m3qxlwj6h/LSUN.tar.gz) 36 | - [LSUN-R](https://www.dropbox.com/s/moqh2wh8696c3yl/LSUN_resize.tar.gz) 37 | - [iSUN](https://www.dropbox.com/s/ssz7qxfqae0cca5/iSUN.tar.gz) 38 | 39 | ### Config file need to be changed for your path to download. For example, 40 | ~~~ 41 | # conf/cifar10.json 42 | { 43 | "epoch" : "100", 44 | "id_dataset" : "./cifar10", # Your path to Cifar10 45 | "batch_size" : 128, 46 | "save_path" : "./cifar10/", # Your path to checkpoint 47 | "num_classes" : 10 48 | } 49 | ~~~ 50 | Also, you need to change the path of the OOD dataset in "eval.py" to conduct a OOD benchmark. 51 | ~~~ 52 | OOD_results(preds_in, model, get_svhn('/SSDe/yyg/data/svhn', batch_size), device, args.method+'-SVHN', f) 53 | OOD_results(preds_in, model, get_ood('/SSDe/yyg/data/ood-set/textures/images'), device, args.method+'-TEXTURES', f) 54 | OOD_results(preds_in, model, get_ood('/SSDe/yyg/data/ood-set/LSUN'), device, args.method+'-LSUN-crop', f) 55 | OOD_results(preds_in, model, get_ood('/SSDe/yyg/data/ood-set/LSUN_resize'), device, args.method+'-LSUN-resize', f) 56 | OOD_results(preds_in, model, get_ood('/SSDe/yyg/data/ood-set/iSUN'), device, args.method+'-iSUN', f) 57 | OOD_results(preds_in, model, get_places('/SSDd/yyg/data/places256'), device, args.method+'-Places365', f) 58 | ~~~ 59 | 60 | --- 61 | ## How to Run 62 | ### To train a model by our setting (i.e., ours) with ResNet18 architecture 63 | ~~~ 64 | python train.py -d 'data_name' -g 'gpu-num' -n resnet18 -s 'save_name' 65 | ~~~ 66 | for example, 67 | ~~~ 68 | python train_baseline.py -d cifar10 -g 0 -n resnet18 -s baseline 69 | ~~~ 70 | 71 | 72 | ### To detect OOD using norm of the penultimate block 73 | ~~~ 74 | python eval.py -n resnet18 -d 'data_name' -g 'gpu_num' -s 'save_name' -m featurenorm 75 | ~~~ 76 | for example, 77 | ~~~ 78 | python eval.py -n resnet18 -d cifar10 -g 0 -s baseline 79 | ~~~ 80 | Also, you can try MSP method 81 | ~~~ 82 | python eval.py -n resnet18 -d 'data_name' -g 'gpu_num' -s 'save_name' -m msp 83 | ~~~ 84 | 85 | ### To calculate NormRatio of each block using generated Jigsaw puzzle images 86 | ~~~ 87 | python normratio.py -n resnet18 -d 'data_name' -g 'gpu_num' -s 'save_name' 88 | ~~~ 89 | for example, 90 | ~~~ 91 | python normratio.py -n resnet18 -d cifar10 -g 0 -s baseline 92 | ~~~ 93 | 94 | 95 | # License 96 | The source code of this repository is released only for academic use. See the [license](LICENSE) file for details. 97 | 98 | # Acknowledgement 99 | This work was partially supported by Institute of Information \& communications Technology Planning \& Evaluation (IITP) grant funded by the Korea government (MSIT) (No. 2022-0-00951, Development of Uncertainty-Aware Agents Learning by Asking Questions) and by ICT R\&D program of MSIT/IITP[2020-0-00857, Development of Cloud Robot Intelligence Augmentation, Sharing and Framework Technology to Integrate and Enhance the Intelligence of Multiple Robots]. 100 | 101 | # Citation 102 | ``` 103 | @InProceedings{Yu_2023_CVPR, 104 | author = {Yu, Yeonguk and Shin, Sungho and Lee, Seongju and Jun, Changhyun and Lee, Kyoobin}, 105 | title = {Block Selection Method for Using Feature Norm in Out-of-Distribution Detection}, 106 | booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, 107 | month = {June}, 108 | year = {2023}, 109 | pages = {15701-15711} 110 | } 111 | 112 | ``` 113 | -------------------------------------------------------------------------------- /__pycache__/resnet.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/__pycache__/resnet.cpython-37.pyc -------------------------------------------------------------------------------- /__pycache__/resnet.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/__pycache__/resnet.cpython-38.pyc -------------------------------------------------------------------------------- /__pycache__/vgg.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/__pycache__/vgg.cpython-37.pyc -------------------------------------------------------------------------------- /__pycache__/vgg.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/__pycache__/vgg.cpython-38.pyc -------------------------------------------------------------------------------- /__pycache__/wrn.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/__pycache__/wrn.cpython-37.pyc -------------------------------------------------------------------------------- /__pycache__/wrn.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/__pycache__/wrn.cpython-38.pyc -------------------------------------------------------------------------------- /conf/cifar10.json: -------------------------------------------------------------------------------- 1 | { 2 | "epoch" : "100", 3 | "id_dataset" : "../cifar10", 4 | "batch_size" : 128, 5 | "save_path" : "../Cifar10/", 6 | "num_classes" : 10 7 | } -------------------------------------------------------------------------------- /conf/imagenet.json: -------------------------------------------------------------------------------- 1 | { 2 | "epoch" : "100", 3 | "id_dataset" : "../data/imagenet", 4 | "batch_size" : 128, 5 | "save_path" : "../ImageNet/", 6 | "num_classes" : 1000 7 | } -------------------------------------------------------------------------------- /eval.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import timm 5 | import argparse 6 | 7 | from utils import * 8 | import resnet 9 | import wrn 10 | import vgg 11 | 12 | parser = argparse.ArgumentParser() 13 | parser.add_argument('--net','-n', default = 'resnet18', type=str) 14 | parser.add_argument('--data', '-d', type=str) 15 | parser.add_argument('--gpu', '-g', type=str) 16 | parser.add_argument('--save_path', '-s', type=str) 17 | parser.add_argument('--method' ,'-m', default = 'featurenorm', type=str) 18 | args = parser.parse_args() 19 | 20 | def calculate_norm(model, loader, device): 21 | #FeatureNorm from penultimate block 22 | model.eval() 23 | predictions = [] 24 | with torch.no_grad(): 25 | for batch_idx, (inputs, t) in enumerate(loader): 26 | x = inputs.to(device) 27 | # ResNet 28 | features = model.forward_features_blockwise(x) 29 | features = features[model.sblock] 30 | 31 | # Norm calculation 32 | norm = torch.norm(F.relu(features), dim=[2, 3]).mean(1) 33 | predictions.append(norm) 34 | predictions = torch.cat(predictions).to(device) 35 | return predictions 36 | 37 | def calculate_msp(model, loader, device): 38 | model.eval() 39 | predictions = [] 40 | with torch.no_grad(): 41 | for batch_idx, (inputs, t) in enumerate(loader): 42 | x = inputs.to(device) 43 | # ResNet 44 | x = model.conv1(x) 45 | x = model.bn1(x) 46 | x = model.act1(x) 47 | 48 | x = model.layer1[0](x) 49 | x = model.layer1[1](x) 50 | x = model.layer2[0](x) 51 | x = model.layer2[1](x) 52 | x = model.layer3[0](x) 53 | x = model.layer3[1](x) 54 | x = model.layer4[0](x) 55 | x = model.layer4[1](x) 56 | x = model.global_pool(x).view(-1, 512) 57 | x = model.fc(x) 58 | x = torch.softmax(x, dim=1).max(dim=1).values 59 | predictions.append(x) 60 | predictions = torch.cat(predictions).to(device) 61 | return predictions 62 | 63 | if args.method == 'msp': 64 | calculate_score = calculate_msp 65 | elif args.method == 'featurenorm': 66 | calculate_score = calculate_norm 67 | 68 | 69 | def OOD_results(preds_id, model, loader, device, method, file): 70 | #image_norm(loader) 71 | preds_ood = calculate_score(model, loader, device).cpu() 72 | 73 | print(torch.mean(preds_ood), torch.mean(preds_id)) 74 | show_performance(preds_id, preds_ood, method, file=file) 75 | 76 | def eval(): 77 | config = read_conf('conf/'+args.data+'.json') 78 | device = 'cuda:'+args.gpu 79 | dataset_path = config['id_dataset'] 80 | batch_size = config['batch_size'] 81 | save_path = config['save_path'] + args.save_path 82 | 83 | num_classes = int(config['num_classes']) 84 | 85 | if 'cifar' in args.data: 86 | train_loader, valid_loader = get_cifar(args.data, dataset_path, batch_size, eval=True) 87 | 88 | if 'resnet18' == args.net: 89 | model = resnet.resnet18(num_classes = num_classes) 90 | model.sblock = 6 91 | if 'wrn28' == args.net: 92 | model = wrn.WideResNet(depth=28, widen_factor=10, num_classes=num_classes) 93 | model.sblock = 10 94 | if 'vgg11' == args.net: 95 | model = vgg.VGG(vgg_name = 'VGG11', num_classes = num_classes) 96 | model.sblock = 5 97 | 98 | 99 | model.load_state_dict((torch.load(save_path+'/last.pth.tar', map_location = device)['state_dict'])) 100 | model.to(device) 101 | model.eval() 102 | 103 | f = open(save_path+'/{}_result.txt'.format(args.method), 'w') 104 | valid_accuracy = validation_accuracy(model, valid_loader, device) 105 | print(valid_accuracy) 106 | f.write('Accuracy for ValidationSet: {}\n'.format(str(valid_accuracy))) 107 | 108 | preds_in = calculate_score(model, valid_loader, device).cpu() 109 | OOD_results(preds_in, model, get_svhn('../svhn', batch_size), device, args.method+'-SVHN', f) 110 | OOD_results(preds_in, model, get_ood('../ood-set/textures/images'), device, args.method+'-TEXTURES', f) # Textures 111 | OOD_results(preds_in, model, get_ood('../ood-set/LSUN'), device, args.method+'-LSUN-crop', f) # LSUN(c) 112 | OOD_results(preds_in, model, get_ood('../ood-set/LSUN_resize'), device, args.method+'-LSUN-resize', f) #LSUN(r) 113 | OOD_results(preds_in, model, get_ood('../ood-set/iSUN'), device, args.method+'-iSUN', f) #iSUN 114 | OOD_results(preds_in, model, get_places('/SSDd/yyg/data/places256'), device, args.method+'-Places365', f) 115 | f.close() 116 | 117 | 118 | if __name__ =='__main__': 119 | eval() -------------------------------------------------------------------------------- /eval_imagenet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import timm 5 | import argparse 6 | 7 | from utils import * 8 | 9 | parser = argparse.ArgumentParser() 10 | parser.add_argument('--net','-n', default = 'resnet50', type=str) 11 | parser.add_argument('--gpu', '-g', default = '0', type=str) 12 | parser.add_argument('--save_path', '-s', default='.', type=str) 13 | parser.add_argument('--method' ,'-m', default = 'featurenorm', type=str) 14 | args = parser.parse_args() 15 | 16 | def forward_feature_resnet50(model, x): 17 | features = [] 18 | x = model.conv1(x) 19 | x = model.bn1(x) 20 | x = model.relu(x) 21 | x = model.maxpool(x) 22 | 23 | for i in range(3): 24 | x = model.layer1[i](x) 25 | features.append(x) 26 | 27 | for i in range(4): 28 | x = model.layer2[i](x) 29 | features.append(x) 30 | 31 | for i in range(6): 32 | x = model.layer3[i](x) 33 | features.append(x) 34 | 35 | for i in range(3): 36 | x = model.layer4[i](x) 37 | features.append(x) 38 | return features 39 | 40 | def forward_feature_vgg16(model, x): 41 | layers = [64, 'r', 64, 'r', "M", 128, 'r', 128, 'r', "M", 256, 'r', 256, 'r', 256, 'r', "M", 512, 'r', 512, 'r', 512, 'r', "M", 512, 'r', 512, 'r', 512, 'r', "M"] 42 | features = [] 43 | 44 | for i, layer in enumerate(layers): 45 | x = model.features[i](x) 46 | if layer == 'M': 47 | features.append(x) 48 | return features 49 | 50 | def forward_feature_mobilenetv3(model, x): 51 | features = [] 52 | for i, layer in enumerate(model.features): 53 | # print(layer, type(layer).__name__) 54 | x = model.features[i](x) 55 | features.append(x) 56 | return features 57 | 58 | 59 | def calculate_norm(model, loader, device): 60 | #FeatureNorm from the selected block 61 | if type(model).__name__ == 'ResNet': 62 | forward_features = forward_feature_resnet50 63 | elif type(model).__name__ == 'VGG': 64 | forward_features = forward_feature_vgg16 65 | elif type(model).__name__ == 'MobileNetV3': 66 | forward_features = forward_feature_mobilenetv3 67 | 68 | model.eval() 69 | predictions = [] 70 | with torch.no_grad(): 71 | for batch_idx, (inputs, t) in enumerate(loader): 72 | x = inputs.to(device) 73 | # ResNet 74 | features = forward_features(model, x) 75 | features = features[model.sblock] 76 | 77 | # Norm calculation 78 | norm = torch.norm(F.relu(features), dim=[2, 3]).mean(1) 79 | predictions.append(norm) 80 | predictions = torch.cat(predictions).to(device) 81 | return predictions 82 | 83 | def calculate_msp(model, loader, device): 84 | model.eval() 85 | predictions = [] 86 | with torch.no_grad(): 87 | for batch_idx, (inputs, t) in enumerate(loader): 88 | x = inputs.to(device) 89 | x = model(x) 90 | x = torch.softmax(x, dim=1).max(dim=1).values 91 | predictions.append(x) 92 | predictions = torch.cat(predictions).to(device) 93 | return predictions 94 | 95 | if args.method == 'msp': 96 | calculate_score = calculate_msp 97 | elif args.method == 'featurenorm': 98 | calculate_score = calculate_norm 99 | 100 | 101 | def OOD_results(preds_id, model, loader, device, method, file): 102 | #image_norm(loader) 103 | preds_ood = calculate_score(model, loader, device).cpu() 104 | 105 | print(torch.mean(preds_ood), torch.mean(preds_id)) 106 | show_performance(preds_id, preds_ood, method, file=file) 107 | 108 | def eval(): 109 | device = 'cuda:'+args.gpu 110 | num_classes = 1000 111 | 112 | if 'resnet50' == args.net: 113 | model = torchvision.models.resnet50(pretrained=True, num_classes=1000) 114 | model.sblock = 14 115 | if 'vgg16' == args.net: 116 | model = torchvision.models.vgg16(pretrained=True, num_classes=1000) 117 | model.sblock = 4 118 | if 'mobilenetv3' == args.net: 119 | model = torchvision.models.mobilenet_v3_large(pretrained=True, num_classes=1000) 120 | model.sblock = 16 121 | model.to(device) 122 | model.eval() 123 | 124 | config = read_conf('conf/imagenet.json') 125 | 126 | _, valid_loader = get_imagenet(config['id_dataset'], 32) 127 | 128 | f = open('{}/{}_result.txt'.format(args.save_path, args.net), 'w') 129 | valid_accuracy = validation_accuracy(model, valid_loader, device) 130 | print(valid_accuracy) 131 | f.write('Accuracy for ValidationSet: {}\n'.format(str(valid_accuracy))) 132 | 133 | preds_in = calculate_score(model, valid_loader, device).cpu() 134 | OOD_results(preds_in, model, get_ood('./OOD_for_ImageNet/iNaturalist', for_imagenet=True), device, args.method+'-SVHN', f) # iNaturalist 135 | OOD_results(preds_in, model, get_ood('./OOD_for_ImageNet/SUN', for_imagenet=True), device, args.method+'-SUN', f) # SUN 136 | OOD_results(preds_in, model, get_ood('./OOD_for_ImageNet/Places', for_imagenet=True), device, args.method+'-PLACES', f) # PLACES 137 | OOD_results(preds_in, model, get_ood('./OOD_for_ImageNet/dtd/images', for_imagenet=True), device, args.method+'-Textures', f) #TExtures 138 | f.close() 139 | 140 | 141 | if __name__ =='__main__': 142 | eval() -------------------------------------------------------------------------------- /figure/POSTER.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/figure/POSTER.png -------------------------------------------------------------------------------- /figure/a: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /figure/figure_intro.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/figure/figure_intro.png -------------------------------------------------------------------------------- /figure/pptTemplate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/figure/pptTemplate.png -------------------------------------------------------------------------------- /normratio.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import argparse 5 | 6 | from utils import * 7 | import resnet 8 | import wrn 9 | import vgg 10 | 11 | parser = argparse.ArgumentParser() 12 | parser.add_argument('--net','-n', default = 'resnet18', type=str) 13 | parser.add_argument('--data', '-d', type=str) 14 | parser.add_argument('--gpu', '-g', type=str) 15 | parser.add_argument('--save_path', '-s', type=str) 16 | args = parser.parse_args() 17 | 18 | def calculate_layer(model, train_loader, blur_loader, num_blocks, device): 19 | model.eval() 20 | 21 | norm_pred_ori = dict() 22 | norm_pred_jigsaw = dict() 23 | for i in range(num_blocks): 24 | norm_pred_ori[i] = [] 25 | norm_pred_jigsaw[i] = [] 26 | 27 | print(type(model).__name__, len(train_loader), len(blur_loader)) 28 | with torch.no_grad(): 29 | for batch_idx, (data1, data2) in enumerate(zip(train_loader, blur_loader)): 30 | x = torch.cat([data1[0], data2[0]], dim=0).to(device) 31 | 32 | features = model.forward_features_blockwise(x) 33 | 34 | for i in range(num_blocks): 35 | norm = torch.norm(F.relu(features[i]), dim=[2,3]).mean(1) 36 | norm_ori = norm[:len(data1[0])] 37 | norm_jigsaw = norm[len(data1[0]):] 38 | 39 | norm_pred_ori[i].append(norm_ori) 40 | norm_pred_jigsaw[i].append(norm_jigsaw) 41 | 42 | for i in range(num_blocks): 43 | norm_pred_ori[i] = torch.cat(norm_pred_ori[i], dim=0) 44 | norm_pred_jigsaw[i] = torch.cat(norm_pred_jigsaw[i], dim=0) 45 | 46 | print('NormRatio-Block{}: {}'.format(i, (norm_pred_ori[i]/norm_pred_jigsaw[i]).mean())) 47 | 48 | 49 | def eval(): 50 | config = read_conf('conf/'+args.data+'.json') 51 | device = 'cuda:'+args.gpu 52 | dataset_path = config['id_dataset'] 53 | batch_size = config['batch_size'] 54 | save_path = config['save_path'] + args.save_path 55 | 56 | num_classes = int(config['num_classes']) 57 | 58 | train_loader, jigsaw_loader = get_cifar_jigsaw(args.data, dataset_path, batch_size) 59 | 60 | 61 | if 'resnet' in args.net: 62 | model = resnet.resnet18(num_classes=num_classes) 63 | num_blocks = 8 64 | if 'wrn28' == args.net: 65 | model = wrn.WideResNet(depth=28, widen_factor=10, num_classes=num_classes) 66 | num_blocks = 12 67 | if 'vgg11' == args.net: 68 | model = vgg.VGG(vgg_name = 'VGG11', num_classes = num_classes) 69 | num_blocks = 8 70 | model.load_state_dict((torch.load(save_path+'/last.pth.tar', map_location = device)['state_dict'])) 71 | model.to(device) 72 | model.eval() 73 | 74 | print(model) 75 | calculate_layer(model, train_loader, jigsaw_loader, num_blocks, device) 76 | 77 | 78 | if __name__ =='__main__': 79 | eval() -------------------------------------------------------------------------------- /normratio_imagenet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import argparse 5 | 6 | from utils import * 7 | import resnet 8 | import wrn 9 | import vgg 10 | 11 | parser = argparse.ArgumentParser() 12 | parser.add_argument('--net','-n', default = 'resnet50', type=str) 13 | parser.add_argument('--gpu', '-g', default = '0', type=str) 14 | parser.add_argument('--save_path', '-s', default='.', type=str) 15 | args = parser.parse_args() 16 | 17 | def forward_feature_resnet50(model, x): 18 | features = [] 19 | x = model.conv1(x) 20 | x = model.bn1(x) 21 | x = model.relu(x) 22 | x = model.maxpool(x) 23 | 24 | for i in range(3): 25 | x = model.layer1[i](x) 26 | features.append(x) 27 | 28 | for i in range(4): 29 | x = model.layer2[i](x) 30 | features.append(x) 31 | 32 | for i in range(6): 33 | x = model.layer3[i](x) 34 | features.append(x) 35 | 36 | for i in range(3): 37 | x = model.layer4[i](x) 38 | features.append(x) 39 | return features 40 | 41 | def forward_feature_vgg16(model, x): 42 | layers = [64, 'r', 64, 'r', "M", 128, 'r', 128, 'r', "M", 256, 'r', 256, 'r', 256, 'r', "M", 512, 'r', 512, 'r', 512, 'r', "M", 512, 'r', 512, 'r', 512, 'r', "M"] 43 | features = [] 44 | 45 | for i, layer in enumerate(layers): 46 | x = model.features[i](x) 47 | if layer == 'M': 48 | features.append(x) 49 | return features 50 | 51 | def forward_feature_mobilenetv3(model, x): 52 | features = [] 53 | for i, layer in enumerate(model.features): 54 | # print(layer, type(layer).__name__) 55 | x = model.features[i](x) 56 | features.append(x) 57 | return features 58 | 59 | def calculate_layer(model, train_loader, jigsaw_loader, device): 60 | model.eval() 61 | if type(model).__name__ == 'ResNet': 62 | forward_features = forward_feature_resnet50 63 | num_blocks = 16 64 | elif type(model).__name__ == 'VGG': 65 | forward_features = forward_feature_vgg16 66 | num_blocks = 5 67 | elif type(model).__name__ == 'MobileNetV3': 68 | forward_features = forward_feature_mobilenetv3 69 | num_blocks = 17 70 | 71 | norm_pred_ori = dict() 72 | norm_pred_jigsaw = dict() 73 | for i in range(num_blocks): 74 | norm_pred_ori[i] = [] 75 | norm_pred_jigsaw[i] = [] 76 | 77 | print(type(model).__name__, len(train_loader), len(jigsaw_loader)) 78 | with torch.no_grad(): 79 | for batch_idx, (data1, data2) in enumerate(zip(train_loader, jigsaw_loader)): 80 | if batch_idx > 100: # For fast calculation 81 | break 82 | x = torch.cat([data1[0], data2[0]], dim=0).to(device) 83 | 84 | features = forward_features(model, x) 85 | 86 | for i in range(num_blocks): 87 | norm = torch.norm(F.relu(features[i]), dim=[2,3]).mean(1) 88 | norm_ori = norm[:len(data1[0])] 89 | norm_jigsaw = norm[len(data1[0]):] 90 | 91 | norm_pred_ori[i].append(norm_ori) 92 | norm_pred_jigsaw[i].append(norm_jigsaw) 93 | 94 | for i in range(num_blocks): 95 | norm_pred_ori[i] = torch.cat(norm_pred_ori[i], dim=0) 96 | norm_pred_jigsaw[i] = torch.cat(norm_pred_jigsaw[i], dim=0) 97 | 98 | print('NormRatio-Block{}: {}'.format(i, (norm_pred_ori[i]/norm_pred_jigsaw[i]).mean())) 99 | 100 | 101 | def eval(): 102 | config = read_conf('conf/imagenet.json') 103 | device = 'cuda:'+args.gpu 104 | dataset_path = config['id_dataset'] 105 | batch_size = config['batch_size'] 106 | 107 | train_loader, jigsaw_loader = get_imagenet_jigsaw(dataset_path, batch_size) 108 | 109 | 110 | if 'resnet50' == args.net: 111 | model = torchvision.models.resnet50(pretrained=True, num_classes=1000) 112 | if 'vgg16' == args.net: 113 | model = torchvision.models.vgg16(pretrained=True, num_classes=1000) 114 | if 'mobilenetv3' == args.net: 115 | model = torchvision.models.mobilenet_v3_large(pretrained=True, num_classes=1000) 116 | model.to(device) 117 | model.eval() 118 | 119 | calculate_layer(model, train_loader, jigsaw_loader, device) 120 | 121 | 122 | if __name__ =='__main__': 123 | eval() -------------------------------------------------------------------------------- /resnet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | 6 | class BasicBlock(nn.Module): 7 | expansion = 1 8 | 9 | def __init__(self, in_planes, planes, stride=1, is_last=False): 10 | super(BasicBlock, self).__init__() 11 | self.is_last = is_last 12 | self.conv1 = nn.Conv2d( 13 | in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False 14 | ) 15 | self.bn1 = nn.BatchNorm2d(planes) 16 | self.conv2 = nn.Conv2d( 17 | planes, planes, kernel_size=3, stride=1, padding=1, bias=False 18 | ) 19 | self.bn2 = nn.BatchNorm2d(planes) 20 | 21 | self.shortcut = nn.Sequential() 22 | if stride != 1 or in_planes != self.expansion * planes: 23 | self.shortcut = nn.Sequential( 24 | nn.Conv2d( 25 | in_planes, 26 | self.expansion * planes, 27 | kernel_size=1, 28 | stride=stride, 29 | bias=False, 30 | ), 31 | nn.BatchNorm2d(self.expansion * planes), 32 | ) 33 | 34 | def forward(self, x): 35 | out = F.relu(self.bn1(self.conv1(x))) 36 | out = self.bn2(self.conv2(out)) 37 | out += self.shortcut(x) 38 | preact = out 39 | out = F.relu(out) 40 | if self.is_last: 41 | return out, preact 42 | else: 43 | return out 44 | 45 | class Bottleneck(nn.Module): 46 | expansion = 4 47 | 48 | def __init__(self, in_planes, planes, stride=1, is_last=False): 49 | super(Bottleneck, self).__init__() 50 | self.is_last = is_last 51 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) 52 | self.bn1 = nn.BatchNorm2d(planes) 53 | self.conv2 = nn.Conv2d( 54 | planes, planes, kernel_size=3, stride=stride, padding=1, bias=False 55 | ) 56 | self.bn2 = nn.BatchNorm2d(planes) 57 | self.conv3 = nn.Conv2d( 58 | planes, self.expansion * planes, kernel_size=1, bias=False 59 | ) 60 | self.bn3 = nn.BatchNorm2d(self.expansion * planes) 61 | 62 | self.shortcut = nn.Sequential() 63 | if stride != 1 or in_planes != self.expansion * planes: 64 | self.shortcut = nn.Sequential( 65 | nn.Conv2d( 66 | in_planes, 67 | self.expansion * planes, 68 | kernel_size=1, 69 | stride=stride, 70 | bias=False, 71 | ), 72 | nn.BatchNorm2d(self.expansion * planes), 73 | ) 74 | 75 | def forward(self, x): 76 | out = F.relu(self.bn1(self.conv1(x))) 77 | out = F.relu(self.bn2(self.conv2(out))) 78 | out = self.bn3(self.conv3(out)) 79 | out += self.shortcut(x) 80 | preact = out 81 | out = F.relu(out) 82 | if self.is_last: 83 | return out, preact 84 | else: 85 | return out 86 | 87 | 88 | class ResNet(nn.Module): 89 | def __init__(self, block, num_blocks, in_channel=3, num_classes = 10, zero_init_residual=False): 90 | super(ResNet, self).__init__() 91 | self.in_planes = 64 92 | 93 | self.conv1 = nn.Conv2d( 94 | in_channel, 64, kernel_size=3, stride=1, padding=2, bias=False 95 | ) 96 | self.bn1 = nn.BatchNorm2d(64) 97 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) 98 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) 99 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) 100 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) 101 | self.global_pool = nn.AdaptiveAvgPool2d((1, 1)) 102 | self.fc = nn.Linear(512, num_classes) 103 | self.act1 = nn.ReLU() 104 | 105 | for m in self.modules(): 106 | if isinstance(m, nn.Conv2d): 107 | nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") 108 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 109 | nn.init.constant_(m.weight, 1) 110 | nn.init.constant_(m.bias, 0) 111 | 112 | # Zero-initialize the last BN in each residual branch, 113 | # so that the residual branch starts with zeros, and each residual block behaves 114 | # like an identity. This improves the model by 0.2~0.3% according to: 115 | # https://arxiv.org/abs/1706.02677 116 | if zero_init_residual: 117 | for m in self.modules(): 118 | if isinstance(m, Bottleneck): 119 | nn.init.constant_(m.bn3.weight, 0) 120 | elif isinstance(m, BasicBlock): 121 | nn.init.constant_(m.bn2.weight, 0) 122 | 123 | def _make_layer(self, block, planes, num_blocks, stride): 124 | strides = [stride] + [1] * (num_blocks - 1) 125 | layers = [] 126 | for i in range(num_blocks): 127 | stride = strides[i] 128 | layers.append(block(self.in_planes, planes, stride)) 129 | self.in_planes = planes * block.expansion 130 | return nn.Sequential(*layers) 131 | 132 | def forward(self, x): 133 | out = self.forward_features(x) 134 | out = self.global_pool(out) 135 | out = torch.flatten(out, 1) 136 | return self.fc(out) 137 | 138 | def forward_features(self, x): 139 | out = F.relu(self.bn1(self.conv1(x))) 140 | out = self.layer1(out) 141 | out = self.layer2(out) 142 | out = self.layer3(out) 143 | out = self.layer4(out) 144 | out_ = self.global_pool(out) 145 | out_ = torch.flatten(out_, 1) 146 | return out 147 | 148 | def forward_features_blockwise(self, x): 149 | features = [] 150 | x = self.conv1(x) 151 | x = self.bn1(x) 152 | x = self.act1(x) 153 | 154 | x = self.layer1[0](x) 155 | features.append(x) 156 | x = self.layer1[1](x) 157 | features.append(x) 158 | 159 | x = self.layer2[0](x) 160 | features.append(x) 161 | x = self.layer2[1](x) 162 | features.append(x) 163 | 164 | x = self.layer3[0](x) 165 | features.append(x) 166 | x = self.layer3[1](x) 167 | features.append(x) 168 | 169 | x = self.layer4[0](x) 170 | features.append(x) 171 | x = self.layer4[1](x) 172 | features.append(x) 173 | return features 174 | 175 | def resnet18(**kwargs): 176 | return ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) 177 | 178 | def resnet34(**kwargs): 179 | return ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) 180 | 181 | def resnet50(**kwargs): 182 | return ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) 183 | 184 | def resnet101(**kwargs): 185 | return ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import torchvision 4 | import argparse 5 | import numpy as np 6 | import timm 7 | 8 | import utils 9 | import resnet 10 | import wrn 11 | import vgg 12 | 13 | torch.manual_seed(0) 14 | 15 | def train(): 16 | parser = argparse.ArgumentParser() 17 | parser.add_argument('--net','-n', default = 'resnet18', type=str) 18 | parser.add_argument('--data', '-d', type=str) 19 | parser.add_argument('--gpu', '-g', default = '0', type=str) 20 | parser.add_argument('--save_path', '-s', type=str) 21 | 22 | args = parser.parse_args() 23 | 24 | config = utils.read_conf('conf/'+args.data+'.json') 25 | device = 'cuda:'+args.gpu 26 | 27 | model_name = args.net 28 | dataset_path = config['id_dataset'] 29 | save_path = config['save_path'] + args.save_path 30 | num_classes = int(config['num_classes']) 31 | class_range = list(range(0, num_classes)) 32 | 33 | if args.net == 'resnet18': 34 | batch_size = int(config['batch_size']) 35 | max_epoch = int(config['epoch']) 36 | wd = 5e-04 37 | lrde = [50, 75, 90] 38 | lr = 0.1 39 | if args.net == 'wrn28': 40 | batch_size = int(config['batch_size']) 41 | max_epoch = 200 42 | wd = 5e-04 43 | lrde = [100, 150] 44 | lr = 0.1 45 | if args.net == 'vgg11': 46 | batch_size = int(config['batch_size']) 47 | max_epoch = int(config['epoch']) 48 | wd = 5e-04 49 | lrde = [50, 75, 90] 50 | lr = 0.05 51 | 52 | print(model_name, dataset_path.split('/')[-2], batch_size, class_range) 53 | 54 | if not os.path.exists(config['save_path']): 55 | os.mkdir(config['save_path']) 56 | if not os.path.exists(save_path): 57 | os.mkdir(save_path) 58 | else: 59 | raise ValueError('save_path already exists') 60 | 61 | if 'cifar' in args.data: 62 | train_loader, valid_loader = utils.get_cifar(args.data, dataset_path, batch_size) 63 | 64 | if 'resnet18' == args.net: 65 | model = resnet.resnet18(num_classes = num_classes) 66 | if 'wrn28' == args.net: 67 | model = wrn.WideResNet(depth=28, widen_factor=10, num_classes=num_classes) 68 | if 'vgg11' == args.net: 69 | model = vgg.VGG(vgg_name = 'VGG11', num_classes = num_classes) 70 | model.to(device) 71 | 72 | criterion = torch.nn.CrossEntropyLoss() 73 | optimizer = torch.optim.SGD(model.parameters(), lr = lr, momentum=0.9, weight_decay = wd) 74 | 75 | scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, lrde) 76 | saver = timm.utils.CheckpointSaver(model, optimizer, checkpoint_dir= save_path, max_history = 2) 77 | 78 | for epoch in range(max_epoch): 79 | ## training 80 | model.train() 81 | total_loss = 0 82 | total = 0 83 | correct = 0 84 | for batch_idx, (inputs, targets) in enumerate(train_loader): 85 | inputs, targets = inputs.to(device), targets.to(device) 86 | optimizer.zero_grad() 87 | 88 | outputs = model(inputs) 89 | loss = criterion(outputs, targets) 90 | 91 | loss.backward() 92 | optimizer.step() 93 | 94 | total_loss += loss 95 | total += targets.size(0) 96 | _, predicted = outputs.max(1) 97 | correct += predicted.eq(targets).sum().item() 98 | print('\r', batch_idx, len(train_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)' 99 | % (total_loss/(batch_idx+1), 100.*correct/total, correct, total), end = '') 100 | train_accuracy = correct/total 101 | train_avg_loss = total_loss/len(train_loader) 102 | print() 103 | 104 | ## validation 105 | model.eval() 106 | total_loss = 0 107 | total = 0 108 | correct = 0 109 | valid_accuracy = utils.validation_accuracy(model, valid_loader, device) 110 | scheduler.step() 111 | 112 | saver.save_checkpoint(epoch, metric = valid_accuracy) 113 | print('EPOCH {:4}, TRAIN [loss - {:.4f}, acc - {:.4f}], VALID [acc - {:.4f}]\n'.format(epoch, train_avg_loss, train_accuracy, valid_accuracy)) 114 | print(scheduler.get_last_lr()) 115 | if __name__ =='__main__': 116 | train() -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .dataset import * 2 | from .metric import * -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/utils/__pycache__/__init__.cpython-37.pyc -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/utils/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /utils/__pycache__/dataset.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/utils/__pycache__/dataset.cpython-37.pyc -------------------------------------------------------------------------------- /utils/__pycache__/dataset.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/utils/__pycache__/dataset.cpython-38.pyc -------------------------------------------------------------------------------- /utils/__pycache__/metric.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/utils/__pycache__/metric.cpython-37.pyc -------------------------------------------------------------------------------- /utils/__pycache__/metric.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gist-ailab/block-selection-for-OOD-detection/da4244ce26738d891c9bb87420157b02d350b8bd/utils/__pycache__/metric.cpython-38.pyc -------------------------------------------------------------------------------- /utils/dataset.py: -------------------------------------------------------------------------------- 1 | import json 2 | import torch.utils.data as data 3 | import torch 4 | import random 5 | 6 | import torchvision 7 | from torchvision import transforms 8 | from torchvision import datasets as dset 9 | 10 | mean = (0.5, 0.5, 0.5) 11 | std = (0.5, 0.5, 0.5) 12 | 13 | size = 32 14 | 15 | train_transform_cifar = transforms.Compose([transforms.Resize([size,size]), transforms.RandomHorizontalFlip(), transforms.RandomCrop(size, padding=4), 16 | transforms.ToTensor(), transforms.Normalize(mean=mean, std=std)]) 17 | test_transform_cifar = transforms.Compose([transforms.Resize([size,size]), transforms.ToTensor(), transforms.Normalize(mean=mean, std=std)])#, ) 18 | 19 | train_transform = transforms.Compose([transforms.Resize([224,224]), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) 20 | test_transform = transforms.Compose([transforms.Resize([224,224]), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) 21 | 22 | class jigsaw_dataset(data.Dataset): 23 | def __init__(self, dataset): 24 | self.dataset = dataset 25 | 26 | def __len__(self): 27 | return len(self.dataset) 28 | 29 | def __getitem__(self, index): 30 | x, y = self.dataset[index] 31 | 32 | s = int(float(x.size(1)) / 3) 33 | 34 | 35 | x_ = torch.zeros_like(x) 36 | tiles_order = random.sample(range(9), 9) 37 | for o, tile in enumerate(tiles_order): 38 | i = int(o/3) 39 | j = int(o%3) 40 | 41 | ti = int(tile/3) 42 | tj = int(tile%3) 43 | # print(i, j, ti, tj) 44 | x_[:, i*s:(i+1)*s, j*s:(j+1)*s] = x[:, ti*s:(ti+1)*s, tj*s:(tj+1)*s] 45 | return x_, y 46 | 47 | def get_cifar_jigsaw(dataset, folder, batch_size, test=False): 48 | test_transform_cifar = transforms.Compose([transforms.Resize([size,size]), transforms.ToTensor()]) 49 | train_ = not test 50 | 51 | if dataset == 'cifar10': 52 | train_data = dset.CIFAR10(folder, train=train_, transform=test_transform_cifar, download=True) 53 | test_data = dset.CIFAR10(folder, train=train_, transform=test_transform_cifar, download=True) 54 | 55 | jigsaw = jigsaw_dataset(test_data) 56 | 57 | train_loader = torch.utils.data.DataLoader(train_data, batch_size, shuffle=False, pin_memory=True, num_workers = 4) 58 | jigsaw_loader = torch.utils.data.DataLoader(jigsaw, batch_size, shuffle=False, pin_memory=True, num_workers = 4) 59 | 60 | return train_loader, jigsaw_loader 61 | 62 | 63 | def get_imagenet_jigsaw(imagenet_path, batch_size, test=False): 64 | # test_transform = transforms.Compose([transforms.Resize([size,size]), transforms.ToTensor()]) 65 | 66 | train_data = torchvision.datasets.ImageFolder(imagenet_path+'/train', test_transform) 67 | test_data = torchvision.datasets.ImageFolder(imagenet_path+'/train', test_transform) 68 | 69 | jigsaw = jigsaw_dataset(test_data) 70 | 71 | train_loader = torch.utils.data.DataLoader(train_data, batch_size, shuffle=False, pin_memory=True, num_workers = 4) 72 | jigsaw_loader = torch.utils.data.DataLoader(jigsaw, batch_size, shuffle=False, pin_memory=True, num_workers = 4) 73 | 74 | return train_loader, jigsaw_loader 75 | 76 | def read_conf(json_path): 77 | """ 78 | read json and return the configure as dictionary. 79 | """ 80 | with open(json_path) as json_file: 81 | config = json.load(json_file) 82 | return config 83 | 84 | def get_cifar(dataset, folder, batch_size, eval=False): 85 | if eval==True: 86 | train_transform_cifar_ = test_transform_cifar 87 | else: 88 | train_transform_cifar_ = train_transform_cifar 89 | if dataset == 'cifar10': 90 | train_data = dset.CIFAR10(folder, train=True, transform=train_transform_cifar_, download=True) 91 | test_data = dset.CIFAR10(folder, train=False, transform=test_transform_cifar, download=True) 92 | num_classes = 10 93 | 94 | train_loader = torch.utils.data.DataLoader(train_data, batch_size, shuffle=True, pin_memory=True, num_workers = 4) 95 | valid_loader = torch.utils.data.DataLoader(test_data, batch_size, shuffle=False, pin_memory=True, num_workers = 4) 96 | 97 | return train_loader, valid_loader 98 | 99 | def get_svhn(folder, batch_size, transform_imagenet = False): 100 | test_data = dset.SVHN(folder, split='test', transform=test_transforms if transform_imagenet else test_transform_cifar, download=True) 101 | valid_loader = torch.utils.data.DataLoader(test_data, batch_size, shuffle=False, pin_memory=True, num_workers = 4) 102 | return valid_loader 103 | 104 | 105 | def get_ood(path, for_imagenet = False): 106 | if for_imagenet: 107 | test_transform_cifar = test_transform 108 | ood_data = torchvision.datasets.ImageFolder(path, test_transform_cifar) 109 | ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=100, shuffle=False, pin_memory=True) 110 | return ood_loader 111 | 112 | def get_imagenet(imagenet_path, batch_size=32, eval=False): 113 | train_trans = train_transform 114 | test_trans = test_transform 115 | if eval: 116 | train_trans = test_transform 117 | 118 | trainset = torchvision.datasets.ImageFolder(imagenet_path+'/train', train_trans) 119 | testset = torchvision.datasets.ImageFolder(imagenet_path+'/val', test_trans) 120 | # trainset = jigsaw_dataset(trainset) 121 | 122 | train_loader = torch.utils.data.DataLoader(trainset, batch_size, shuffle=False, pin_memory=True, num_workers = 8) 123 | valid_loader = torch.utils.data.DataLoader(testset, batch_size, shuffle=False, pin_memory=True, num_workers = 8) 124 | return train_loader, valid_loader 125 | 126 | 127 | def get_places(path): 128 | ood_data = torchvision.datasets.ImageFolder(path, test_transform_cifar) 129 | 130 | random.seed(0) 131 | ood_data.samples = random.sample(ood_data.samples, 10000) 132 | 133 | ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=100, shuffle=False, pin_memory=True) 134 | return ood_loader 135 | 136 | if __name__ == '__main__': 137 | pass -------------------------------------------------------------------------------- /utils/metric.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import numpy as np 3 | from sklearn.metrics import roc_auc_score 4 | import sklearn.metrics as sk 5 | 6 | import torch.nn.functional as F 7 | 8 | recall_level_default = 0.95 9 | 10 | def validation_accuracy(model, loader, device): 11 | total = 0 12 | correct = 0 13 | 14 | model.eval() 15 | with torch.no_grad(): 16 | for batch_idx, (inputs, targets) in enumerate(loader): 17 | inputs, targets = inputs.to(device), targets.to(device) 18 | outputs = model(inputs) 19 | #print(outputs.shape) 20 | total += targets.size(0) 21 | _, predicted = outputs.max(1) 22 | correct += predicted.eq(targets).sum().item() 23 | valid_accuracy = correct/total 24 | return valid_accuracy 25 | 26 | def validation_accuracy_norm(model, loader, device): 27 | total = 0 28 | correct = 0 29 | 30 | model.eval() 31 | with torch.no_grad(): 32 | for batch_idx, (inputs, targets) in enumerate(loader): 33 | inputs, targets = inputs.to(device), targets.to(device) 34 | x = model.conv1(inputs) 35 | x = model.bn1(x) 36 | x = model.act1(x) 37 | x = model.maxpool(x) 38 | 39 | x = model.layer1(x) 40 | x = model.layer2(x) 41 | x = model.layer3(x) 42 | xgap = F.adaptive_avg_pool2d(x, [1,1]) 43 | norm = torch.norm(xgap, dim=1, keepdim=True) 44 | x = x/norm 45 | # x = attention(x) 46 | 47 | x = model.layer4(x) # Batch, 512, 4, 4 48 | x = model.global_pool(x).view(-1, 512) 49 | outputs = model.fc(x) 50 | #print(outputs.shape) 51 | total += targets.size(0) 52 | _, predicted = outputs.max(1) 53 | correct += predicted.eq(targets).sum().item() 54 | valid_accuracy = correct/total 55 | return valid_accuracy 56 | 57 | def validation_accuracy_norm_wrn(model, loader, device): 58 | total = 0 59 | correct = 0 60 | 61 | model.eval() 62 | with torch.no_grad(): 63 | for batch_idx, (inputs, targets) in enumerate(loader): 64 | inputs, targets = inputs.to(device), targets.to(device) 65 | out = model.conv1(inputs) 66 | out = model.block1(out) 67 | out = model.block2(out) 68 | 69 | out = model.block3.layer[0].bn1(out) 70 | out = model.block3.layer[0].relu1(out) 71 | outgap = F.adaptive_avg_pool2d(out, [1,1]) 72 | norm = torch.norm(outgap, dim=1, keepdim=True) 73 | out = out/norm 74 | 75 | out2 = out 76 | 77 | out = model.block3.layer[0].conv1(out) 78 | out = model.block3.layer[0].bn2(out) 79 | out = model.block3.layer[0].relu2(out) 80 | out = model.block3.layer[0].conv2(out) 81 | out = torch.add(model.block3.layer[0].convShortcut(out2), out) 82 | 83 | # out = model.block3.layer[0](out) 84 | out = model.block3.layer[1](out) 85 | out = model.block3.layer[2](out) 86 | out = model.block3.layer[3](out) 87 | # out = model.block3.layer[4](out) 88 | # out = model.block3.layer[5](out) 89 | 90 | 91 | out = model.relu(model.bn1(out)) 92 | out = F.avg_pool2d(out, 8) 93 | out = out.view(-1, model.nChannels) 94 | outputs = model.fc(out) 95 | #print(outputs.shape) 96 | total += targets.size(0) 97 | _, predicted = outputs.max(1) 98 | correct += predicted.eq(targets).sum().item() 99 | valid_accuracy = correct/total 100 | return valid_accuracy 101 | 102 | 103 | 104 | def stable_cumsum(arr, rtol=1e-05, atol=1e-08): 105 | """Use high precision for cumsum and check that final value matches sum 106 | Parameters 107 | ---------- 108 | arr : array-like 109 | To be cumulatively summed as flat 110 | rtol : float 111 | Relative tolerance, see ``np.allclose`` 112 | atol : float 113 | Absolute tolerance, see ``np.allclose`` 114 | """ 115 | out = np.cumsum(arr, dtype=np.float64) 116 | expected = np.sum(arr, dtype=np.float64) 117 | if not np.allclose(out[-1], expected, rtol=rtol, atol=atol): 118 | raise RuntimeError('cumsum was found to be unstable: ' 119 | 'its last element does not correspond to sum') 120 | return out 121 | 122 | 123 | def fpr_and_fdr_at_recall(y_true, y_score, recall_level=recall_level_default, pos_label=None): 124 | classes = np.unique(y_true) 125 | if (pos_label is None and 126 | not (np.array_equal(classes, [0, 1]) or 127 | np.array_equal(classes, [-1, 1]) or 128 | np.array_equal(classes, [0]) or 129 | np.array_equal(classes, [-1]) or 130 | np.array_equal(classes, [1]))): 131 | raise ValueError("Data is not binary and pos_label is not specified") 132 | elif pos_label is None: 133 | pos_label = 1. 134 | 135 | # make y_true a boolean vector 136 | y_true = (y_true == pos_label) 137 | 138 | # sort scores and corresponding truth values 139 | desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1] 140 | y_score = y_score[desc_score_indices] 141 | y_true = y_true[desc_score_indices] 142 | 143 | # y_score typically has many tied values. Here we extract 144 | # the indices associated with the distinct values. We also 145 | # concatenate a value for the end of the curve. 146 | distinct_value_indices = np.where(np.diff(y_score))[0] 147 | threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1] 148 | 149 | # accumulate the true positives with decreasing threshold 150 | tps = stable_cumsum(y_true)[threshold_idxs] 151 | fps = 1 + threshold_idxs - tps # add one because of zero-based indexing 152 | 153 | thresholds = y_score[threshold_idxs] 154 | 155 | recall = tps / tps[-1] 156 | 157 | last_ind = tps.searchsorted(tps[-1]) 158 | sl = slice(last_ind, None, -1) # [last_ind::-1] 159 | recall, fps, tps, thresholds = np.r_[recall[sl], 1], np.r_[fps[sl], 0], np.r_[tps[sl], 0], thresholds[sl] 160 | 161 | cutoff = np.argmin(np.abs(recall - recall_level)) 162 | 163 | return fps[cutoff] / (np.sum(np.logical_not(y_true))) # , fps[cutoff]/(fps[cutoff] + tps[cutoff]) 164 | 165 | 166 | def get_measures(_pos, _neg, recall_level=recall_level_default): 167 | pos = np.array(_pos[:]).reshape((-1, 1)) 168 | neg = np.array(_neg[:]).reshape((-1, 1)) 169 | examples = np.squeeze(np.vstack((pos, neg))) 170 | labels = np.zeros(len(examples), dtype=np.int32) 171 | labels[:len(pos)] += 1 172 | 173 | auroc = sk.roc_auc_score(labels, examples) 174 | aupr = sk.average_precision_score(labels, examples) 175 | fpr = fpr_and_fdr_at_recall(labels, examples, recall_level) 176 | 177 | return auroc, aupr, fpr 178 | 179 | 180 | def show_performance(pos, neg, method_name='Ours', recall_level=recall_level_default, file=None): 181 | ''' 182 | :param pos: 1's class, class to detect, outliers, or wrongly predicted 183 | example scores 184 | :param neg: 0's class scores 185 | ''' 186 | 187 | auroc, aupr, fpr = get_measures(pos[:], neg[:], recall_level) 188 | 189 | print('\t\t\t' + method_name) 190 | print('FPR{:d}:\t\t\t{:.2f}'.format(int(100 * recall_level), 100 * fpr)) 191 | print('AUROC:\t\t\t{:.2f}'.format(100 * auroc)) 192 | print('AUPR:\t\t\t{:.2f}'.format(100 * aupr)) 193 | # print('FDR{:d}:\t\t\t{:.2f}'.format(int(100 * recall_level), 100 * fdr)) 194 | if not file is None: 195 | file.write('{}\n'.format(method_name)) 196 | file.write('FPR{:d}:\t\t\t{:.2f}\n'.format(int(100 * recall_level), 100 * fpr)) 197 | file.write('AUROC:\t\t\t{:.2f}\n'.format(100 * auroc)) 198 | file.write('AUPR:\t\t\t{:.2f}\n'.format(100 * aupr)) 199 | file.write('\n') 200 | 201 | 202 | def print_measures(auroc, aupr, fpr, method_name='Ours', recall_level=recall_level_default): 203 | print('\t\t\t\t' + method_name) 204 | print(' FPR{:d} AUROC AUPR'.format(int(100*recall_level))) 205 | print('& {:.2f} & {:.2f} & {:.2f}'.format(100*fpr, 100*auroc, 100*aupr)) 206 | #print('FPR{:d}:\t\t\t{:.2f}'.format(int(100 * recall_level), 100 * fpr)) 207 | #print('AUROC: \t\t\t{:.2f}'.format(100 * auroc)) 208 | #print('AUPR: \t\t\t{:.2f}'.format(100 * aupr)) 209 | 210 | 211 | def print_measures_with_std(aurocs, auprs, fprs, method_name='Ours', recall_level=recall_level_default): 212 | print('\t\t\t\t' + method_name) 213 | print(' FPR{:d} AUROC AUPR'.format(int(100*recall_level))) 214 | print('& {:.2f} & {:.2f} & {:.2f}'.format(100*np.mean(fprs), 100*np.mean(aurocs), 100*np.mean(auprs))) 215 | print('& {:.2f} & {:.2f} & {:.2f}'.format(100*np.std(fprs), 100*np.std(aurocs), 100*np.std(auprs))) 216 | #print('FPR{:d}:\t\t\t{:.2f}\t+/- {:.2f}'.format(int(100 * recall_level), 100 * np.mean(fprs), 100 * np.std(fprs))) 217 | #print('AUROC: \t\t\t{:.2f}\t+/- {:.2f}'.format(100 * np.mean(aurocs), 100 * np.std(aurocs))) 218 | #print('AUPR: \t\t\t{:.2f}\t+/- {:.2f}'.format(100 * np.mean(auprs), 100 * np.std(auprs))) 219 | -------------------------------------------------------------------------------- /vgg.py: -------------------------------------------------------------------------------- 1 | '''VGG11/13/16/19 in Pytorch.''' 2 | import torch 3 | import torch.nn as nn 4 | import math 5 | 6 | cfg = { 7 | 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 8 | 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 9 | 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], 10 | 'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'], 11 | } 12 | 13 | 14 | class VGG(nn.Module): 15 | def __init__(self, vgg_name, num_classes): 16 | super(VGG, self).__init__() 17 | self.features = self._make_layers(cfg[vgg_name]) 18 | 19 | self.classifier = nn.Sequential( 20 | nn.Linear(512, 512), 21 | nn.ReLU(True), 22 | nn.Dropout(p=0.5), 23 | nn.Linear(512 , 512), 24 | nn.ReLU(True), 25 | nn.Dropout(p=0.5), 26 | nn.Linear(512, num_classes) 27 | ) 28 | # # Initialize weights 29 | for m in self.modules(): 30 | if isinstance(m, nn.Conv2d): 31 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 32 | m.weight.data.normal_(0, math.sqrt(2. / n)) 33 | m.bias.data.zero_() # for bias 34 | 35 | def forward(self, x): 36 | out = self.forward_features(x) 37 | out = self.classifier(out) 38 | return out 39 | 40 | def forward_features(self,x): 41 | out = self.features(x) 42 | return out.view(out.size(0), -1) 43 | 44 | def _make_layers(self, cfg): 45 | layers = [] 46 | in_channels = 3 47 | for x in cfg: 48 | if x == 'M': 49 | layers += [nn.MaxPool2d(kernel_size=2, stride=2)] 50 | else: 51 | layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1 ,bias=True), #bias=False 52 | nn.ReLU(inplace=True)] 53 | in_channels = x 54 | layers += [nn.AvgPool2d(kernel_size=1, stride=1)] 55 | return nn.Sequential(*layers) 56 | 57 | def forward_features_blockwise(self, x): 58 | # VGG11 forward features 59 | features = [] 60 | 61 | x = self.features[0](x) 62 | x = self.features[1](x); features.append(x) 63 | x = self.features[2](x) 64 | x = self.features[3](x) 65 | x = self.features[4](x); features.append(x) 66 | x = self.features[5](x) 67 | x = self.features[6](x) 68 | x = self.features[7](x); features.append(x) 69 | x = self.features[8](x) 70 | x = self.features[9](x) 71 | x = self.features[10](x); features.append(x) 72 | x = self.features[11](x) 73 | x = self.features[12](x); features.append(x) 74 | x = self.features[13](x) 75 | x = self.features[14](x); features.append(x) 76 | x = self.features[15](x) 77 | x = self.features[16](x) 78 | x = self.features[17](x); features.append(x) 79 | x = self.features[18](x) 80 | x = self.features[19](x); features.append(x) 81 | 82 | return features 83 | 84 | def test(): 85 | net = VGG('VGG11') 86 | x = torch.randn(2,3,32,32) 87 | y = net(x) 88 | print(y.size()) 89 | 90 | # test() -------------------------------------------------------------------------------- /wrn.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | 7 | class BasicBlock(nn.Module): 8 | def __init__(self, in_planes, out_planes, stride, dropRate=0.0): 9 | super(BasicBlock, self).__init__() 10 | self.bn1 = nn.BatchNorm2d(in_planes) 11 | self.relu1 = nn.ReLU(inplace=True) 12 | self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 13 | padding=1, bias=False) 14 | self.bn2 = nn.BatchNorm2d(out_planes) 15 | self.relu2 = nn.ReLU(inplace=True) 16 | self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1, 17 | padding=1, bias=False) 18 | self.droprate = dropRate 19 | self.equalInOut = (in_planes == out_planes) 20 | self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, 21 | padding=0, bias=False) or None 22 | 23 | def forward(self, x): 24 | if not self.equalInOut: 25 | x = self.relu1(self.bn1(x)) 26 | else: 27 | out = self.relu1(self.bn1(x)) 28 | if self.equalInOut: 29 | out = self.relu2(self.bn2(self.conv1(out))) 30 | else: 31 | out = self.relu2(self.bn2(self.conv1(x))) 32 | if self.droprate > 0: 33 | out = F.dropout(out, p=self.droprate, training=self.training) 34 | out = self.conv2(out) 35 | if not self.equalInOut: 36 | return torch.add(self.convShortcut(x), out) 37 | else: 38 | return torch.add(x, out) 39 | 40 | class BasicBlock_nobn(nn.Module): 41 | def __init__(self, in_planes, out_planes, stride, dropRate=0.0): 42 | super(BasicBlock, self).__init__() 43 | self.relu1 = nn.ReLU(inplace=True) 44 | self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 45 | padding=1, bias=False) 46 | self.relu2 = nn.ReLU(inplace=True) 47 | self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1, 48 | padding=1, bias=False) 49 | self.droprate = dropRate 50 | self.equalInOut = (in_planes == out_planes) 51 | self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, 52 | padding=0, bias=False) or None 53 | 54 | def forward(self, x): 55 | if not self.equalInOut: 56 | x = self.relu1(x) 57 | else: 58 | out = self.relu1(x) 59 | if self.equalInOut: 60 | out = self.relu2(self.bn2(self.conv1(out))) 61 | else: 62 | out = self.relu2(self.bn2(self.conv1(x))) 63 | if self.droprate > 0: 64 | out = F.dropout(out, p=self.droprate, training=self.training) 65 | out = self.conv2(out) 66 | if not self.equalInOut: 67 | return torch.add(self.convShortcut(x), out) 68 | else: 69 | return torch.add(x, out) 70 | 71 | class NetworkBlock(nn.Module): 72 | def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0): 73 | super(NetworkBlock, self).__init__() 74 | self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate) 75 | 76 | def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate): 77 | layers = [] 78 | for i in range(nb_layers): 79 | layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate)) 80 | return nn.Sequential(*layers) 81 | 82 | def forward(self, x): 83 | return self.layer(x) 84 | 85 | 86 | class WideResNet(nn.Module): 87 | def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0): 88 | super(WideResNet, self).__init__() 89 | nChannels = [16, 16 * widen_factor, 32 * widen_factor, 64 * widen_factor] 90 | assert ((depth - 4) % 6 == 0) 91 | n = (depth - 4) // 6 92 | block = BasicBlock 93 | # 1st conv before any network block 94 | self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1, 95 | padding=1, bias=False) 96 | # 1st block 97 | self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate) 98 | # 2nd block 99 | self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate) 100 | # 3rd block 101 | self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate) 102 | 103 | # global average pooling and classifier 104 | self.bn1 = nn.BatchNorm2d(nChannels[3]) 105 | self.relu = nn.ReLU(inplace=True) 106 | self.fc = nn.Linear(nChannels[3], num_classes) 107 | self.nChannels = nChannels[3] 108 | 109 | for m in self.modules(): 110 | if isinstance(m, nn.Conv2d): 111 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 112 | m.weight.data.normal_(0, math.sqrt(2. / n)) 113 | elif isinstance(m, nn.BatchNorm2d): 114 | m.weight.data.fill_(1) 115 | m.bias.data.zero_() 116 | elif isinstance(m, nn.Linear): 117 | m.bias.data.zero_() 118 | 119 | def forward(self, x): 120 | out = self.forward_features(x) 121 | return self.fc(out) 122 | 123 | def forward_features(self,x): 124 | out = self.conv1(x) 125 | out = self.block1(out) 126 | out = self.block2(out) 127 | out = self.block3(out) 128 | 129 | out = self.relu(self.bn1(out)) 130 | out = F.avg_pool2d(out, 8) 131 | out = out.view(-1, self.nChannels) 132 | return out 133 | 134 | def forward_features_blockwise(self, x): 135 | features = [] 136 | x = self.conv1(x) 137 | 138 | x = self.block1.layer[0](x); features.append(x) 139 | x = self.block1.layer[1](x); features.append(x) 140 | x = self.block1.layer[2](x); features.append(x) 141 | x = self.block1.layer[3](x); features.append(x) 142 | 143 | x = self.block2.layer[0](x); features.append(x) 144 | x = self.block2.layer[1](x); features.append(x) 145 | x = self.block2.layer[2](x); features.append(x) 146 | x = self.block2.layer[3](x); features.append(x) 147 | 148 | x = self.block3.layer[0](x); features.append(x) 149 | x = self.block3.layer[1](x); features.append(x) 150 | x = self.block3.layer[2](x); features.append(x) 151 | x = self.block3.layer[3](x); features.append(x) 152 | return features --------------------------------------------------------------------------------