将张量作为参数传递给函数

Passing tensors as an argument to a function

我正在尝试规范化 tf.data.Dataset,如下所示:

def normalization(image):
    print(image['label'])
    
    return 1
    

z = val.map(normalization) 

val数据集是这样的:

<TakeDataset shapes: { id: (), image: (32, 32, 3), label: ()}, types: {id: tf.string, image: tf.uint8, label: tf.int64}>

如果我打印一个元素,我可以看到:

  { 'id': <tf.Tensor: shape=(), dtype=string, numpy=b'train_31598'>, 'image': <tf.Tensor: shape=(32, 32, 3), dtype=uint8, 
 numpy=    array([[[151, 130, 106],
            .....,
            [104,  95,  77]]], dtype=uint8)>, 'label': <tf.Tensor: shape=(), dtype=int64, numpy=50>}

但是在我的函数输出中打印这个:

 'id': <tf.Tensor 'args_1:0' shape=() dtype=string>, 'image': <tf.Tensor 'args_2:0' shape=(32, 32, 3) dtype=uint8>, 'label': <tf.Tensor 'args_3:0' shape=() dtype=int64>}

所以我无法对我的图像数组执行任何转换,因为我有 'args_2:0'

而不是张量数组

如何将每个元素正确传递到我的规范化函数?

我在标准数据集上试过你的代码,但没有用。 image['label'] 不正确,因为您应该给出一个整数。这是我对您的代码的修改:

def normalization(image,label):
print(image[0])

return tf.cast(image, tf.float32) / 255., label


z = ds_train.map(normalization)