【问题标题】:Extracting numpy array from Tensorflow-Hub Module (tensor to numpy conversion)从 Tensorflow-Hub 模块中提取 numpy 数组(张量到 numpy 的转换)
【发布时间】:2019-12-16 20:35:50
【问题描述】:

我正在尝试开始使用 Tensorflow-Hub 从图像中提取特征向量。但是,我不确定如何将 Tensorflow-Hub 输出(张量)转换为 numpy 向量。这是一个简单的例子:

from keras.preprocessing.image import load_img
import tensorflow_hub as hub
import tensorflow as tf
import numpy as np

im = load_img('sample.png')
im = np.expand_dims(im.resize((299,299)), 0)

module = hub.Module("https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1")
out = module(im)

o = np.add(out, 0)
type(o)

docs 表示“NumPy 操作自动将张量转换为 NumPy ndarrays”,但我上面的np.add() 调用返回对象类型tensorflow.python.framework.ops.Tensor。有谁知道我如何从out 获得一个 numpy 数组?任何指针将不胜感激!

版本

# output from `pip freeze | grep tensorflow`
tensorflow==1.14.0
tensorflow-estimator==1.14.0
tensorflow-hub==0.1.1
tensorflow-probability==0.6.0

【问题讨论】:

    标签: python arrays numpy tensorflow


    【解决方案1】:

    以下应该有效。但是我没有检查输出是否有意义。但它会在多次运行中返回一致的结果。

    im = load_img('sample.png')
    im = np.expand_dims(im.resize((299,299)), 0)
    
    module = hub.Module("https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1")
    
    out = module(im)
    
    with tf.Session() as sess:
      tf.global_variables_initializer().run()
      o = sess.run(out)
      o = np.add(o, 0)
      print(type(o))
    

    【讨论】:

      【解决方案2】:

      你可以使用

      out.numpy()
      
      type(out)  
      # <class 'tensorflow.python.framework.ops.EagerTensor'>
      
      type(out.numpy()
      # <class 'numpy.ndarray'>
      

      【讨论】:

        猜你喜欢
        • 2020-12-31
        • 2016-03-09
        • 1970-01-01
        • 2021-10-13
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 2018-11-28
        • 1970-01-01
        相关资源
        最近更新 更多