Skip to main content
 首页 » 编程设计

python之在 TensorFlow 上使用 Inception 时出错(所有图片输出相同)

2024年10月17日24myhome

我正在尝试在 cifar-10 数据集上训练网络,但我不想使用图片,而是想使用 Inceptions 中最后一层之前的特征。

所以我写了一些和平的pf代码来传递Inception中的所有图片并获取特征,这里是:

def run_inference_on_images(images): 
 #Creates graph from saved GraphDef. 
 create_graph() 
 
 features_vec = np.ndarray(shape=(len(images),2048),dtype=np.float32) 
 
 with tf.Session() as sess: 
   # Some useful tensors: 
   # 'pool_3:0': A tensor containing the next-to-last layer containing 2048 
   #   float description of the image. 
   # 'DecodeJpeg:0': A numpy array of the image 
   # Runs the softmax tensor by feeding the image data as input to the graph. 
   length = len(images) 
   for i in range(length): 
       print ('inferencing image number',i,'out of', length) 
       features_tensor = sess.graph.get_tensor_by_name('pool_3:0') 
       features = sess.run(features_tensor, 
                        {'DecodeJpeg:0': images[i]}) 
       features_vec[i] = np.squeeze(features) 
 return features_vec 

“图像”是 CIFAR-10 数据集。这是一个形状为 (50000,32,32,3) 的 numpy 数组

我面临的问题是,即使我将不同的图片提供给“sess.run”部分,“功能”输出始终相同。 我错过了什么吗?

请您参考如下方法:

我能够解决这个问题。 Inception 似乎无法像我想的那样处理 numPy 数组,所以我将数组转换为 JPEG 图片,然后才将其提供给网络。

下面是有效的代码(其余部分相同):

def run_inference_on_images(images): 
  # Creates graph from saved GraphDef. 
  create_graph() 
 
  features_vec = np.ndarray(shape=(len(images),2048),dtype=np.float32) 
  with tf.Session() as sess: 
    features_tensor = sess.graph.get_tensor_by_name('pool_3:0') 
    length = len(images) 
    for i in range(length): 
        im = Image.fromarray(images[i],'RGB') 
        im.save("tmp.jpeg") 
        data = tf.gfile.FastGFile("tmp.jpeg", 'rb').read() 
        print ('inferencing image number',i,'out of', length) 
        features = sess.run(features_tensor, 
                        {'DecodeJpeg/contents:0': data}) 
        features_vec[i] = np.squeeze(features)        
   return features_vec