tf.keras.backend.function,用于转换tf.data.dataset内部的嵌入

时间:2020-08-25 12:26:37

标签: tensorflow tensorflow2.0 tf.keras autoencoder tf.data.dataset

我正在尝试使用神经网络的输出来转换tf.data.dataset中的数据。具体来说,我正在使用Delta-Encoder来操纵tf.data管道内的嵌入。但是,这样做时出现以下错误:

OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.

我已经搜索了dataset pipeline页,并且堆栈溢出,但是找不到能够解决我的问题的内容。在下面的代码中,我使用的是自动编码器,因为它使用更简洁的代码会产生相同的错误。

冒犯的部分似乎是 [[x,]] = tf.py_function(Auto_Func, [x], [tf.float32])tf_auto_transform

num_embeddings = 100
input_dims = 1000
embeddings = np.random.normal(size = (num_embeddings, input_dims)).astype(np.float32)
target = np.zeros(num_embeddings)

#creating Autoencoder
inp = Input(shape = (input_dims,), name ='input')
hidden = Dense(10, activation = 'relu', name = 'hidden')(inp)
out = Dense(input_dims, activation = 'relu', name='output')(hidden)
auto_encoder = tf.keras.models.Model(inputs =inp, outputs=out)

Auto_Func = tf.keras.backend.function(inputs = Autoencoder.get_layer(name='input').input, 
                                      outputs = Autoencoder.get_layer(name='output').input )

#Autoencoder transform for dataset.map
def tf_auto_transform(x, target):
    x_shape = x.shape
    #@tf.function
    #def func(x):
    #    return tf.py_function(Auto_Func, [x], [tf.float32])
    #[[x,]] = func(x)
    [[x,]] = tf.py_function(Auto_Func, [x], [tf.float32]) 
    x.set_shape(x_shape) 
    return x, target

def get_dataset(X,y, batch_size = 32):
    train_ds = tf.data.Dataset.from_tensor_slices((X, y))
    train_ds = train_ds.map(tf_auto_transform)
    train_ds = train_ds.batch(batch_size)
    return train_ds

dataset = get_dataset(embeddings, target, 2)

上面的代码产生以下错误:

OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.

我试图通过运行tf_auto_transform函数的注释掉的部分来消除该错误,但是该错误仍然存​​在。

侧面注意:Delta编码器纸确实有code,但它是用tf 1.x编写的。我正在尝试将tf 2.x与tf功能性API结合使用。谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

冒着使自己成为n00b的危险,答案是切换映射和批处理功能的顺序。我正在尝试应用神经网络对数据进行一些更改。 tf.keras模型采用批次作为输入,而不是单个样本。通过首先批量处理数据,我可以在我的nn中运行批次

def get_dataset(X,y, batch_size = 32):
    train_ds = tf.data.Dataset.from_tensor_slices((X, y))
    
    #The changed order
    train_ds = train_ds.batch(batch_size)
    train_ds = train_ds.map(tf_auto_transform)**strong text**
    return train_ds

就是这么简单。