无需会话即可将张量转换为 numpy [英] Convert tensor to numpy without a session

查看:33
本文介绍了无需会话即可将张量转换为 numpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 上使用 tensorflow 的 estimator 库.我想使用经过预训练的老师来训练学生网络.我面临以下问题.

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)

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

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)

这要求 x 和 y 是 numpy 数组,所以我通过使用诸如使用会话将张量转换为 numpy 的丑陋技巧来转换它.有没有更好的方法来做到这一点?

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?

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

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

推荐答案

使用 tf.make_ndarray 将 Tensor 转换为 Numpy_array.

Convert Tensor to Numpy_array using tf.make_ndarray.

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

tf.make_ndarray(), Create a numpy ndarray with the same shape and data as the tensor.

示例工作代码:

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)

这篇关于无需会话即可将张量转换为 numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆