代码之家  ›  专栏  ›  技术社区  ›  duhaime

从Tensorflow Hub模块提取numpy数组(张量到numpy转换)

  •  0
  • duhaime  · 技术社区  · 6 年前

    我正在尝试使用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 ndarray”,但我的 np.add() 上面的调用返回对象类型 tensorflow.python.framework.ops.Tensor .有人知道我如何从中获得numpy数组吗 out

    版本 :

    # 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
    
    0 回复  |  直到 6 年前
        1
  •  2
  •   thushv89    6 年前

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

    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
  •  0
  •   Gino Mempin Brijesh Sondarva    5 年前

    你可以用

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