简体   繁体   中英

keras model.predict() is slow

I try to create a heatmap of the perceptron's outputs by solving xor problem, but

model.predict (np.array ([[i / 255, i2 / 255]]))

It takes a long time to generate the map. How can I run this faster?

code to generate the model

from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
import numpy as np 
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
import numpy as np 

#X son los datos de entrada
#y son la salida correpondiente a cada entrada
X = np.array([[0,0],[0,1],[1,0],[1,1]])
y = np.array([[0],[1],[1],[0]])

model = Sequential()
model.add(Dense(8, input_dim=2))
model.add(Activation('tanh'))
model.add(Dense(1))
model.add(Activation('sigmoid'))

sgd = SGD(lr=0.1)
model.compile(loss='binary_crossentropy', optimizer=sgd)

model.fit(X, y, batch_size=1, nb_epoch=1000)

code to draw heatmap of the outputs for the problem xor

from PIL import Image

img = Image.new('RGB', (320, 280))
pixels = img.load()
for i2 in range(255):
    for i in range(255):
       g=model.predict(np.array([[i/255,i2/255]]))
       pixels[i,i2] = (0,g*255,0)
plt.imshow(img)

The problem is that you are calling model.predict() 65536 times for a single vector. This is quite inefficient. Calculate the input vectors beforehand and run predict only once then. Takes 2 seconds on my machine.

x = np.linspace(0,1,256)
img = list()
for i in range(256):
    for j in range(256):
        img.append([x[j],x[i]])
pred=model.predict(np.array(img),verbose=1)
plt.imshow(pred.reshape((256,256)))
plt.colorbar()
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM