├── LICENSE ├── README.md ├── SSM.py ├── St-SS-pGRU ├── 1810.12563.pdf ├── Experiment.ipynb └── README.md └── WCRN ├── Pavia_University ├── PU_predict.py ├── PU_tarin.py ├── SSM.py ├── WCRN.py └── predict.asc.aux.xml ├── README.md ├── WCRN.py ├── wcrn_igarss_poster.jpg └── wcrn_igarss_poster.pdf /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 2018 Yue H.W. Luo, yue.rimoe@gmail.com . 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 | # DL_for_RSIs 2 | 3 | ##### Deep Leaning (DL) for remote sensing image (RSI) classification. 4 | 5 | ##### If it helps, please STAR the project and CITE our papers. 6 | 7 | ### Sample-set Maker(SSM) V5.0 8 | 9 | - SSM.py 10 | 11 | This is a class definition scipts for Sample-set Maker. SSM is a sample maker for RSI (Remote Sencing Image) classification, specifically for deep learning classification algorithm. 12 | With SSM, you can easily load a RSI and get samples for training. Every Sample made by SSM is a N*N sub-image, which can be a sample of its center pixel for CNN/ResNet classifier. 13 | Also, AL (Active Learning) is supported in SSM. 14 | 15 | The script is compliant with PEP-8 specifications. 16 | 17 | --- 18 | 19 | ### Networks 20 | 21 | #### 1. Wide Contextual Residual Network (WCRN) 22 | 23 | This is a wide contextual residual network (WCRN) with active learning (AL) for remote sensing image (RSI) classification. 24 | 25 | Though ResNets have achieved great success in various applications, its performance is limited by the requirement of abundant labeled samples. As it is very difficult and expensive to obtain class labels in real world, we integrate the proposed WCRN with AL to improve its generalization by using the most informative training samples. 26 | 27 | Specifically, we first design a WCRN for RSI classification, and then integrate it with AL to achieve good machine generalization with limited number of training sampling. Experimental results on Pavia University and Flevoland datasets demonstrate that the proposed WCRN with AL can significantly reduce the needs of samples. 28 | 29 | Environment: 30 | > We run the scripts in Windows OS.
31 | > Spyder with Python 3.6
32 | > Keras 2.0.8 using Tensorflow 1.2.1 backend
33 | > SSM.py
34 | 35 | Script: 36 | > WCRN.py: the definition of the network.
37 | > SSM.py: a sample manager.
38 | > PU_train.py: an example script for Pavia University, used for training.
39 | > PU_predict.py: an example script for Pavia University, used for predicting. 40 | 41 | The scripts are compliant with PEP-8 specifications. 42 | 43 | Reference: 44 | 45 | [S. Liu, H. Luo, Y. Tu, Z. He and J. Li, "Wide Contextual Residual Network with Active Learning for Remote Sensing Image Classification," IGARSS 2018 - 2018 IEEE International Geoscience and Remote Sensing Symposium, Valencia, 2018, pp. 7145-7148. doi: 10.1109/IGARSS.2018.8517855](https://ieeexplore.ieee.org/document/8517855) 46 | 47 | 48 | #### 2. Shorten Spatial-spectral RNN with Parallel-GRU (St-SS-pGRU) 49 | 50 | Convolutional neural networks (CNNs) attained a good performance in hyperspectral sensing image (HSI) classification, but CNNs consider spectra as orderless vectors. Therefore, considering the spectra as sequences, recurrent neural networks (RNNs) have been applied in HSI classification, for RNNs is skilled at dealing with sequential data. However, for a long-sequence task, RNNs is difficult for training and not as effective as we expected. Besides, spatial contextual features are not considered in RNNs. In this study, we propose a Shorten Spatial-spectral RNN with Parallel-GRU (St-SS-pGRU) for HSI classification. A shorten RNN is more efficient and easier for training than band-by-band RNN. By combining converlusion layer, the St-SSpGRU model considers not only spectral but also spatial feature, which results in a better performance. An architecture named parallel-GRU is also proposed and applied in St-SS-pGRU. With this architecture, the model gets a better performance and is more robust. 51 | 52 | Environment: 53 | > We run the scripts in Windows OS.
54 | > Jupyter with Python 3.6
55 | > Tensorflow 1.8.0
56 | > SSM.py 57 | 58 | Script: 59 | > Experiment.ipynb 60 | 61 | Reference: 62 | 63 | [Haowen Luo. Shorten Spatial-spectral RNN with Parallel-GRU for Hyperspectral Image Classification. arXiv preprint arXiv:1810.12563, 2018.](https://arxiv.org/abs/1810.12563) 64 | -------------------------------------------------------------------------------- /SSM.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Sample-set Maker(SSM) V5.0 4 | # Author: Yue H.W. Luo 5 | # Mail: yue.rimoe@gmail.com 6 | # License : http://www.apache.org/licenses/LICENSE-2.0 7 | # Reference: 8 | 9 | ''' 10 | This is a class definition scipts for Sample-set Maker. SSM is a sample maker 11 | for RSI (Remote Sencing Image) classification, specifically for deep learning 12 | classification algorithm. 13 | With SSM, you can easily load a RSI and get samples for training. Every Sample 14 | made by SSM is a N*N sub-image, which can be a sample of its center pixel for 15 | CNN/ResNet classifier. 16 | Also, AL (Active Learning) is supported in SSM. 17 | ''' 18 | 19 | # Usage: 20 | # 1.import model: 21 | # > from SSM import * 22 | # 2.initial SSM: 23 | # SSM(IMGSize, SAMN, CLAN[, AUG=1, RSEED=-1]): 24 | # ` IMGSize: the ROW, COL, BAND of image: [ROW, COL, BAND] 25 | # ` SAMN: the size of sample: NS 26 | # ` CLAM: the number of classes: NC 27 | # ` AUG: Data Augmentation, 1 for augmented, 0 for no augmented 28 | # ` RSEED: random seed, int required, [default: -1 (time seed)] 29 | # > samples = SSM([340, 610, 103], 5, 9, 1, -1) 30 | # 3.load image: 31 | # samples.load(img_file, img_id, gt_file, gt_id, [reshape=0], [bg_bias=1]) 32 | # ` img_file: image file(.mat) name 33 | # ` img_id: the var name in image file 34 | # ` gt_file: ground true file(.mat) name 35 | # ` gt_id: the var name in ground true file 36 | # ` reshape: reshape or not [default: 0 (not resheap)] 37 | # ` bg_bias: the background value in ground true image [default: 1] 38 | # > samples.load('PaviaU_im', 'im', 'PaviaU_gt_map', 'map', 1, 1) 39 | # 4.normalization: 40 | # samples.normalization([nor_type=-1, save=[]]) 41 | # ` nor_type: -1: normalize to [-1, 1] 42 | # 0: normalize to [0, 1] 43 | # save: a numpy array, the scale of normalization, if [] is given, a 44 | # numpy array (the scale) will return [default: []] 45 | # > save_w = samples.normalization() 46 | # > samples.normalization(save=save_w) 47 | # # if you have 2 RSI, you train a classifer with RSI1, but then 48 | # you want to predict RSI2, you should normalize RSI2 with the 49 | # scale given by RSI2: 50 | # > samples.normalization(save=save_w) 51 | # 5.initial training samples 52 | # samples.init_sam(n_perclass, [n_test=-1, self_train=0]) 53 | # ` n_perclass: number of samples per class 54 | # ` n_test: number of samples per class, [default: -1(all the rest of 55 | # samples is used as test samples)] 56 | # ` self_train: self train or not, [default: 0] 57 | # samples.init_sam2(ntrain_list, nvali_list) 58 | # ` ntrain_list: number of train samples per class 59 | # ` nvali_list: number of validation samples per class, input a list of 60 | # int, if the length of list is 1, every class will get 61 | # the same number of samples. 62 | # ` The rest of samples is for test set. 63 | # > samples.init_sam(10) 64 | # > samples.init_sam(10, 20) 65 | # > samples.init_sam2([10, 5, 25, 30], 20) 66 | # > samples.init_sam2([10, 5, 25, 30], [20, 10, 50, 60]) 67 | # 6.load samples (make samples) 68 | # samples.load_all_sam() 69 | # 7.save or load samples set 70 | # samples.save(Filename) 71 | # ` Save labeled samples only. 72 | # samples.save_all(Filename) 73 | # ` Save all samples. 74 | # samples.load(Filename) 75 | # ` Load labeled samples only. 76 | # samples.load_all(Filename) 77 | # ` Load all samples. 78 | # 8.Active Learning 79 | # samples.selector(stype, para) 80 | # ` stype: AL method 81 | # ` para: parameters of AL method 82 | # 83 | 84 | 85 | import random 86 | import h5py 87 | import copy 88 | import scipy 89 | import numpy as np 90 | 91 | 92 | def to_categorical(cla, ncls): 93 | _tt = [] 94 | for _i in cla: 95 | _t = np.zeros(ncls, dtype=np.int32) 96 | _t[_i] = 1 97 | _tt.append(_t) 98 | return np.array(_tt) 99 | 100 | 101 | class SSM: 102 | 103 | # initial the SSM 104 | def __init__(self, IMGSize, SAMN, CLAN, AUG=1, RSEED=-1): 105 | self.img = {'im': [], 106 | 'gt': [], 107 | 'pad': [], 108 | } 109 | self.all = {'sample': [], 110 | 'label': [], 111 | 'label_v': [], 112 | 'XY': [] 113 | } 114 | self.train = {'sample': [], 115 | 'label': [], 116 | 'label_v': [], 117 | 'XY': [] 118 | } 119 | self.test = {'sample': [], 120 | 'label': [], 121 | 'label_v': [], 122 | 'XY': [] 123 | } 124 | self.candidate = {'sample': [], 125 | 'label': [], 126 | 'label_v': [], 127 | 'XY': [] 128 | } 129 | self.IMGX = IMGSize[0] 130 | self.IMGY = IMGSize[1] 131 | self.IMGB = IMGSize[2] 132 | self.SAMD = SAMN // 2 133 | self.SAMN = SAMN 134 | self.CLAN = CLAN 135 | self.AUG = AUG 136 | if RSEED != -1: 137 | random.seed(RSEED) 138 | 139 | # destructor 140 | def __del__(self): 141 | self.img.clear() 142 | self.all.clear() 143 | self.train.clear() 144 | self.test.clear() 145 | self.candidate.clear() 146 | del self.img 147 | del self.all 148 | del self.train 149 | del self.test 150 | del self.candidate 151 | try: 152 | self.self_sam.clear() 153 | self.flush.clear() 154 | del self.self_sam 155 | del self.flush 156 | except: 157 | pass 158 | print('SSM Destructor: Delete samples!') 159 | 160 | # load the image and padding 161 | def load(self, img_file, img_id, gt_file, gt_id, reshape=0, bg_bias=1): 162 | self.img['gt'] = scipy.io.loadmat(gt_file)[gt_id] 163 | self.img['im'] = scipy.io.loadmat(img_file)[img_id] 164 | self.img['gt'] = self.img['gt'] - bg_bias 165 | if reshape == 1: 166 | self.img['gt'] = self.img['gt'].T 167 | self.img['im'] = np.reshape(self.img['im'].T, 168 | [self.IMGX, self.IMGY, self.IMGB]) 169 | img_im = self.img['im'] 170 | n = self.SAMD 171 | # Padding 172 | r1 = np.repeat([img_im[0, :, :]], n, axis=0) 173 | r2 = np.repeat([img_im[-1, :, :]], n, axis=0) 174 | img_add = np.concatenate((r1, img_im, r2)) 175 | r1 = np.reshape(img_add[:, 0, :], [self.IMGX + 2 * n, 1, self.IMGB]) 176 | r2 = np.reshape(img_add[:, -1, :], [self.IMGX + 2 * n, 1, self.IMGB]) 177 | r1 = np.repeat(r1, self.SAMD, axis=1) 178 | r2 = np.repeat(r2, self.SAMD, axis=1) 179 | self.img['pad'] = np.concatenate((r1, img_add, r2), axis=1) 180 | 181 | # normalize the sample of the padded image 182 | # note that normalization should do before samples-getting function, such 183 | # as init_sam, init_sam2 and load_all_sam. 184 | # a numpy array will be returned if the parameter `save` is not given, 185 | # which can use as a parameter for normalization 186 | def normalization(self, nor_type=-1, save=[]): 187 | img_add = self.img['pad'].astype('float') 188 | if save == []: 189 | save_w = np.zeros((2, self.IMGB)) 190 | for i in range(self.IMGB): 191 | save_w[0, i] = img_add[:, :, i].min() 192 | img_add[:, :, i] = img_add[:, :, i] - img_add[:, :, i].min() 193 | save_w[1, i] = img_add[:, :, i].max() 194 | img_add[:, :, i] = img_add[:, :, i] / img_add[:, :, i].max() 195 | if nor_type == -1: 196 | img_add[:, :, i] = img_add[:, :, i] * 2 - 1 197 | self.img['pad'] = img_add 198 | return save_w 199 | else: 200 | for i in range(self.IMGB): 201 | img_add[:, :, i] = img_add[:, :, i] - save[0, i] 202 | img_add[:, :, i] = img_add[:, :, i] / save[1, i] 203 | if nor_type == -1: 204 | img_add[:, :, i] = img_add[:, :, i] * 2 - 1 205 | self.img['pad'] = img_add 206 | 207 | # initial training samples, by given number of training and test samples 208 | # every class get the same number of samples, no validation set. 209 | def init_sam(self, n_perclass, n_test=-1, self_train=0): 210 | if self_train: 211 | self.self_sam = {} 212 | self.self_sam['map'] = np.zeros(self.img['gt'].shape) 213 | self.flush = {'XY': [], 214 | 'label': [], 215 | 'sample': [] 216 | } 217 | for i in range(self.CLAN): 218 | c_label = list(np.array(np.where(self.img['gt'] == i)).T) 219 | random.shuffle(c_label) 220 | self.train['XY'].extend(c_label[:n_perclass]) 221 | if n_perclass == 0: 222 | self.test['XY'].extend(c_label[:]) 223 | continue 224 | if n_test < 0: 225 | self.test['XY'].extend(c_label[n_perclass:]) 226 | else: 227 | self.test['XY'].extend(c_label[n_perclass:n_perclass + n_test]) 228 | random.shuffle(self.train['XY']) 229 | random.shuffle(self.test['XY']) 230 | for i in self.train['XY']: 231 | self.train['sample'].append(self.get_sample(i)) 232 | self.train['label'].append(self.get_label(i)) 233 | if self_train: 234 | self.self_sam['map'][i[0]][i[1]] = 1 235 | for i in self.test['XY']: 236 | self.test['sample'].append(self.get_sample(i)) 237 | self.test['label'].append(self.get_label(i)) 238 | self.train['label_v'] = to_categorical(self.train['label'], self.CLAN) 239 | self.test['label_v'] = to_categorical(self.test['label'], self.CLAN) 240 | for i in self.train: 241 | self.train[i] = np.array(self.train[i]) 242 | self.test[i] = np.array(self.test[i]) 243 | if self_train: 244 | self.candidate[i] = np.array(self.candidate[i]) 245 | if not self_train: 246 | self.candidate = copy.deepcopy(self.test) 247 | else: 248 | self.self_sam['XY'] = copy.deepcopy(self.train['XY']) 249 | self.self_sam['label'] = copy.deepcopy(self.train['label']) 250 | if n_perclass != 0: 251 | if self.AUG != 0: 252 | self.train = self.make_sample(self.train) 253 | 254 | # initial training samples, by given number of training and validation 255 | # samples for every class, the rest samples is test set. 256 | def init_sam2(self, ntrain_list, nvali_list): 257 | self.vali = {'sample': [], 258 | 'label': [], 259 | 'label_v': [], 260 | 'XY': [] 261 | } 262 | for i in range(self.CLAN): 263 | if len(ntrain_list) == self.CLAN: 264 | i_ = i 265 | else: 266 | i_ = 0 267 | if len(nvali_list) == self.CLAN: 268 | j_ = i 269 | else: 270 | j_ = 0 271 | c_label = list(np.array(np.where(self.img['gt'] == i)).T) 272 | random.shuffle(c_label) 273 | self.train['XY'].extend(c_label[:ntrain_list[i_]]) 274 | self.vali['XY'].extend(c_label[ntrain_list[i_]:ntrain_list[i_] + 275 | nvali_list[j_]]) 276 | self.test['XY'].extend(c_label[ntrain_list[i_] + nvali_list[j_]:]) 277 | random.shuffle(self.train['XY']) 278 | random.shuffle(self.vali['XY']) 279 | random.shuffle(self.test['XY']) 280 | 281 | for i in self.train['XY']: 282 | self.train['sample'].append(self.get_sample(i)) 283 | self.train['label'].append(self.get_label(i)) 284 | for i in self.test['XY']: 285 | self.test['sample'].append(self.get_sample(i)) 286 | self.test['label'].append(self.get_label(i)) 287 | for i in self.vali['XY']: 288 | self.vali['sample'].append(self.get_sample(i)) 289 | self.vali['label'].append(self.get_label(i)) 290 | self.train['label_v'] = to_categorical(self.train['label'], self.CLAN) 291 | self.test['label_v'] = to_categorical(self.test['label'], self.CLAN) 292 | self.vali['label_v'] = to_categorical(self.vali['label'], self.CLAN) 293 | 294 | for i in self.train: 295 | self.train[i] = np.array(self.train[i]) 296 | self.test[i] = np.array(self.test[i]) 297 | self.vali[i] = np.array(self.vali[i]) 298 | self.candidate = copy.deepcopy(self.test) 299 | if self.AUG != 0: 300 | self.train = self.make_sample(self.train) 301 | 302 | # load all pixel as samples for predicting, caution that large memory will 303 | # be occupied. 304 | def load_all_sam(self): 305 | self.all = {'sample': [], 306 | 'label': [], 307 | 'label_v': [], 308 | 'XY': [] 309 | } 310 | for i in range(self.IMGX): 311 | for j in range(self.IMGY): 312 | xy = np.array([i, j]) 313 | self.all['XY'].append(xy) 314 | self.all['sample'].append(self.get_sample(xy)) 315 | self.all['label'].append(self.get_label(xy)) 316 | 317 | def save(self, name): 318 | with h5py.File(name + '_img', 'w') as h5f: 319 | for i in self.img: 320 | h5f.create_dataset(i, data=self.img[i]) 321 | 322 | with h5py.File(name + '_train', 'w') as h5f: 323 | for i in self.train: 324 | h5f.create_dataset(i, data=self.train[i]) 325 | 326 | with h5py.File(name + '_candidate', 'w') as h5f: 327 | for i in self.candidate: 328 | h5f.create_dataset(i, data=self.candidate[i]) 329 | 330 | with h5py.File(name + '_test', 'w') as h5f: 331 | for i in self.test: 332 | h5f.create_dataset(i, data=self.test[i]) 333 | 334 | def save_all(self, name): 335 | with h5py.File(name, 'w') as h5f: 336 | for i in self.all: 337 | h5f.create_dataset(i, data=self.all[i]) 338 | 339 | def load_file(self, name): 340 | with h5py.File(name + '_img', 'r') as h5f: 341 | for i in h5f: 342 | self.img[i] = h5f[i][:] 343 | 344 | with h5py.File(name + '_train', 'r') as h5f: 345 | for i in h5f: 346 | self.train[i] = h5f[i][:] 347 | 348 | with h5py.File(name + '_candidate', 'r') as h5f: 349 | for i in h5f: 350 | self.candidate[i] = h5f[i][:] 351 | 352 | with h5py.File(name + '_test', 'r') as h5f: 353 | for i in h5f: 354 | self.test[i] = h5f[i][:] 355 | 356 | def load_all_file(self, name): 357 | with h5py.File(name, 'r') as h5f: 358 | for i in h5f: 359 | self.all[i] = h5f[i][:] 360 | 361 | def loop_sample(self, no_time, batch_size): 362 | samn = len(self.train['sample']) 363 | _s = no_time * batch_size % samn 364 | _t = _s + batch_size 365 | _sam = self.train['sample'][_s:_t] 366 | _lv = self.train['label_v'][_s:_t] 367 | _lab = self.train['label'][_s:_t] 368 | _delta = _t - samn 369 | if _delta > 0: 370 | _sam = np.concatenate([_sam, self.train['sample'][:_delta]]) 371 | _lv = np.concatenate([_lv, self.train['label_v'][:_delta]]) 372 | _lab = np.concatenate([_lab, self.train['label'][:_delta]]) 373 | return _sam, _lv, _lab 374 | 375 | # AL-selector 376 | def selector(self, stype, para): 377 | n = para[0] 378 | try: 379 | predict = para[1] 380 | except IndexError: 381 | pass 382 | if stype == 'RS': 383 | indexs = self.RS_sample(n) 384 | elif stype == 'BT': 385 | indexs = self.BT_sample(predict, n) 386 | elif stype == 'SM': 387 | indexs = self.SM_sample(predict, n) 388 | elif stype == 'MI': 389 | indexs = self.MI_sample(predict, n) 390 | elif stype == 'MBT': 391 | indexs = self.MBT_sample(predict, n) 392 | elif stype == 'entropy': 393 | indexs = self.entropy_sample(predict, n) 394 | self.add_sample(indexs) 395 | 396 | # filp, mirror 397 | def make_sample(self, origin): 398 | sample = origin['sample'] 399 | label = origin['label'] 400 | label_v = origin['label_v'] 401 | XY = origin['XY'] 402 | a = np.flip(sample, 1) 403 | b = np.flip(sample, 2) 404 | c = np.flip(b, 1) 405 | new = {} 406 | new['sample'] = np.concatenate((a, b, c, sample), axis=0) 407 | new['label'] = np.concatenate((label, label, label, label), axis=0) 408 | new['label_v'] = np.concatenate( 409 | (label_v, label_v, label_v, label_v), 410 | axis=0) 411 | new['XY'] = np.concatenate((XY, XY, XY, XY), axis=0) 412 | return new 413 | 414 | # return a sample(N*N sub-image), by given XY 415 | def get_sample(self, xy): 416 | d = self.SAMD 417 | x = xy[0] 418 | y = xy[1] 419 | try: 420 | self.img['im'][x][y] 421 | except IndexError: 422 | return [] 423 | # considering the padded pixel, xy should add d 424 | x += d 425 | y += d 426 | sam = self.img['pad'][(x - d): (x + d + 1), (y - d): (y + d + 1)] 427 | return np.array(sam) 428 | 429 | # return lebel of a sample, by given XY 430 | def get_label(self, xy): 431 | return self.img['gt'][xy[0]][xy[1]] 432 | 433 | # add samples to training set from candidate set 434 | def add_sample(self, indexs): 435 | new = {} 436 | for i in self.train: 437 | new[i] = self.candidate[i][indexs] 438 | self.candidate[i] = np.delete(self.candidate[i], indexs, axis=0) 439 | if self.AUG != 0: 440 | new = self.make_sample(new) 441 | for i in self.train: 442 | self.train[i] = np.append(self.train[i], new[i], 0) 443 | 444 | # Active Learning Algorithm 445 | def RS_sample(self, n): 446 | cand_sam = self.candidate 447 | index = list(range(len(cand_sam['sample']))) 448 | random.shuffle(index) 449 | return index[:n] 450 | 451 | def BT_sample(self, predict, n): 452 | index = np.argsort(-predict) 453 | diff = np.zeros((len(index), 2)) 454 | for i in range(len(index)): 455 | diff[i, 0] = predict[i, index[i, 0]] 456 | diff[i, 1] = predict[i, index[i, 1]] 457 | diff2 = diff[:, 0] - diff[:, 1] 458 | index = np.argsort(diff2) 459 | return index[:n] 460 | 461 | # sort by max probability 462 | def new_sample(self, predict, n): 463 | probability = predict.max(axis=1) 464 | index = np.argsort(probability) 465 | return index[:n] 466 | 467 | # cos 468 | def cos_sample(self, predict, n): 469 | probability = predict.max(axis=1) 470 | index = np.argsort(probability) 471 | return index[:n] 472 | 473 | def SM_sample(self, predict, n): 474 | index = np.argsort(-predict) 475 | diff = np.zeros((len(index), 2)) 476 | for i in range(len(index)): 477 | diff[i, 0] = predict[i, index[i, 0]] 478 | diff[i, 1] = predict[i, index[i, 1]] 479 | diff2 = diff[:, 1] 480 | index = np.argsort(-diff2) 481 | return index[:n] 482 | 483 | def MBT_sample(self, predict, n): 484 | predictlabel = np.argmax(predict, axis=1) 485 | total_index = [] 486 | total_p2 = [] 487 | for i in range(9): 488 | tmpindex = np.where(predictlabel == i) 489 | tmpindex = tmpindex[0].T 490 | classpredict = predict[tmpindex, :] 491 | classpredict[:, i] = 0.0 492 | maxx = np.max(classpredict, axis=1) 493 | index2 = np.argsort(-maxx) 494 | total_p2.append(maxx[index2[:2]]) 495 | total_index.append(tmpindex[index2[:2]]) 496 | total_p2 = np.array(total_p2).reshape(18) 497 | total_index = np.array(total_index).reshape(18) 498 | index3 = np.argsort(-total_p2.T)[:10] 499 | index = total_index[index3] 500 | return index[:n] 501 | 502 | def entropy_sample(self, predict, n): 503 | etp = scipy.stats.entropy(predict.T) 504 | index = np.argsort(-etp) 505 | return index[:n] 506 | 507 | # Self-Train Model 508 | def add_self_sam(self, x, y, label): 509 | self_map = self.self_sam['map'] 510 | try: 511 | self_map[x][y] 512 | if (x < 0) | (y < 0): 513 | raise IndexError 514 | except IndexError: 515 | return 516 | if (not self_map[x][y]): 517 | XY = np.array([x, y]) 518 | self.flush['XY'].append(XY) 519 | self.flush['label'].append(label) 520 | self.flush['sample'].append(self.get_sample(XY)) 521 | 522 | def st_flush(self): 523 | l = len(self.self_sam['label']) 524 | for i in self.flush: 525 | del self.flush[i] 526 | self.flush[i] = [] 527 | for i in range(l): 528 | xy = self.self_sam['XY'][i] 529 | label = self.self_sam['label'][i] 530 | self.add_self_sam(xy[0] - 1, xy[1], label) 531 | self.add_self_sam(xy[0] + 1, xy[1], label) 532 | self.add_self_sam(xy[0], xy[1] + 1, label) 533 | self.add_self_sam(xy[0], xy[1] - 1, label) 534 | for i in self.flush: 535 | self.flush[i] = np.array(self.flush[i]) 536 | return self.flush['sample'] 537 | 538 | def st_merge(self, predict): 539 | indexs = np.where(self.flush['label'] != predict) 540 | indexs = list(indexs[0]) 541 | for i in self.flush: 542 | self.flush[i] = np.delete(self.flush[i], indexs, axis=0) 543 | try: 544 | self.candidate[i] = np.append( 545 | self.candidate[i], 546 | self.flush[i], 547 | 0) 548 | except ValueError: 549 | self.candidate[i] = self.flush[i] 550 | self.candidate['label_v'] = to_categorical( 551 | self.candidate['label'], 552 | self.CLAN) 553 | for i in ['XY', 'label']: 554 | self.self_sam[i] = np.append(self.self_sam[i], self.flush[i], 0) 555 | for i in self.flush['XY']: 556 | self.self_sam['map'][i[0]][i[1]] = 1 557 | -------------------------------------------------------------------------------- /St-SS-pGRU/1810.12563.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeRimoe/DL_for_RSIs/246cf32cfde7713d8659143033b26e60ec68f147/St-SS-pGRU/1810.12563.pdf -------------------------------------------------------------------------------- /St-SS-pGRU/README.md: -------------------------------------------------------------------------------- 1 | ## Shorten Spatial-spectral RNN with Parallel-GRU (St-SS-pGRU) 2 | 3 | Author : Haowen Luo 4 | 5 | License : http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | If it helps, please STAR the project and CITE our papers. 8 | 9 | Convolutional neural networks (CNNs) attained a good performance in hyperspectral sensing image (HSI) classification, but CNNs consider spectra as orderless vectors. Therefore, considering the spectra as sequences, recurrent neural networks (RNNs) have been applied in HSI classification, for RNNs is skilled at dealing with sequential data. However, for a long-sequence task, RNNs is difficult for training and not as effective as we expected. Besides, spatial contextual features are not considered in RNNs. In this study, we propose a Shorten Spatial-spectral RNN with Parallel-GRU (St-SS-pGRU) for HSI classification. A shorten RNN is more efficient and easier for training than band-by-band RNN. By combining converlusion layer, the St-SSpGRU model considers not only spectral but also spatial feature, which results in a better performance. An architecture named parallel-GRU is also proposed and applied in St-SS-pGRU. With this architecture, the model gets a better performance and is more robust. 10 | 11 | Environment: 12 | > We run the scripts in Windows OS.
13 | > Jupyter with Python 3.6
14 | > Tensorflow 1.8.0
15 | > SSM.py 16 | 17 | Script: 18 | > Experiment.ipynb 19 | 20 | The Hyperspetral RSI of Pavia University is available at: [Hyperspectral Remote Sensing Scenes - Grupo de Inteligencia Computacional (GIC)](http://www.ehu.eus/ccwintco/index.php/Hyperspectral_Remote_Sensing_Scenes) 21 | 22 | 23 | Reference: 24 | 25 | [Haowen Luo. Shorten Spatial-spectral RNN with Parallel-GRU for Hyperspectral Image Classification. arXiv preprint arXiv:1810.12563, 2018.](https://arxiv.org/abs/1810.12563) 26 | -------------------------------------------------------------------------------- /WCRN/Pavia_University/PU_predict.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Nov 26 12:31:01 2017 4 | 5 | This script is for predicting. 6 | 7 | author: Shengjie Liu, Haowen Luo 8 | """ 9 | 10 | from __future__ import print_function 11 | import SSM 12 | import WCRN 13 | import numpy as np 14 | import keras 15 | 16 | img_file = r'PaviaU' 17 | img_id = 'paviaU' 18 | gt_file = r'PaviaU_gt' 19 | gt_id = 'paviaU_gt' 20 | 21 | samples = SSM.SSM([610, 340, 103], 5, 9, 1, -1) 22 | samples.load(img_file, img_id, gt_file, gt_id, 0, 1) 23 | samples.normalization() 24 | samples.load_all_sam() 25 | 26 | samples.save_all('all.h5') 27 | # samples.load_all_file('all.h5') 28 | 29 | # network 30 | model = WCRN.build(103, 9, 1, 32) 31 | 32 | # 33 | model.summary() 34 | model.compile(loss=keras.losses.categorical_crossentropy, 35 | optimizer=keras.optimizers.Adadelta(), 36 | metrics=['accuracy']) 37 | 38 | # reload 39 | model.load_weights('model/str_SM0.h5') 40 | 41 | # evaluation = model.evaluate(x=samples.test['sample'], 42 | # y=samples.test['label_v'], 43 | # verbose=1) # test on test sample 44 | 45 | predict_map = np.argmax(model.predict(x=np.array(samples.all['sample'][:]), 46 | verbose=1), axis=1) 47 | predict_map = predict_map.reshape(610, 340).astype(int) 48 | 49 | 50 | # pm = np.zeros([610,340]) 51 | # j = 0 52 | # for i in samples.all['XY']: 53 | # pm[i[1]][i[0]] = predict_map[j] 54 | # j += 1 55 | 56 | np.savetxt('predict.asc', predict_map, fmt='%d') 57 | tmp = '' 58 | with open('predict.asc', 'r') as rf: 59 | tmp = rf.read() 60 | with open('predict.asc', 'w') as wf: 61 | wf.write('ncols 340\n' + 62 | 'nrows 610\n' + 63 | 'xllcorner 0\n' + 64 | 'yllcorner 0\n' + 65 | 'cellsize 1\n' + 66 | 'NODATA_value -9999\n' + 67 | tmp) 68 | -------------------------------------------------------------------------------- /WCRN/Pavia_University/PU_tarin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Nov 26 12:31:01 2017 4 | 5 | This script is for training. 6 | 7 | author: Shengjie Liu, Haowen Luo 8 | """ 9 | 10 | from __future__ import print_function 11 | import SSM 12 | import WCRN 13 | import scipy.io 14 | import scipy.stats 15 | import numpy as np 16 | import keras 17 | from keras.callbacks import ModelCheckpoint, History 18 | 19 | img_file = r'PaviaU' 20 | img_id = 'paviaU' 21 | gt_file = r'PaviaU_gt' 22 | gt_id = 'paviaU_gt' 23 | 24 | samples = SSM.SSM([610, 340, 103], 5, 9, 1, -1) 25 | samples.load(img_file, img_id, gt_file, gt_id, 0, 1) 26 | samples.normalization() 27 | samples.init_sam(10) 28 | 29 | samples.save('samples.h5') # save samples 30 | # samples.load_file('samples.h5') # load samples 31 | 32 | # network: build a WCRN with 1 residual layer 33 | model = WCRN.build(103, 9, 1, 32) 34 | 35 | # summary and compile 36 | model.summary() 37 | model.compile(loss=keras.losses.categorical_crossentropy, 38 | optimizer=keras.optimizers.Adadelta(), 39 | metrics=['accuracy']) 40 | 41 | # reload model (for pre-train) 42 | # model.load_weights('model804.h5') 43 | 44 | num = -1 # init loop num 45 | total = np.zeros((100, 5)) # record OA 46 | 47 | # training 48 | while(1): 49 | if num == 50: 50 | break 51 | num += 1 52 | 53 | # set batch_size 54 | if num < 20: 55 | batch_size = 10 56 | elif num < 40: 57 | batch_size = 20 58 | else: 59 | batch_size = 40 60 | epochs = 50 61 | 62 | # # abandoned 63 | # # self_train 64 | # if num % 5 == 0: 65 | # print(len(samples.candidate['label'])) 66 | # print('self_train!') 67 | # predict3 = samples.st_flush() 68 | # m = np.argmax(model.predict(x=predict3,verbose=0), axis=1) 69 | # samples.st_merge(m) 70 | 71 | # save model 72 | fpara = 'model/str_SM' + str(num) + '.h5' 73 | model_checkpoint = ModelCheckpoint(fpara, monitor='loss', 74 | save_best_only=True, mode='min') 75 | 76 | history = History() 77 | history = model.fit(samples.train['sample'], samples.train['label_v'], 78 | batch_size=batch_size, epochs=epochs, verbose=1, 79 | shuffle=True, callbacks=[model_checkpoint]) 80 | 81 | # record OA 82 | total[num, 2] = min(history.history['loss']) 83 | total[num, 3] = max(history.history['acc']) 84 | predict = [] 85 | prob = [] 86 | 87 | # voting 88 | for i in range(3): 89 | epochs = 1 90 | history = model.fit(samples.train['sample'], 91 | samples.train['label_v'], 92 | batch_size=batch_size, 93 | epochs=epochs, 94 | verbose=1, 95 | shuffle=True) 96 | tmp = model.predict(x=samples.candidate['sample'], verbose=0) # cand 97 | tmp2 = model.predict(x=samples.test['sample'], verbose=0) # test 98 | prob.append(tmp) 99 | predict.append(np.argmax(tmp2, axis=1)) # test 100 | 101 | predict2 = np.sum(prob, axis=0) 102 | maxx = scipy.stats.mode(predict) 103 | maxx = maxx[0].T 104 | maxx = maxx.reshape(maxx.shape[0]) 105 | predict.append(maxx) 106 | # maxx.reshape(len(maxx),1) 107 | total[num, 4] = np.sum(maxx == np.argmax(samples.test['label_v'], 108 | axis=1)) / len(maxx) # testlabel 109 | print(total[num, 4]) # print OA 110 | 111 | # save OA 112 | # np.savetxt(fpara+'.csv',np.vstack(predict).T,delimiter=',') 113 | 114 | model.load_weights(fpara) 115 | evaluation = model.evaluate(x=samples.test['sample'], 116 | y=samples.test['label_v'], 117 | verbose=1) # test on test sample 118 | total[num, 0] = evaluation[0] 119 | total[num, 1] = evaluation[1] 120 | 121 | # Self Train 122 | # self_train(np.argmax(samples.test['label_v'],axis=1)) 123 | 124 | # Active Learning 125 | samples.selector('SM', [10, predict2]) 126 | -------------------------------------------------------------------------------- /WCRN/Pavia_University/SSM.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Sample-set Maker(SSM) V5.0 4 | # Author: Yue H.W. Luo 5 | # Mail: yue.rimoe@gmail.com 6 | # License : http://www.apache.org/licenses/LICENSE-2.0 7 | # Reference: 8 | 9 | ''' 10 | This is a class definition scipts for Sample-set Maker. SSM is a sample maker 11 | for RSI (Remote Sencing Image) classification, specifically for deep learning 12 | classification algorithm. 13 | With SSM, you can easily load a RSI and get samples for training. Every Sample 14 | made by SSM is a N*N sub-image, which can be a sample of its center pixel for 15 | CNN/ResNet classifier. 16 | Also, AL (Active Learning) is supported in SSM. 17 | ''' 18 | 19 | # Usage: 20 | # 1.import model: 21 | # > from SSM import * 22 | # 2.initial SSM: 23 | # SSM(IMGSize, SAMN, CLAN[, AUG=1, RSEED=-1]): 24 | # ` IMGSize: the ROW, COL, BAND of image: [ROW, COL, BAND] 25 | # ` SAMN: the size of sample: NS 26 | # ` CLAM: the number of classes: NC 27 | # ` AUG: Data Augmentation, 1 for augmented, 0 for no augmented 28 | # ` RSEED: random seed, int required, [default: -1 (time seed)] 29 | # > samples = SSM([340, 610, 103], 5, 9, 1, -1) 30 | # 3.load image: 31 | # samples.load(img_file, img_id, gt_file, gt_id, [reshape=0], [bg_bias=1]) 32 | # ` img_file: image file(.mat) name 33 | # ` img_id: the var name in image file 34 | # ` gt_file: ground true file(.mat) name 35 | # ` gt_id: the var name in ground true file 36 | # ` reshape: reshape or not [default: 0 (not resheap)] 37 | # ` bg_bias: the background value in ground true image [default: 1] 38 | # > samples.load('PaviaU_im', 'im', 'PaviaU_gt_map', 'map', 1, 1) 39 | # 4.normalization: 40 | # samples.normalization([nor_type=-1, save=[]]) 41 | # ` nor_type: -1: normalize to [-1, 1] 42 | # 0: normalize to [0, 1] 43 | # save: a numpy array, the scale of normalization, if [] is given, a 44 | # numpy array (the scale) will return [default: []] 45 | # > save_w = samples.normalization() 46 | # > samples.normalization(save=save_w) 47 | # # if you have 2 RSI, you train a classifer with RSI1, but then 48 | # you want to predict RSI2, you should normalize RSI2 with the 49 | # scale given by RSI2: 50 | # > samples.normalization(save=save_w) 51 | # 5.initial training samples 52 | # samples.init_sam(n_perclass, [n_test=-1, self_train=0]) 53 | # ` n_perclass: number of samples per class 54 | # ` n_test: number of samples per class, [default: -1(all the rest of 55 | # samples is used as test samples)] 56 | # ` self_train: self train or not, [default: 0] 57 | # samples.init_sam2(ntrain_list, nvali_list) 58 | # ` ntrain_list: number of train samples per class 59 | # ` nvali_list: number of validation samples per class, input a list of 60 | # int, if the length of list is 1, every class will get 61 | # the same number of samples. 62 | # ` The rest of samples is for test set. 63 | # > samples.init_sam(10) 64 | # > samples.init_sam(10, 20) 65 | # > samples.init_sam2([10, 5, 25, 30], 20) 66 | # > samples.init_sam2([10, 5, 25, 30], [20, 10, 50, 60]) 67 | # 6.load samples (make samples) 68 | # samples.load_all_sam() 69 | # 7.save or load samples set 70 | # samples.save(Filename) 71 | # ` Save labeled samples only. 72 | # samples.save_all(Filename) 73 | # ` Save all samples. 74 | # samples.load(Filename) 75 | # ` Load labeled samples only. 76 | # samples.load_all(Filename) 77 | # ` Load all samples. 78 | # 8.Active Learning 79 | # samples.selector(stype, para) 80 | # ` stype: AL method 81 | # ` para: parameters of AL method 82 | # 83 | 84 | 85 | import random 86 | import h5py 87 | import copy 88 | import scipy 89 | import numpy as np 90 | 91 | 92 | def to_categorical(cla, ncls): 93 | _tt = [] 94 | for _i in cla: 95 | _t = np.zeros(ncls, dtype=np.int32) 96 | _t[_i] = 1 97 | _tt.append(_t) 98 | return np.array(_tt) 99 | 100 | 101 | class SSM: 102 | 103 | # initial the SSM 104 | def __init__(self, IMGSize, SAMN, CLAN, AUG=1, RSEED=-1): 105 | self.img = {'im': [], 106 | 'gt': [], 107 | 'pad': [], 108 | } 109 | self.all = {'sample': [], 110 | 'label': [], 111 | 'label_v': [], 112 | 'XY': [] 113 | } 114 | self.train = {'sample': [], 115 | 'label': [], 116 | 'label_v': [], 117 | 'XY': [] 118 | } 119 | self.test = {'sample': [], 120 | 'label': [], 121 | 'label_v': [], 122 | 'XY': [] 123 | } 124 | self.candidate = {'sample': [], 125 | 'label': [], 126 | 'label_v': [], 127 | 'XY': [] 128 | } 129 | self.IMGX = IMGSize[0] 130 | self.IMGY = IMGSize[1] 131 | self.IMGB = IMGSize[2] 132 | self.SAMD = SAMN // 2 133 | self.SAMN = SAMN 134 | self.CLAN = CLAN 135 | self.AUG = AUG 136 | if RSEED != -1: 137 | random.seed(RSEED) 138 | 139 | # destructor 140 | def __del__(self): 141 | self.img.clear() 142 | self.all.clear() 143 | self.train.clear() 144 | self.test.clear() 145 | self.candidate.clear() 146 | del self.img 147 | del self.all 148 | del self.train 149 | del self.test 150 | del self.candidate 151 | try: 152 | self.self_sam.clear() 153 | self.flush.clear() 154 | del self.self_sam 155 | del self.flush 156 | except: 157 | pass 158 | print('SSM Destructor: Delete samples!') 159 | 160 | # load the image and padding 161 | def load(self, img_file, img_id, gt_file, gt_id, reshape=0, bg_bias=1): 162 | self.img['gt'] = scipy.io.loadmat(gt_file)[gt_id] 163 | self.img['im'] = scipy.io.loadmat(img_file)[img_id] 164 | self.img['gt'] = self.img['gt'] - bg_bias 165 | if reshape == 1: 166 | self.img['gt'] = self.img['gt'].T 167 | self.img['im'] = np.reshape(self.img['im'].T, 168 | [self.IMGX, self.IMGY, self.IMGB]) 169 | img_im = self.img['im'] 170 | n = self.SAMD 171 | # Padding 172 | r1 = np.repeat([img_im[0, :, :]], n, axis=0) 173 | r2 = np.repeat([img_im[-1, :, :]], n, axis=0) 174 | img_add = np.concatenate((r1, img_im, r2)) 175 | r1 = np.reshape(img_add[:, 0, :], [self.IMGX + 2 * n, 1, self.IMGB]) 176 | r2 = np.reshape(img_add[:, -1, :], [self.IMGX + 2 * n, 1, self.IMGB]) 177 | r1 = np.repeat(r1, self.SAMD, axis=1) 178 | r2 = np.repeat(r2, self.SAMD, axis=1) 179 | self.img['pad'] = np.concatenate((r1, img_add, r2), axis=1) 180 | 181 | # normalize the sample of the padded image 182 | # note that normalization should do before samples-getting function, such 183 | # as init_sam, init_sam2 and load_all_sam. 184 | # a numpy array will be returned if the parameter `save` is not given, 185 | # which can use as a parameter for normalization 186 | def normalization(self, nor_type=-1, save=[]): 187 | img_add = self.img['pad'].astype('float') 188 | if save == []: 189 | save_w = np.zeros((2, self.IMGB)) 190 | for i in range(self.IMGB): 191 | save_w[0, i] = img_add[:, :, i].min() 192 | img_add[:, :, i] = img_add[:, :, i] - img_add[:, :, i].min() 193 | save_w[1, i] = img_add[:, :, i].max() 194 | img_add[:, :, i] = img_add[:, :, i] / img_add[:, :, i].max() 195 | if nor_type == -1: 196 | img_add[:, :, i] = img_add[:, :, i] * 2 - 1 197 | self.img['pad'] = img_add 198 | return save_w 199 | else: 200 | for i in range(self.IMGB): 201 | img_add[:, :, i] = img_add[:, :, i] - save[0, i] 202 | img_add[:, :, i] = img_add[:, :, i] / save[1, i] 203 | if nor_type == -1: 204 | img_add[:, :, i] = img_add[:, :, i] * 2 - 1 205 | self.img['pad'] = img_add 206 | 207 | # initial training samples, by given number of training and test samples 208 | # every class get the same number of samples, no validation set. 209 | def init_sam(self, n_perclass, n_test=-1, self_train=0): 210 | if self_train: 211 | self.self_sam = {} 212 | self.self_sam['map'] = np.zeros(self.img['gt'].shape) 213 | self.flush = {'XY': [], 214 | 'label': [], 215 | 'sample': [] 216 | } 217 | for i in range(self.CLAN): 218 | c_label = list(np.array(np.where(self.img['gt'] == i)).T) 219 | random.shuffle(c_label) 220 | self.train['XY'].extend(c_label[:n_perclass]) 221 | if n_perclass == 0: 222 | self.test['XY'].extend(c_label[:]) 223 | continue 224 | if n_test < 0: 225 | self.test['XY'].extend(c_label[n_perclass:]) 226 | else: 227 | self.test['XY'].extend(c_label[n_perclass:n_perclass + n_test]) 228 | random.shuffle(self.train['XY']) 229 | random.shuffle(self.test['XY']) 230 | for i in self.train['XY']: 231 | self.train['sample'].append(self.get_sample(i)) 232 | self.train['label'].append(self.get_label(i)) 233 | if self_train: 234 | self.self_sam['map'][i[0]][i[1]] = 1 235 | for i in self.test['XY']: 236 | self.test['sample'].append(self.get_sample(i)) 237 | self.test['label'].append(self.get_label(i)) 238 | self.train['label_v'] = to_categorical(self.train['label'], self.CLAN) 239 | self.test['label_v'] = to_categorical(self.test['label'], self.CLAN) 240 | for i in self.train: 241 | self.train[i] = np.array(self.train[i]) 242 | self.test[i] = np.array(self.test[i]) 243 | if self_train: 244 | self.candidate[i] = np.array(self.candidate[i]) 245 | if not self_train: 246 | self.candidate = copy.deepcopy(self.test) 247 | else: 248 | self.self_sam['XY'] = copy.deepcopy(self.train['XY']) 249 | self.self_sam['label'] = copy.deepcopy(self.train['label']) 250 | if n_perclass != 0: 251 | if self.AUG != 0: 252 | self.train = self.make_sample(self.train) 253 | 254 | # initial training samples, by given number of training and validation 255 | # samples for every class, the rest samples is test set. 256 | def init_sam2(self, ntrain_list, nvali_list): 257 | self.vali = {'sample': [], 258 | 'label': [], 259 | 'label_v': [], 260 | 'XY': [] 261 | } 262 | for i in range(self.CLAN): 263 | if len(ntrain_list) == self.CLAN: 264 | i_ = i 265 | else: 266 | i_ = 0 267 | if len(nvali_list) == self.CLAN: 268 | j_ = i 269 | else: 270 | j_ = 0 271 | c_label = list(np.array(np.where(self.img['gt'] == i)).T) 272 | random.shuffle(c_label) 273 | self.train['XY'].extend(c_label[:ntrain_list[i_]]) 274 | self.vali['XY'].extend(c_label[ntrain_list[i_]:ntrain_list[i_] + 275 | nvali_list[j_]]) 276 | self.test['XY'].extend(c_label[ntrain_list[i_] + nvali_list[j_]:]) 277 | random.shuffle(self.train['XY']) 278 | random.shuffle(self.vali['XY']) 279 | random.shuffle(self.test['XY']) 280 | 281 | for i in self.train['XY']: 282 | self.train['sample'].append(self.get_sample(i)) 283 | self.train['label'].append(self.get_label(i)) 284 | for i in self.test['XY']: 285 | self.test['sample'].append(self.get_sample(i)) 286 | self.test['label'].append(self.get_label(i)) 287 | for i in self.vali['XY']: 288 | self.vali['sample'].append(self.get_sample(i)) 289 | self.vali['label'].append(self.get_label(i)) 290 | self.train['label_v'] = to_categorical(self.train['label'], self.CLAN) 291 | self.test['label_v'] = to_categorical(self.test['label'], self.CLAN) 292 | self.vali['label_v'] = to_categorical(self.vali['label'], self.CLAN) 293 | 294 | for i in self.train: 295 | self.train[i] = np.array(self.train[i]) 296 | self.test[i] = np.array(self.test[i]) 297 | self.vali[i] = np.array(self.vali[i]) 298 | self.candidate = copy.deepcopy(self.test) 299 | if self.AUG != 0: 300 | self.train = self.make_sample(self.train) 301 | 302 | # load all pixel as samples for predicting, caution that large memory will 303 | # be occupied. 304 | def load_all_sam(self): 305 | self.all = {'sample': [], 306 | 'label': [], 307 | 'label_v': [], 308 | 'XY': [] 309 | } 310 | for i in range(self.IMGX): 311 | for j in range(self.IMGY): 312 | xy = np.array([i, j]) 313 | self.all['XY'].append(xy) 314 | self.all['sample'].append(self.get_sample(xy)) 315 | self.all['label'].append(self.get_label(xy)) 316 | 317 | def save(self, name): 318 | with h5py.File(name + '_img', 'w') as h5f: 319 | for i in self.img: 320 | h5f.create_dataset(i, data=self.img[i]) 321 | 322 | with h5py.File(name + '_train', 'w') as h5f: 323 | for i in self.train: 324 | h5f.create_dataset(i, data=self.train[i]) 325 | 326 | with h5py.File(name + '_candidate', 'w') as h5f: 327 | for i in self.candidate: 328 | h5f.create_dataset(i, data=self.candidate[i]) 329 | 330 | with h5py.File(name + '_test', 'w') as h5f: 331 | for i in self.test: 332 | h5f.create_dataset(i, data=self.test[i]) 333 | 334 | def save_all(self, name): 335 | with h5py.File(name, 'w') as h5f: 336 | for i in self.all: 337 | h5f.create_dataset(i, data=self.all[i]) 338 | 339 | def load_file(self, name): 340 | with h5py.File(name + '_img', 'r') as h5f: 341 | for i in h5f: 342 | self.img[i] = h5f[i][:] 343 | 344 | with h5py.File(name + '_train', 'r') as h5f: 345 | for i in h5f: 346 | self.train[i] = h5f[i][:] 347 | 348 | with h5py.File(name + '_candidate', 'r') as h5f: 349 | for i in h5f: 350 | self.candidate[i] = h5f[i][:] 351 | 352 | with h5py.File(name + '_test', 'r') as h5f: 353 | for i in h5f: 354 | self.test[i] = h5f[i][:] 355 | 356 | def load_all_file(self, name): 357 | with h5py.File(name, 'r') as h5f: 358 | for i in h5f: 359 | self.all[i] = h5f[i][:] 360 | 361 | def loop_sample(self, no_time, batch_size): 362 | samn = len(self.train['sample']) 363 | _s = no_time * batch_size % samn 364 | _t = _s + batch_size 365 | _sam = self.train['sample'][_s:_t] 366 | _lv = self.train['label_v'][_s:_t] 367 | _lab = self.train['label'][_s:_t] 368 | _delta = _t - samn 369 | if _delta > 0: 370 | _sam = np.concatenate([_sam, self.train['sample'][:_delta]]) 371 | _lv = np.concatenate([_lv, self.train['label_v'][:_delta]]) 372 | _lab = np.concatenate([_lab, self.train['label'][:_delta]]) 373 | return _sam, _lv, _lab 374 | 375 | # AL-selector 376 | def selector(self, stype, para): 377 | n = para[0] 378 | try: 379 | predict = para[1] 380 | except IndexError: 381 | pass 382 | if stype == 'RS': 383 | indexs = self.RS_sample(n) 384 | elif stype == 'BT': 385 | indexs = self.BT_sample(predict, n) 386 | elif stype == 'SM': 387 | indexs = self.SM_sample(predict, n) 388 | elif stype == 'MI': 389 | indexs = self.MI_sample(predict, n) 390 | elif stype == 'MBT': 391 | indexs = self.MBT_sample(predict, n) 392 | elif stype == 'entropy': 393 | indexs = self.entropy_sample(predict, n) 394 | self.add_sample(indexs) 395 | 396 | # filp, mirror 397 | def make_sample(self, origin): 398 | sample = origin['sample'] 399 | label = origin['label'] 400 | label_v = origin['label_v'] 401 | XY = origin['XY'] 402 | a = np.flip(sample, 1) 403 | b = np.flip(sample, 2) 404 | c = np.flip(b, 1) 405 | new = {} 406 | new['sample'] = np.concatenate((a, b, c, sample), axis=0) 407 | new['label'] = np.concatenate((label, label, label, label), axis=0) 408 | new['label_v'] = np.concatenate( 409 | (label_v, label_v, label_v, label_v), 410 | axis=0) 411 | new['XY'] = np.concatenate((XY, XY, XY, XY), axis=0) 412 | return new 413 | 414 | # return a sample(N*N sub-image), by given XY 415 | def get_sample(self, xy): 416 | d = self.SAMD 417 | x = xy[0] 418 | y = xy[1] 419 | try: 420 | self.img['im'][x][y] 421 | except IndexError: 422 | return [] 423 | # considering the padded pixel, xy should add d 424 | x += d 425 | y += d 426 | sam = self.img['pad'][(x - d): (x + d + 1), (y - d): (y + d + 1)] 427 | return np.array(sam) 428 | 429 | # return lebel of a sample, by given XY 430 | def get_label(self, xy): 431 | return self.img['gt'][xy[0]][xy[1]] 432 | 433 | # add samples to training set from candidate set 434 | def add_sample(self, indexs): 435 | new = {} 436 | for i in self.train: 437 | new[i] = self.candidate[i][indexs] 438 | self.candidate[i] = np.delete(self.candidate[i], indexs, axis=0) 439 | if self.AUG != 0: 440 | new = self.make_sample(new) 441 | for i in self.train: 442 | self.train[i] = np.append(self.train[i], new[i], 0) 443 | 444 | # Active Learning Algorithm 445 | def RS_sample(self, n): 446 | cand_sam = self.candidate 447 | index = list(range(len(cand_sam['sample']))) 448 | random.shuffle(index) 449 | return index[:n] 450 | 451 | def BT_sample(self, predict, n): 452 | index = np.argsort(-predict) 453 | diff = np.zeros((len(index), 2)) 454 | for i in range(len(index)): 455 | diff[i, 0] = predict[i, index[i, 0]] 456 | diff[i, 1] = predict[i, index[i, 1]] 457 | diff2 = diff[:, 0] - diff[:, 1] 458 | index = np.argsort(diff2) 459 | return index[:n] 460 | 461 | # sort by max probability 462 | def new_sample(self, predict, n): 463 | probability = predict.max(axis=1) 464 | index = np.argsort(probability) 465 | return index[:n] 466 | 467 | # cos 468 | def cos_sample(self, predict, n): 469 | probability = predict.max(axis=1) 470 | index = np.argsort(probability) 471 | return index[:n] 472 | 473 | def SM_sample(self, predict, n): 474 | index = np.argsort(-predict) 475 | diff = np.zeros((len(index), 2)) 476 | for i in range(len(index)): 477 | diff[i, 0] = predict[i, index[i, 0]] 478 | diff[i, 1] = predict[i, index[i, 1]] 479 | diff2 = diff[:, 1] 480 | index = np.argsort(-diff2) 481 | return index[:n] 482 | 483 | def MBT_sample(self, predict, n): 484 | predictlabel = np.argmax(predict, axis=1) 485 | total_index = [] 486 | total_p2 = [] 487 | for i in range(9): 488 | tmpindex = np.where(predictlabel == i) 489 | tmpindex = tmpindex[0].T 490 | classpredict = predict[tmpindex, :] 491 | classpredict[:, i] = 0.0 492 | maxx = np.max(classpredict, axis=1) 493 | index2 = np.argsort(-maxx) 494 | total_p2.append(maxx[index2[:2]]) 495 | total_index.append(tmpindex[index2[:2]]) 496 | total_p2 = np.array(total_p2).reshape(18) 497 | total_index = np.array(total_index).reshape(18) 498 | index3 = np.argsort(-total_p2.T)[:10] 499 | index = total_index[index3] 500 | return index[:n] 501 | 502 | def entropy_sample(self, predict, n): 503 | etp = scipy.stats.entropy(predict.T) 504 | index = np.argsort(-etp) 505 | return index[:n] 506 | 507 | # Self-Train Model 508 | def add_self_sam(self, x, y, label): 509 | self_map = self.self_sam['map'] 510 | try: 511 | self_map[x][y] 512 | if (x < 0) | (y < 0): 513 | raise IndexError 514 | except IndexError: 515 | return 516 | if (not self_map[x][y]): 517 | XY = np.array([x, y]) 518 | self.flush['XY'].append(XY) 519 | self.flush['label'].append(label) 520 | self.flush['sample'].append(self.get_sample(XY)) 521 | 522 | def st_flush(self): 523 | l = len(self.self_sam['label']) 524 | for i in self.flush: 525 | del self.flush[i] 526 | self.flush[i] = [] 527 | for i in range(l): 528 | xy = self.self_sam['XY'][i] 529 | label = self.self_sam['label'][i] 530 | self.add_self_sam(xy[0] - 1, xy[1], label) 531 | self.add_self_sam(xy[0] + 1, xy[1], label) 532 | self.add_self_sam(xy[0], xy[1] + 1, label) 533 | self.add_self_sam(xy[0], xy[1] - 1, label) 534 | for i in self.flush: 535 | self.flush[i] = np.array(self.flush[i]) 536 | return self.flush['sample'] 537 | 538 | def st_merge(self, predict): 539 | indexs = np.where(self.flush['label'] != predict) 540 | indexs = list(indexs[0]) 541 | for i in self.flush: 542 | self.flush[i] = np.delete(self.flush[i], indexs, axis=0) 543 | try: 544 | self.candidate[i] = np.append( 545 | self.candidate[i], 546 | self.flush[i], 547 | 0) 548 | except ValueError: 549 | self.candidate[i] = self.flush[i] 550 | self.candidate['label_v'] = to_categorical( 551 | self.candidate['label'], 552 | self.CLAN) 553 | for i in ['XY', 'label']: 554 | self.self_sam[i] = np.append(self.self_sam[i], self.flush[i], 0) 555 | for i in self.flush['XY']: 556 | self.self_sam['map'][i[0]][i[1]] = 1 557 | -------------------------------------------------------------------------------- /WCRN/Pavia_University/WCRN.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This script is used to definr a WCRN. 4 | 5 | author: Shengjie Liu, Haowen Luo 6 | """ 7 | 8 | from __future__ import print_function 9 | import keras 10 | from keras.models import Model 11 | from keras.layers import Dense, Flatten, Add 12 | from keras.layers import Conv2D, MaxPooling2D, Input, Activation 13 | from keras.initializers import RandomNormal 14 | 15 | 16 | # band is the number of band 17 | # ncla is the number of classes 18 | # nr is the number of residual layers 19 | # nk is the number of kernels 20 | def build(band, ncla, nr=1, nk=32): 21 | input_ = Input(shape=(5, 5, band)) 22 | inputs = keras.layers.core.Permute((3, 1, 2))(input_) 23 | inputs = keras.layers.core.Reshape((band, 5, 5, 1))(inputs) 24 | x1 = keras.layers.ConvLSTM2D(filters=nk, kernel_size=(3, 3), 25 | padding='valid', activation='tanh', 26 | recurrent_activation='hard_sigmoid', 27 | use_bias=True, 28 | kernel_initializer='glorot_uniform', 29 | recurrent_initializer='orthogonal', 30 | bias_initializer='zeros')(inputs) 31 | 32 | x2 = keras.layers.ConvLSTM2D(filters=nk, kernel_size=(1, 1), 33 | padding='valid', activation='tanh', 34 | recurrent_activation='hard_sigmoid', 35 | use_bias=True, 36 | kernel_initializer='glorot_uniform', 37 | recurrent_initializer='orthogonal', 38 | bias_initializer='zeros')(inputs) 39 | x1 = keras.layers.core.Reshape((3, 3, nk))(x1) 40 | x2 = keras.layers.core.Reshape((5, 5, nk))(x2) 41 | x1 = MaxPooling2D(pool_size=(3, 3))(x1) 42 | x2 = MaxPooling2D(pool_size=(5, 5))(x2) 43 | x = keras.layers.concatenate([x1, x2], axis=3) 44 | 45 | while nr: 46 | nr -= 1 47 | # residual 48 | x1 = keras.layers.BatchNormalization(axis=-1, 49 | momentum=0.9, 50 | epsilon=0.001, 51 | center=True, 52 | scale=True, 53 | beta_initializer='zeros', 54 | gamma_initializer='ones', 55 | moving_mean_initializer='zeros', 56 | moving_variance_initializer='ones' 57 | )(x) 58 | x1 = Activation('relu')(x1) 59 | x1 = Conv2D(2 * nk, kernel_size=(1, 1), 60 | kernel_initializer=RandomNormal(mean=0.0, stddev=0.01))(x1) 61 | x1 = keras.layers.BatchNormalization(axis=-1, 62 | momentum=0.9, 63 | epsilon=0.001, 64 | center=True, 65 | scale=True, 66 | beta_initializer='zeros', 67 | gamma_initializer='ones', 68 | moving_mean_initializer='zeros', 69 | moving_variance_initializer='ones' 70 | )(x1) 71 | x1 = Activation('relu')(x1) 72 | x1 = Conv2D(2 * nk, kernel_size=(1, 1), 73 | kernel_initializer=RandomNormal(mean=0.0, stddev=0.01))(x1) 74 | x = Add()([x1, x]) 75 | 76 | # x = Activation('relu')(x) 77 | # x = Dropout(0.5)(x) 78 | # x = Conv2D(128,kernel_size=(1,1), 79 | # kernel_initializer=RandomNormal(mean=0.0, stddev=0.01))(x) 80 | # x = Activation('relu')(x) 81 | # x = Dropout(0.5)(x) 82 | 83 | x = Flatten()(x) 84 | predict = Dense(ncla, activation='softmax')(x) 85 | model = Model(inputs=input_, outputs=predict) 86 | return model 87 | -------------------------------------------------------------------------------- /WCRN/Pavia_University/predict.asc.aux.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 0 6 | 8 7 | 256 8 | 1 9 | 0 10 | 19619|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|30676|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|3696|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|51628|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|17431|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|29447|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|19115|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|19982|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|15806 11 | 12 | 13 | 14 | 5.727261547083914 15 | 16 | 8 17 | 3.8135149469624 18 | 0 19 | 1 20 | 1 21 | 2.3931697697999 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /WCRN/README.md: -------------------------------------------------------------------------------- 1 | ## Wide Contextual Residual Network (WCRN) 2 | 3 | Author : Shengjie Liu, Haowen Luo (Equal Contribution) 4 | 5 | License : http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | If it helps, please STAR the project and CITE our papers. 8 | 9 | This is a wide contextual residual network (WCRN) with active learning (AL) for remote sensing image (RSI) classification. 10 | 11 | Though ResNets have achieved great success in various applications, its performance is limited by the requirement of abundant labeled samples. As it is very difficult and expensive to obtain class labels in real world, we integrate the proposed WCRN with AL to improve its generalization by using the most informative training samples. 12 | 13 | Specifically, we first design a WCRN for RSI classification, and then integrate it with AL to achieve good machine generalization with limited number of training sampling. Experimental results on Pavia University and Flevoland datasets demonstrate that the proposed WCRN with AL can significantly reduce the needs of samples. 14 | 15 | Environment: 16 | > We run the scripts in Windows OS.
17 | > Spyder with Python 3.6
18 | > Keras 2.0.8 using Tensorflow 1.2.1 backend
19 | > SSM.py 20 | 21 | Script: 22 | > Pavia_University
23 | > WCRN.py: the definition of the network.
24 | > SSM.py: a sample manager.
25 | > PU_train.py: an example script for Pavia University, used for training.
26 | > PU_predict.py: an example script for Pavia University, used for predicting. 27 | 28 | The Hyperspetral RSI of Pavia University is available at: [Hyperspectral Remote Sensing Scenes - Grupo de Inteligencia Computacional (GIC)](http://www.ehu.eus/ccwintco/index.php/Hyperspectral_Remote_Sensing_Scenes) 29 | 30 | ![poster](https://raw.githubusercontent.com/codeRimoe/DL_for_RSIs/master/WCRN/wcrn_igarss_poster.jpg) 31 | 32 | Reference: 33 | 34 | [S. Liu, H. Luo, Y. Tu, Z. He and J. Li, "Wide Contextual Residual Network with Active Learning for Remote Sensing Image Classification," IGARSS 2018 - 2018 IEEE International Geoscience and Remote Sensing Symposium, Valencia, 2018, pp. 7145-7148. doi: 10.1109/IGARSS.2018.8517855](https://ieeexplore.ieee.org/document/8517855) 35 | -------------------------------------------------------------------------------- /WCRN/WCRN.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | This script is used to definr a WCRN. 4 | 5 | author: Shengjie Liu, Haowen Luo 6 | """ 7 | 8 | from __future__ import print_function 9 | import keras 10 | from keras.models import Model 11 | from keras.layers import Dense, Flatten, Add 12 | from keras.layers import Conv2D, MaxPooling2D, Input, Activation 13 | from keras.initializers import RandomNormal 14 | 15 | 16 | # band is the number of band 17 | # ncla is the number of classes 18 | # nr is the number of residual layers 19 | # nk is the number of kernels 20 | def build(band, ncla, nr=1, nk=32): 21 | input_ = Input(shape=(5, 5, band)) 22 | inputs = keras.layers.core.Permute((3, 1, 2))(input_) 23 | inputs = keras.layers.core.Reshape((band, 5, 5, 1))(inputs) 24 | x1 = keras.layers.ConvLSTM2D(filters=nk, kernel_size=(3, 3), 25 | padding='valid', activation='tanh', 26 | recurrent_activation='hard_sigmoid', 27 | use_bias=True, 28 | kernel_initializer='glorot_uniform', 29 | recurrent_initializer='orthogonal', 30 | bias_initializer='zeros')(inputs) 31 | 32 | x2 = keras.layers.ConvLSTM2D(filters=nk, kernel_size=(1, 1), 33 | padding='valid', activation='tanh', 34 | recurrent_activation='hard_sigmoid', 35 | use_bias=True, 36 | kernel_initializer='glorot_uniform', 37 | recurrent_initializer='orthogonal', 38 | bias_initializer='zeros')(inputs) 39 | x1 = keras.layers.core.Reshape((3, 3, nk))(x1) 40 | x2 = keras.layers.core.Reshape((5, 5, nk))(x2) 41 | x1 = MaxPooling2D(pool_size=(3, 3))(x1) 42 | x2 = MaxPooling2D(pool_size=(5, 5))(x2) 43 | x = keras.layers.concatenate([x1, x2], axis=3) 44 | 45 | while nr: 46 | nr -= 1 47 | # residual 48 | x1 = keras.layers.BatchNormalization(axis=-1, 49 | momentum=0.9, 50 | epsilon=0.001, 51 | center=True, 52 | scale=True, 53 | beta_initializer='zeros', 54 | gamma_initializer='ones', 55 | moving_mean_initializer='zeros', 56 | moving_variance_initializer='ones' 57 | )(x) 58 | x1 = Activation('relu')(x1) 59 | x1 = Conv2D(2 * nk, kernel_size=(1, 1), 60 | kernel_initializer=RandomNormal(mean=0.0, stddev=0.01))(x1) 61 | x1 = keras.layers.BatchNormalization(axis=-1, 62 | momentum=0.9, 63 | epsilon=0.001, 64 | center=True, 65 | scale=True, 66 | beta_initializer='zeros', 67 | gamma_initializer='ones', 68 | moving_mean_initializer='zeros', 69 | moving_variance_initializer='ones' 70 | )(x1) 71 | x1 = Activation('relu')(x1) 72 | x1 = Conv2D(2 * nk, kernel_size=(1, 1), 73 | kernel_initializer=RandomNormal(mean=0.0, stddev=0.01))(x1) 74 | x = Add()([x1, x]) 75 | 76 | # x = Activation('relu')(x) 77 | # x = Dropout(0.5)(x) 78 | # x = Conv2D(128,kernel_size=(1,1), 79 | # kernel_initializer=RandomNormal(mean=0.0, stddev=0.01))(x) 80 | # x = Activation('relu')(x) 81 | # x = Dropout(0.5)(x) 82 | 83 | x = Flatten()(x) 84 | predict = Dense(ncla, activation='softmax')(x) 85 | model = Model(inputs=input_, outputs=predict) 86 | return model 87 | -------------------------------------------------------------------------------- /WCRN/wcrn_igarss_poster.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeRimoe/DL_for_RSIs/246cf32cfde7713d8659143033b26e60ec68f147/WCRN/wcrn_igarss_poster.jpg -------------------------------------------------------------------------------- /WCRN/wcrn_igarss_poster.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeRimoe/DL_for_RSIs/246cf32cfde7713d8659143033b26e60ec68f147/WCRN/wcrn_igarss_poster.pdf --------------------------------------------------------------------------------