├── .gitignore ├── convnet_fig.png ├── convnet_fig_with_omitted_channel.png ├── README.md └── draw_convnet.py /.gitignore: -------------------------------------------------------------------------------- 1 | /.venv/ 2 | -------------------------------------------------------------------------------- /convnet_fig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/horoscopes/draw_convnet/master/convnet_fig.png -------------------------------------------------------------------------------- /convnet_fig_with_omitted_channel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/horoscopes/draw_convnet/master/convnet_fig_with_omitted_channel.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # draw_convnet 2 | 3 | Python script for illustrating Convolutional Neural Network (ConvNet) 4 | 5 | ## Example image 6 | With `flag_omit=False` 7 | ![](https://raw.githubusercontent.com/gwding/draw_convnet/master/convnet_fig.png) 8 | 9 | With `flag_omit=True` 10 | ![](https://raw.githubusercontent.com/gwding/draw_convnet/ccaa14e2f8e41580bd29b97a501f7a4218779356/convnet_fig_with_omitted_channel.png) 11 | 12 | 13 | ## Known issues 14 | The issue with matplotlib 2.0.x has been resolved, please let me know if you encounter problems. 15 | 16 | ~~`Line2D` doesn't seem to work well under `python3 + matplotlib 2.0.0` as pointed out by @ahoereth~~ 17 | 18 | ## Using the code 19 | It is NOT required to cite anything to use the code. 20 | 21 | If you are not facing space limitation and it does not break the flow of the paper, you might consider adding something like "This figure is generated by adapting the code from https://github.com/gwding/draw_convnet" (maybe in the footnote). 22 | 23 | FYI, originally I used the code to generate the convnet figure in this paper "Automatic moth detection from trap images for pest management". 24 | -------------------------------------------------------------------------------- /draw_convnet.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright (c) 2017, Gavin Weiguang Ding 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | 3. Neither the name of the copyright holder nor the names of its contributors 16 | may be used to endorse or promote products derived from this software 17 | without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 23 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 | POSSIBILITY OF SUCH DAMAGE. 30 | """ 31 | 32 | 33 | import os 34 | import numpy as np 35 | import matplotlib.pyplot as plt 36 | plt.rcdefaults() 37 | from matplotlib.lines import Line2D 38 | from matplotlib.patches import Rectangle 39 | from matplotlib.patches import Circle 40 | 41 | NumDots = 4 42 | NumConvMax = 8 43 | NumFcMax = 20 44 | White = 1. 45 | Light = 0.7 46 | Medium = 0.5 47 | Dark = 0.3 48 | Darker = 0.15 49 | Black = 0. 50 | 51 | 52 | def add_layer(patches, colors, size=(24, 24), num=5, 53 | top_left=[0, 0], 54 | loc_diff=[3, -3], 55 | ): 56 | # add a rectangle 57 | top_left = np.array(top_left) 58 | loc_diff = np.array(loc_diff) 59 | loc_start = top_left - np.array([0, size[0]]) 60 | for ind in range(num): 61 | patches.append(Rectangle(loc_start + ind * loc_diff, size[1], size[0])) 62 | if ind % 2: 63 | colors.append(Medium) 64 | else: 65 | colors.append(Light) 66 | 67 | 68 | def add_layer_with_omission(patches, colors, size=(24, 24), 69 | num=5, num_max=8, 70 | num_dots=4, 71 | top_left=[0, 0], 72 | loc_diff=[3, -3], 73 | ): 74 | # add a rectangle 75 | top_left = np.array(top_left) 76 | loc_diff = np.array(loc_diff) 77 | loc_start = top_left - np.array([0, size[0]]) 78 | this_num = min(num, num_max) 79 | start_omit = (this_num - num_dots) // 2 80 | end_omit = this_num - start_omit 81 | start_omit -= 1 82 | for ind in range(this_num): 83 | if (num > num_max) and (start_omit < ind < end_omit): 84 | omit = True 85 | else: 86 | omit = False 87 | 88 | if omit: 89 | patches.append( 90 | Circle(loc_start + ind * loc_diff + np.array(size) / 2, 0.5)) 91 | else: 92 | patches.append(Rectangle(loc_start + ind * loc_diff, 93 | size[1], size[0])) 94 | 95 | if omit: 96 | colors.append(Black) 97 | elif ind % 2: 98 | colors.append(Medium) 99 | else: 100 | colors.append(Light) 101 | 102 | 103 | def add_mapping(patches, colors, start_ratio, end_ratio, patch_size, ind_bgn, 104 | top_left_list, loc_diff_list, num_show_list, size_list): 105 | 106 | start_loc = top_left_list[ind_bgn] \ 107 | + (num_show_list[ind_bgn] - 1) * np.array(loc_diff_list[ind_bgn]) \ 108 | + np.array([start_ratio[0] * (size_list[ind_bgn][1] - patch_size[1]), 109 | - start_ratio[1] * (size_list[ind_bgn][0] - patch_size[0])] 110 | ) 111 | 112 | 113 | 114 | 115 | end_loc = top_left_list[ind_bgn + 1] \ 116 | + (num_show_list[ind_bgn + 1] - 1) * np.array( 117 | loc_diff_list[ind_bgn + 1]) \ 118 | + np.array([end_ratio[0] * size_list[ind_bgn + 1][1], 119 | - end_ratio[1] * size_list[ind_bgn + 1][0]]) 120 | 121 | 122 | patches.append(Rectangle(start_loc, patch_size[1], -patch_size[0])) 123 | colors.append(Dark) 124 | patches.append(Line2D([start_loc[0], end_loc[0]], 125 | [start_loc[1], end_loc[1]])) 126 | colors.append(Darker) 127 | patches.append(Line2D([start_loc[0] + patch_size[1], end_loc[0]], 128 | [start_loc[1], end_loc[1]])) 129 | colors.append(Darker) 130 | patches.append(Line2D([start_loc[0], end_loc[0]], 131 | [start_loc[1] - patch_size[0], end_loc[1]])) 132 | colors.append(Darker) 133 | patches.append(Line2D([start_loc[0] + patch_size[1], end_loc[0]], 134 | [start_loc[1] - patch_size[0], end_loc[1]])) 135 | colors.append(Darker) 136 | 137 | 138 | 139 | def label(xy, text, xy_off=[0, 4]): 140 | plt.text(xy[0] + xy_off[0], xy[1] + xy_off[1], text, 141 | family='sans-serif', size=8) 142 | 143 | 144 | if __name__ == '__main__': 145 | 146 | fc_unit_size = 2 147 | layer_width = 40 148 | flag_omit = True 149 | 150 | patches = [] 151 | colors = [] 152 | 153 | fig, ax = plt.subplots() 154 | 155 | 156 | ############################ 157 | # conv layers 158 | size_list = [(32, 32), (18, 18), (10, 10), (6, 6), (4, 4)] 159 | num_list = [3, 32, 32, 48, 48] 160 | x_diff_list = [0, layer_width, layer_width, layer_width, layer_width] 161 | text_list = ['Inputs'] + ['Feature\nmaps'] * (len(size_list) - 1) 162 | loc_diff_list = [[3, -3]] * len(size_list) 163 | 164 | num_show_list = list(map(min, num_list, [NumConvMax] * len(num_list))) 165 | top_left_list = np.c_[np.cumsum(x_diff_list), np.zeros(len(x_diff_list))] 166 | 167 | for ind in range(len(size_list)-1,-1,-1): 168 | if flag_omit: 169 | add_layer_with_omission(patches, colors, size=size_list[ind], 170 | num=num_list[ind], 171 | num_max=NumConvMax, 172 | num_dots=NumDots, 173 | top_left=top_left_list[ind], 174 | loc_diff=loc_diff_list[ind]) 175 | else: 176 | add_layer(patches, colors, size=size_list[ind], 177 | num=num_show_list[ind], 178 | top_left=top_left_list[ind], loc_diff=loc_diff_list[ind]) 179 | label(top_left_list[ind], text_list[ind] + '\n{}@{}x{}'.format( 180 | num_list[ind], size_list[ind][0], size_list[ind][1])) 181 | 182 | ############################ 183 | # in between layers 184 | start_ratio_list = [[0.4, 0.5], [0.4, 0.8], [0.4, 0.5], [0.4, 0.8]] 185 | end_ratio_list = [[0.4, 0.5], [0.4, 0.8], [0.4, 0.5], [0.4, 0.8]] 186 | patch_size_list = [(5, 5), (2, 2), (5, 5), (2, 2)] 187 | ind_bgn_list = range(len(patch_size_list)) 188 | text_list = ['Convolution', 'Max-pooling', 'Convolution', 'Max-pooling'] 189 | 190 | for ind in range(len(patch_size_list)): 191 | add_mapping( 192 | patches, colors, start_ratio_list[ind], end_ratio_list[ind], 193 | patch_size_list[ind], ind, 194 | top_left_list, loc_diff_list, num_show_list, size_list) 195 | label(top_left_list[ind], text_list[ind] + '\n{}x{} kernel'.format( 196 | patch_size_list[ind][0], patch_size_list[ind][1]), xy_off=[26, -65] 197 | ) 198 | 199 | 200 | ############################ 201 | # fully connected layers 202 | size_list = [(fc_unit_size, fc_unit_size)] * 3 203 | num_list = [768, 500, 2] 204 | num_show_list = list(map(min, num_list, [NumFcMax] * len(num_list))) 205 | x_diff_list = [sum(x_diff_list) + layer_width, layer_width, layer_width] 206 | top_left_list = np.c_[np.cumsum(x_diff_list), np.zeros(len(x_diff_list))] 207 | loc_diff_list = [[fc_unit_size, -fc_unit_size]] * len(top_left_list) 208 | text_list = ['Hidden\nunits'] * (len(size_list) - 1) + ['Outputs'] 209 | 210 | for ind in range(len(size_list)): 211 | if flag_omit: 212 | add_layer_with_omission(patches, colors, size=size_list[ind], 213 | num=num_list[ind], 214 | num_max=NumFcMax, 215 | num_dots=NumDots, 216 | top_left=top_left_list[ind], 217 | loc_diff=loc_diff_list[ind]) 218 | else: 219 | add_layer(patches, colors, size=size_list[ind], 220 | num=num_show_list[ind], 221 | top_left=top_left_list[ind], 222 | loc_diff=loc_diff_list[ind]) 223 | label(top_left_list[ind], text_list[ind] + '\n{}'.format( 224 | num_list[ind])) 225 | 226 | text_list = ['Flatten\n', 'Fully\nconnected', 'Fully\nconnected'] 227 | 228 | for ind in range(len(size_list)): 229 | label(top_left_list[ind], text_list[ind], xy_off=[-10, -65]) 230 | 231 | ############################ 232 | for patch, color in zip(patches, colors): 233 | patch.set_color(color * np.ones(3)) 234 | if isinstance(patch, Line2D): 235 | ax.add_line(patch) 236 | else: 237 | patch.set_edgecolor(Black * np.ones(3)) 238 | ax.add_patch(patch) 239 | 240 | plt.tight_layout() 241 | plt.axis('equal') 242 | plt.axis('off') 243 | plt.show() 244 | fig.set_size_inches(8, 2.5) 245 | 246 | fig_dir = './' 247 | fig_ext = '.png' 248 | fig.savefig(os.path.join(fig_dir, 'convnet_fig' + fig_ext), 249 | bbox_inches='tight', pad_inches=0) 250 | --------------------------------------------------------------------------------