在没有急切模式的情况下转换为 numpy 张量

问题描述

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

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 函数,因此它接受张量而不是 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)>