【问题标题】:Convert tensor to numpy without a session在没有会话的情况下将张量转换为 numpy
【发布时间】:2018-09-03 11:10:44
【问题描述】:

我在 python 上使用 tensorflow 的估计器库。我想通过使用预先训练的老师来训练学生网络。我面临以下问题。

train_input_fn = tf.estimator.inputs.numpy_input_fn(
  x={"x": train_data},
  y=train_labels,
  batch_size=100,
  num_epochs=None,
  shuffle=True)

student_classifier.train(
  input_fn=train_input_fn,
  steps=20,
  hooks=None)

此代码返回传递给学生分类器的生成器对象。在生成器内部,我们将输入和标签(每批 100 个)作为张量。问题是,我想将相同的值传递给教师模型并提取其 softmax 输出。但不幸的是,模型输入需要一个numpy数组如下

student_classifier = tf.estimator.Estimator(
  model_fn=student_model_fn, model_dir="./models/mnist_student")

def student_model_fn(features, labels, mode): 
  sess=tf.InteractiveSession()
  tf.train.start_queue_runners(sess)
  data=features['x'].eval()
  out=labels.eval()
  sess.close()

  input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])
  eval_teacher_fn = tf.estimator.inputs.numpy_input_fn(
      x={"x":data},
      y=out,
      num_epochs=1,
      shuffle=False)

这要求 x 和 y 是 numpy 数组,所以我通过使用诸如使用会话将张量转换为 numpy 的丑陋 hack 来转换它。有更好的方法吗?

附:我试过tf.estimator.Estimator.get_variable_value(),但它从模型中检索权重,而不是输入和输出

【问题讨论】:

    标签: python-3.x tensorflow tensorflow-estimator


    【解决方案1】:

    使用tf.make_ndarray 将张量转换为 Numpy_array。

    tf.make_ndarray(),创建一个与张量具有相同形状和数据的numpy ndarray。

    示例工作代码:

    import tensorflow as tf
    a = tf.constant([[1,2,3],[4,5,6]])
    proto_tensor = tf.make_tensor_proto(a)  
    tf.make_ndarray(proto_tensor)
    

    输出:

    array([[1, 2, 3],
         [4, 5, 6]], dtype=int32)
    # output has shape (2,3)
    

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 2016-12-03
      • 2021-04-28
      • 2022-08-11
      • 1970-01-01
      • 2019-06-26
      • 2019-10-20
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多