簡體   English   中英

嘗試在Keras中創建自定義損失函數時出現“僅當啟用急切執行時,張量對象才可迭代”錯誤

[英]“Tensor objects are only iterable when eager execution is enabled” error when trying to create custom loss function in Keras

我正在嘗試使用神經網絡來做SVD。 我的輸入是一個矩陣(僅說4x4矩陣),輸出是一個表示分解形式的向量(假設輸入是4x4,這將是一個36元素向量,其中U元素為16個元素,S元素為4個元素,S元素為16個元素對於VT)。

我試圖定義一個自定義損失函數,而不是在分解后的表單上使用MSE之類的東西。 因此,我不想比較36個長度向量的損失,而是要計算重建矩陣之間的損失。 因此,如果A = U * S * VT (實際)並且A' = U' * S' * V.T' (預測),我想計算A和A'之間的損耗。

我對tensorflow和keras相當陌生,因此我可能在做一些幼稚的事情,但是到目前為止,這是我所擁有的。 雖然邏輯對我來說還可以,但我收到TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn. TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn. 我不確定為什么會這樣,如何解決? 另外,我是否需要像我目前正在做的那樣平整來自reconstruct_matrix的輸出,還是應該保持原樣?

# This function takes the decomposed matrix (vector of U, S, V.T)
# and reconstructs the original matrix

def reconstruct_matrix(decomposed_vector):
  example = decomposed_vector
  s = np.zeros((4,4))
  for en, i in enumerate(example[16:20]):
    s[en, en] = i
  u = example[:16].reshape(4,4)
  vt = example[20:].reshape(4,4)
  orig = np.matmul(u, s)
  orig = np.matmul(orig, vt)
  return orig.flatten() # Given that matrices are 4x4, this will be a length 16 vector

# Custom loss that essentially computes MSE on reconstructed matrices 

def custom_loss(y_true, y_pred):
    Y = reconstruct_matrix(y_true)
    Y_prime = reconstruct_matrix(y_pred)
    return K.mean(K.square(Y - Y_prime)) 

model.compile(optimizer='adam',
              loss=custom_loss)

注意:我的keras版本是2.2.4,我的tensorflow版本是1.14.0。

tf1.x ,默認情況下,急切執行被禁用(從版本2開始啟用)。

您必須通過調用腳本頂部來啟用它:

import tensorflow as tf

tf.enable_eager_execution()

這種模式允許您將類似Python的抽象用於流控制(例如for您在代碼中一直使用的if語句和for循環)。 如果禁用它,則需要使用Tensorflow函數( tf.condtf.while_loop分別用於iffor )。

有關更多信息,請參閱docs

順便說一句。 我不確定是否要展平,但是請記住您的y_truey_pred需要相同的形狀,並且樣本必須彼此對應,如果可以的話,您應該可以。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM