Git Product home page Git Product logo

convnet-drawer's Introduction

ConvNet Drawer

Python script for illustrating Convolutional Neural Networks (CNN). Inspired by the draw_convnet project [1].

Models can be visualized via Keras-like (Sequential) model definitions. The result can be saved as SVG file or pptx file!

Requirements

python-pptx (if you want to save models as pptx)

pip install python-pptx

Keras (if you want to convert Keras sequential model)

pip install keras

matplotlib (if you want to save models via matplotlib)

pip install matplotlib

Usage

Write a script to define and save a model. An example of visualizing AlexNet [2] is as follows.

Write and save convnet_drawer.Model

from convnet_drawer import Model, Conv2D, MaxPooling2D, Flatten, Dense
from pptx_util import save_model_to_pptx
from matplotlib_util import save_model_to_file

model = Model(input_shape=(227, 227, 3))
model.add(Conv2D(96, (11, 11), (4, 4)))
model.add(MaxPooling2D((3, 3), strides=(2, 2)))
model.add(Conv2D(256, (5, 5), padding="same"))
model.add(MaxPooling2D((3, 3), strides=(2, 2)))
model.add(Conv2D(384, (3, 3), padding="same"))
model.add(Conv2D(384, (3, 3), padding="same"))
model.add(Conv2D(256, (3, 3), padding="same"))
model.add(MaxPooling2D((3, 3), strides=(2, 2)))
model.add(Flatten())
model.add(Dense(4096))
model.add(Dense(4096))
model.add(Dense(1000))

# save as svg file
model.save_fig("example.svg")

# save as pptx file
save_model_to_pptx(model, "example.pptx")

# save via matplotlib
save_model_to_file(model, "example.pdf")

Result:

The other examples can be found here.

Convert Keras sequential model

Keras sequential model can be converted to convnet_drawer.Model (thanks to @wakamezake). Only Conv2D, MaxPooling2D, GlobalAveragePooling2D, Flatten, Dense layers are supported for this conversion.

from keras_util import convert_drawer_model
from keras_models import AlexNet
from pptx_util import save_model_to_pptx
from matplotlib_util import save_model_to_file

# get Keras sequential model
keras_sequential_model = AlexNet.get_model()
model = convert_drawer_model(keras_sequential_model)

# save as svg file
model.save_fig("example.svg")

# save as pptx file
save_model_to_pptx(model, "example.pptx")

# save via matplotlib
save_model_to_file(model, "example.pdf")

Supported Layers

  • Conv2D
    • Conv2D(filters=None, kernel_size=None, strides=(1, 1), padding="valid")
    • e.g. Conv2D(96, (11, 11), (4, 4)))
  • Deconv2D
    • Deconv2D(filters=None, kernel_size=None, strides=(1, 1), padding="valid")
    • e.g. Deconv2D(256, (3, 3), (2, 2)))
  • MaxPooling2D, AveragePooling2D
    • MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid")
    • e.g. MaxPooling2D((3, 3), strides=(2, 2))
    • If strides = None, stride is set to be pool_size.
  • GlobalAveragePooling2D
    • GlobalAveragePooling2D()
  • Flatten
    • Flatten()
  • Dense
    • Dense(units)
    • e.g. Dense(4096)

Visualization Parameters

Visualization Parameters can be found in config.py. Please adjust these parameters before model definition (see LeNet.py). The most important parameter is channel_scale = 3 / 5. This parameter rescale actual channel size c to c_ for visualization as:

c_ = math.pow(c, channel_scale)

If the maximum channel size is small (e.g. 512), please increase channel_scale.

Check how the other parameters works:

Default Values

theta = - math.pi / 6
ratio = 0.7
bounding_box_margin = 10
inter_layer_margin = 50
text_margin = 10
channel_scale = 3 / 5
text_size = 14
one_dim_width = 4
line_color_feature_map = (0, 0, 0)
line_color_layer = (0, 0, 255)
text_color_feature_map = (0, 0, 0)
text_color_layer = (0, 0, 0)

TODOs

  • Implement padding option for Conv2D and Pooling layers.
  • Add some effects to Dense layer (and Flatten / GlobalAveragePooling2D).
  • Automatically calibrate the scale of feature maps for better visibility.
  • Move hard-coded parameters to a config file or options.
  • Refactor Layer classes.
  • Draw with matplotlib? for other formats. The model is now directly saved as a pptx file.

Results

LeNet

AlexNet

ZFNet

VGG16

AutoEncoder

AlexNet saved by matplotlib with plt.xkcd()

References

[1] https://github.com/gwding/draw_convnet

[2] A. Krizhevsky, I. Sutskever, and G. E. Hinton, "ImageNet Classification with Deep Convolutional Neural Networks," in Proc. of NIPS, 2012.

convnet-drawer's People

Contributors

wakame1367 avatar xsthunder avatar yu4u avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

convnet-drawer's Issues

Export PPTX issue/question

Hi there,

Thanks for making this great project! I am interested in using the project to export CNN diagrams in powerpoint, however I am running into an issue I was wondering if you maybe know how to troubleshoot.

I downloaded AlexNet.pptx from your repo and the graph looks like its not being rendered on the powerpoint correctly, here is a screenshot of what I am seeing in powerpoint:

image

It seems that the render location is going beyond the white region area, and going off the slides. Is this an issue on my powerpoint file, or do I have to offset the location in order to have the diagram rendered correctly.

When I export it to jpg, the rendering issue exists.
AlexNet

Please advise if you need more information, and I look forward to your response!

Missing Keras Layers

The Dropout-Layer doesnt seem to be represented.
Error comes from the keras_util
NameError: name 'Dropout' is not defined

Matplotlib_util get an error

Hi there,

I'm getting an error everytime I want to generate the graph into the pdf file:

  File "C:\Users\ngenne\Desktop\PRIVE-Deep-Learning\NIH\chest-xray\convnet_drawer\matplotlib_util.py", line 10, in save_model_to_file
    plt.xlim(model.x, model.x + model.width)

AttributeError: 'Sequential' object has no attribute 'x'

Below my code:

from convnet_drawer.convnet_drawer import Model, Conv2D, MaxPooling2D, Flatten, Dense
from convnet_drawer.keras_util import convert_drawer_model
from convnet_drawer.matplotlib_util import save_model_to_file
from keras.models import Sequential
from convnet_drawer.keras_models import AlexNet

classifier = Sequential()



classifier = Model(input_shape=(1024, 1024, 1))
classifier.add(Conv2D(512, (256,256), strides=(4, 4), padding="same"))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Conv2D(512, (256,256), strides=(4, 4), padding="same"))
classifier.add(Conv2D(512, (256,256), strides=(4, 4), padding="same"))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Flatten())
classifier.add(Dense(4096))
classifier.add(Dense(4096))
classifier.add(Dense(1000))

classifier = AlexNet.get_model()
classifier_seq = convert_drawer_model(classifier)

Do you have a trick for me?

AttributeError: 'str' object has no attribute 'get'

I receive an error about 'str' object has no attribute 'get':

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D

model = Sequential()

model.add(Conv2D(16, kernel_size=3, strides=3, activation='relu',
data_format="channels_last", input_shape=(129,1173,1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, kernel_size=3, strides=3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=3, strides=3, activation='relu'))
model.add(Flatten())
model.add(Dense(units=256, activation='relu'))
model.add(Dense(units=128, activation='relu'))
model.add(Dense(units=64, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')

model_draw = convert_drawer_model(model)
model_draw.save_fig("11.svg")


AttributeError Traceback (most recent call last)
in
----> 1 model_draw = convert_drawer_model(model)
2 model_draw.save_fig("11.svg")

~/Notebooks/convnet-drawer/keras_util.py in convert_drawer_model(model)
33 figure = Model(input_shape=_input_shape[1:])
34 for config in model.get_config():
---> 35 class_name = config.get("class_name", False)
36 class_config = config.get("config", False)
37 if class_name and class_config:

AttributeError: 'str' object has no attribute 'get'

Unable to save model as pptx file

Hi there,

Another error to declare:

  File "C:\Users\ngenne\Desktop\PRIVE-Deep-Learning\NIH\chest-xray\convnet_drawer\pptx_util.py", line 63, in save_model_to_pptx
    for feature_map in model.feature_maps + model.layers:

AttributeError: 'Sequential' object has no attribute 'feature_maps'

Code is below:

from convnet_drawer.convnet_drawer import Model, Conv2D, MaxPooling2D, Flatten, Dense
from convnet_drawer.keras_util import convert_drawer_model
from convnet_drawer.matplotlib_util import save_model_to_file
from convnet_drawer.pptx_util import save_model_to_pptx
from keras.models import Sequential
from convnet_drawer.keras_models import AlexNet

classifier = Sequential()

classifier = Model(input_shape=(1024, 1024, 1))
classifier.add(Conv2D(512, (256,256), strides=(4, 4), padding="same"))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Conv2D(512, (256,256), strides=(4, 4), padding="same"))
classifier.add(Conv2D(512, (256,256), strides=(4, 4), padding="same"))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Flatten())
classifier.add(Dense(4096))
classifier.add(Dense(4096))
classifier.add(Dense(1000))

classifier = AlexNet.get_model()
classifier_seq = convert_drawer_model(classifier)

classifier.save_model_to_pptx(classifier, "classifier.pptx")

Could you help me please?

convert_drawer_model fail when GlobalAveragePooling2D layer is included

Hi there,
I have come across some problem. convert_drawer_model from keras_util fail when GlobalAveragePooling2D layer is included. But it is said here that GlobalAveragePooling2D is supported.
Thanks in advance.

update

fix this problem. see pr #12

my code

from keras_util import convert_drawer_model
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense,Dropout,Activation,Flatten
from keras.layers import Conv2D,MaxPool2D,GlobalAveragePooling2D,AveragePooling2D
from keras import optimizers
from keras.callbacks import ReduceLROnPlateau,EarlyStopping
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l2

batch_size = 128
epochs = 30
num_classes = 10
weight_decay = 1e-6
nets = 15

model = Sequential()

model.add(Conv2D(192,(5,5),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal',input_shape=(28,28,1)))
#model.add(BatchNormalization())
#model.add(Activation('relu'))
model.add(Conv2D(160,(1,1),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal'))
#model.add(BatchNormalization())
#model.add(Activation('relu'))
model.add(Conv2D(96,(1,1),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal'))
#model.add(BatchNormalization())
#model.add(Activation('relu'))
model.add(MaxPool2D(pool_size=(3,3),strides=(2,2),padding='same'))

#model.add(Dropout(0.2))

model.add(Conv2D(192,(5,5),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal'))
#model.add(BatchNormalization())
#model.add(Activation('relu'))
model.add(Conv2D(192,(1,1),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal'))
#model.add(BatchNormalization())
#model.add(Activation('relu'))
model.add(Conv2D(192,(1,1),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal'))
#model.add(BatchNormalization())
#model.add(Activation('relu'))
model.add(MaxPool2D(pool_size=(3,3),strides=(2,2),padding='same'))

#model.add(Dropout(0.2))

model.add(Conv2D(192,(3,3),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal'))
#model.add(BatchNormalization())
#model.add(Activation('relu'))
model.add(Conv2D(192,(1,1),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal'))
#model.add(BatchNormalization())
#model.add(Activation('relu'))
model.add(Conv2D(10,(1,1),padding='same',kernel_regularizer=l2(weight_decay),kernel_initializer='he_normal'))
#model.add(BatchNormalization())
#model.add(Activation('relu'))  

model.add(GlobalAveragePooling2D())
#model.add(Activation('softmax'))

#adam = optimizers.rmsprop()
#model.compile(loss='categorical_crossentropy',optimizer=adam,metrics=['accuracy'])

Error

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-19-677489d1360a> in <module>
----> 1 convert_drawer_model(model).save_fig('tmp.svg')

~/python_lib/convnet_drawer/keras_util.py in convert_drawer_model(model)
     36         class_config = config.get("config", False)
     37         if class_name and class_config:
---> 38             class_obj = is_class_object(class_name)
     39             if class_name == "Conv2D":
     40                 conv_2d = get_conv2d_obj(class_obj, class_config)

~/python_lib/convnet_drawer/keras_util.py in is_class_object(class_name)
     26 
     27 def is_class_object(class_name):
---> 28     return eval(class_name)
     29 
     30 

~/python_lib/convnet_drawer/keras_util.py in <module>

NameError: name 'GlobalAveragePooling2D' is not defined

I really love your work, however

I really love your work, as I said earlier but why don't you add the other layers, (Batch Normalization, Activation, Dropout, Zero Padding 2D, Max Pooling 2D), or at least package your code?

I am ready and willing to contribute with you, if you want..

Run error

Hi, I follow every step of the instruction, however, does not work, anyone can help me, thank you!

Traceback (most recent call last):
File "D:/lyceum/plot_CNN_architecture/CNN_archi.py", line 23, in
save_model_to_pptx(model, "1.pptx")
File "D:\lyceum\plot_CNN_architecture\pptx_util.py", line 63, in save_model_to_pptx
presentation.add_line(obj.x1, obj.y1, obj.x2, obj.y2, obj.color, obj.width, obj.dasharray)
File "D:\lyceum\plot_CNN_architecture\pptx_util.py", line 29, in add_line
connector.ln = connector.get_or_add_ln()
AttributeError: can't set attribute

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.