Convert tensor to numpy without a session

我的梦境 提交于 2020-05-30 07:20:30

问题


I'm using the estimator library of tensorflow on python. I want to train a student network by using a pre-trained teacher.I'm facing the following issue.

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)

This code returns a generator object that is passed to a student classifier. Inside the generator, we have the inputs and labels (in batches of 100) as tensors. The problem is, I want to pass the same values to the teacher model and extract its softmax outputs. But unfortunately, the model input requires a numpy array as follows

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)

This requires x and y to be numpy arrays so I converted it via using such as ugly hack of using a session to convert tensor to numpy. Is there a better way of doing this?

P.S. I tried tf.estimator.Estimator.get_variable_value() but it retrieves weights from the model, not the input and output

来源:https://stackoverflow.com/questions/52148590/convert-tensor-to-numpy-without-a-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!