将没有渴求模式的张量转换为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

权重与我的问题无关,因为我知道如何管理它们。问题是,这一层在渴望模式下工作得很好,但是使用这个选项,训练阶段会变慢。我的问题是:有没有什么我能做的来实现这一层,而不是急于模式?那么,或者,我可以访问张量的单个分量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))

Will result in

>>> 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)>

最新更新