Crystal.W
Crystal.W

Reputation: 21

Model visualization error: 'file' not defined

I am trying to use the Keras visualization module:

# Begin a model
model = Sequential()  
model.add(Convolution2D(4,1,5,input_shape=(1,1,49),init='uniform',weights=None,border_mode='valid') )   
model.add(Activation('tanh')) 
model.add(MaxPooling2D(pool_size=(1, 2)))
model.add(Flatten())  
model.add(Dense(600,init='normal'))
model.add(Activation('tanh'))   
model.add(Dense(2, init='normal'))  
model.add(Activation('softmax'))  
model.summary()
sgd = SGD(lr=list_lr[i], decay=0.0, momentum=0.1, nesterov=False)
model.compile(loss='categorical_crossentropy', metrics=['accuracy'],optimizer=sgd)

# using visualization
from keras.utils.visualize_util import plot
plot(model, to_file='/home/wj/DL/model.png')

model.fit(X_train,train_label, batch_size=list_batch[j], nb_epoch=list_epoch[k],shuffle=False,verbose=2,validation_split=0.2)

I get the following error:

Traceback (most recent call last):
File "6.2.4.cnn.py", line 85, in  <module>
    plot(model, to_file='/home/wj/DL/model.png')
File "/usr/local/lib/python3.4/dist-packages/keras/utils/visualize_util.py", line 67, in plot    dot.write_png(to_file)
File "/usr/local/lib/python3.4/dist-packages/pydot.py", line 1809, in    <lambda>
    lambda path, f=frmt, prog=self.prog : self.write(path, format=f, prog=prog))
File "/usr/local/lib/python3.4/dist-packages/pydot.py",    line 1895, in write    dot_fd = file(path, "w+b")
    NameError: name 'file' is not defined

What am I doing wrong?

Upvotes: 2

Views: 6863

Answers (1)

hpwww
hpwww

Reputation: 565

Take your model as example.

Import and define your model.

from keras.models import Sequential
from keras.layers import Dense, Activation, Convolution2D, MaxPooling2D,Flatten

model = Sequential()  
model.add(Convolution2D(4,1,5,input_shape=(1,1,49),init='uniform',weights=None,border_mode='valid') )   
model.add(Activation('tanh')) 
model.add(MaxPooling2D(pool_size=(1, 2)))
model.add(Flatten())  
model.add(Dense(600,init='normal'))
model.add(Activation('tanh'))   
model.add(Dense(2, init='normal'))  
model.add(Activation('softmax'))  

Before plotting the model, make sure you have already install libraries: Install pydot,

pip install git+https://github.com/nlhepler/pydot.git

and graphviz,

sudo apt-get install graphviz

Then, import the necessary libraries and call lib. to plot your model.

from IPython.display import Image, display, SVG
from keras.utils.visualize_util import model_to_dot

# Show the model in ipython notebook
figure = SVG(model_to_dot(model, show_shapes=True).create(prog='dot', format='svg'))
display(figure)

# Save the model as png file
from keras.utils.visualize_util import plot
plot(model, to_file='model.png', show_shapes=True)

Upvotes: 1

Related Questions