繁体   English   中英

将张量转换为 numpy 没有急切模式

[英]Convert to numpy a tensor without eager mode

我将自定义层定义为我的网络的最后一个。 在这里,我需要将输入的张量转换为 numpy 数组,以在其上定义 function。 特别是,我想像这样定义我的最后一层:

import tensorflow as tf
def hat(x):
  A = tf.constant([[0.,-x[2],x[1]],[x[2],0.,-x[0]],[-x[1],x[0],0.]])
  return A

class FinalLayer(layers.Layer):
  def __init__(self, units):
    super(FinalLayer, self).__init__()
    self.units = units
  

  def call(self, inputs):
    p = tf.constant([1.,2.,3.])
    q = inputs.numpy()
    p = tf.matmul(hat(q),p)
    return p

权重对我的问题无关紧要,因为我知道如何管理它们。 问题是该层在 Eager 模式下完美运行,但是使用此选项训练阶段会变慢。 我的问题是:在没有急切模式的情况下,我可以做些什么来实现这一层? 那么,或者,我可以访问张量的单个分量 x[i] 而不将其转换为 numpy 数组吗?

您可以稍微不同地重写您的hat function,因此它接受张量而不是numpy数组。 例如:

def hat(x):
  zero = tf.zeros(())
  A = tf.concat([zero,-x[2],x[1],x[2],zero,-x[0],-x[1],x[0],zero], axis=0)
  return tf.reshape(A,(3,3))

将导致

>>> p = tf.constant([1.,2.,3.])
>>> hat(p)
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[ 0., -3.,  2.],
       [ 3.,  0., -1.],
       [-2.,  1.,  0.]], dtype=float32)>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM