【发布时间】:2017-11-21 11:35:53
【问题描述】:
我想使用来自 Keras 的预训练 Inception-V3 模型,与来自 Tensorflow 的输入管道配对(即通过张量提供网络的输入输入)。 这是我的代码:
import tensorflow as tf
from keras.preprocessing.image import load_img, img_to_array
from keras.applications.inception_v3 import InceptionV3, decode_predictions, preprocess_input
import numpy as np
img_sample_filename = 'my_image.jpg'
img = img_to_array(load_img(img_sample_filename, target_size=(299,299)))
img = preprocess_input(img)
img_tensor = tf.constant(img[None,:])
# WITH KERAS:
model = InceptionV3()
pred = model.predict(img[None,:])
pred = decode_predictions(np.asarray(pred)) #<------ correct prediction!
print(pred)
# WITH TF:
model = InceptionV3(input_tensor=img_tensor)
init = tf.global_variables_initializer()
with tf.Session() as sess:
from keras import backend as K
K.set_session(sess)
sess.run(init)
pred = sess.run([model.output], feed_dict={K.learning_phase(): 0})
pred = decode_predictions(np.asarray(pred)[0])
print(pred) #<------ wrong prediction!
my_image.jpg 是我想要分类的任何图像。
如果我使用 keras 的 predict 函数来计算预测,结果是正确的。但是,如果我从图像数组中创建一个张量并通过input_tensor=... 将该张量提供给模型,然后通过sess.run([model.output], ...) 计算预测,则结果非常错误。
不同行为的原因是什么?不能这样使用 Keras 网络吗?
【问题讨论】:
标签: python tensorflow keras