Python 转换为numpy张量而不使用渴望模式
我将自定义层定义为网络的最后一个层。这里我需要将一个张量(输入张量)转换成一个numpy数组来定义一个函数。特别是,我想定义我的最后一层,类似如下:Python 转换为numpy张量而不使用渴望模式,python,numpy,tensorflow,neural-network,eager-execution,Python,Numpy,Tensorflow,Neural Network,Eager Execution,我将自定义层定义为网络的最后一个层。这里我需要将一个张量(输入张量)转换成一个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
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))
将导致
>>> 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)>
p=tf.常数([1,2,3.])
>>>帽子(p)
太好了,非常感谢。不幸的是,我学习tensorflow只是为了我的研究需要,因此我缺乏一些基础知识。我认为我的问题是一个基本的问题。你有没有任何文字可以建议你更恰当地学习它?你可以阅读。但是请记住,您必须使用该框架来更多地了解它是如何工作的,以及它的缺点是什么。在这种情况下,您无法从tensorslices轻松创建
tf.常量,这就是为什么使用类似op的concat
比创建新的Tensor
对象更容易的原因。