Python 使用张量输入时,Keras模型预测会发生变化

Python 使用张量输入时,Keras模型预测会发生变化,python,tensorflow,keras,Python,Tensorflow,Keras,我想使用来自Keras的预训练Inception-V3模型,与来自Tensorflow的输入管道配对(即通过tensor提供网络的输入)。 这是我的代码: import tensorflow as tf from keras.preprocessing.image import load_img, img_to_array from keras.applications.inception_v3 import InceptionV3, decode_predictions, preprocess

我想使用来自Keras的预训练Inception-V3模型,与来自Tensorflow的输入管道配对(即通过tensor提供网络的输入)。 这是我的代码:

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!
将tensorflow导入为tf
从keras.preprocessing.image导入加载\u img、img\u到\u数组
从keras.applications.inception\u v3导入InceptionV3,解码\u预测,预处理\u输入
将numpy作为np导入
img_sample_filename='my_image.jpg'
img=img\u到\u数组(加载\u img(img\u示例\u文件名,目标\u大小=(299299)))
img=预处理输入(img)
img_张量=tf.常数(img[None,:])
#对于KERAS:
模型=接收v3()
pred=model.predict(img[None,:])

pred=decode_predictions(np.asarray(pred))#最后,在
InceptionV3
代码中,我发现了一个问题:
sess.run(init)
覆盖了
InceptionV3
的构造函数中加载的weigts。 我发现这个问题的-dirty-fix是在sess.run(init)
之后重新加载权重

注意
get\u file()
的参数直接取自
InceptionV3
的构造函数,在我的示例中,这些参数特定于使用
image\u data\u format='channels\u last'
恢复整个网络的权重。
我问他是否有更好的解决办法。如果需要获得更多信息,我将更新此答案。

您始终可以初始化变量子集,而不是初始化每个变量(包括模型预训练权重)。
from keras.applications.inception_v3 import get_file, WEIGHTS_PATH

with tf.Session() as sess:
  from keras import backend as K
  K.set_session(sess)

  sess.run(init)
  weights_path = get_file(
                'inception_v3_weights_tf_dim_ordering_tf_kernels.h5',
                WEIGHTS_PATH,
                cache_subdir='models',
                md5_hash='9a0d58056eeedaa3f26cb7ebd46da564')
  model.load_weights(weights_path)
  pred = sess.run([model.output], feed_dict={K.learning_phase(): 0})