簡體   English   中英

RaggedTensor 變成 Tensor in loss function

[英]RaggedTensor becomes Tensor in loss function

我有一個序列到序列 model,我試圖在其中預測轉換后的 output 序列。 為此,我需要計算參差不齊的張量中元素之間的 MSE:

def cpu_bce(y_value, y_pred):
    with tf.device('/CPU:0'):
        y_v = y_value.to_tensor()
        y_p = y_pred.to_tensor()
        
        return tf.keras.losses.MeanSquaredError()(y_v, y_p)

然而,執行時遇到錯誤:

    AttributeError: 'Tensor' object has no attribute 'to_tensor'

是什么導致了這個問題? GRU 似乎在直接調用時返回一個RaggedTensor 然而在運行時,損失函數的 arguments 是正常的Tensor

import tensorflow as tf
import numpy as np
import functools

def generate_example(n):
    
    for i in range(n):
        dims = np.random.randint(7, 11)
        x = np.random.random((dims, ))
        y = 2 * x.cumsum()

        yield tf.constant(x), tf.constant(y)

N = 200

ds = tf.data.Dataset.from_generator(
    functools.partial(generate_example, N),
    output_signature=(
        tf.TensorSpec(shape=(None,), dtype=tf.float32),
        tf.TensorSpec(shape=(None,), dtype=tf.float32),
    ),
)

def rag(x, y):
    x1 = tf.expand_dims(x, 0)
    y1 = tf.expand_dims(y, 0)
    
    x1 = tf.expand_dims(x1, -1)
    y1 = tf.expand_dims(y1, -1)
    
    return (
        tf.RaggedTensor.from_tensor(x1),
        tf.RaggedTensor.from_tensor(y1),
    )

def unexp(x, y):
    return (
        tf.squeeze(x, axis=1),
        tf.squeeze(y, axis=1)
    )

ds = ds.map(rag).batch(32).map(unexp)

model = tf.keras.Sequential([
    tf.keras.Input(
        type_spec=tf.RaggedTensorSpec(shape=[None, None, 1],
                                      dtype=tf.float32)),
    tf.keras.layers.GRU(1, return_sequences=True),
])

def cpu_bce(y_value, y_pred):
    with tf.device('/CPU:0'):
        y_v = y_value.to_tensor()
        y_p = y_pred.to_tensor()
        
        return tf.keras.losses.MeanSquaredError()(y_v, y_p)

model.compile(loss=cpu_bce, optimizer="adam", metrics=[cpu_bce])

model.fit(ds, epochs=3)

在你的loss function中,你可以通過以下方式重寫,使其生效。

def cpu_bce(y_value, y_pred):
    with tf.device('/CPU:0'):
        if isinstance(y_value, tf.RaggedTensor):
            y_value = y_value.to_tensor()
            
        if isinstance(y_pred, tf.RaggedTensor):   
            y_pred = y_pred.to_tensor()
            
        return tf.keras.losses.MeanSquaredError()(y_value, y_pred)

model.compile(loss=cpu_bce, optimizer="adam", metrics=[cpu_bce])
model.fit(ds, epochs=3) # loss & metrics will vary

或者,您不需要轉換參差不齊的張量,保持原樣。

def cpu_bce(y_value, y_pred):
    with tf.device('/CPU:0'):
        return tf.keras.losses.MeanSquaredError()(y_value, y_pred)

model.compile(loss=cpu_bce, optimizer="adam", metrics=[cpu_bce])
model.fit(ds, epochs=3) # loss & metrics will alike

你得到AttributeError的原因是因為在metrics=[cpu_bce]中,目標和預測張量在內部轉換為 tesnor。 您可以通過打印損失 function 中的目標和預測來進行檢查。您會發現損失 function 是參差不齊的,但對於度量 function 是張量。 可能覺得不方便,那就GitHub提票吧。

暫無
暫無

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

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