簡體   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