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

Python 将张量作为参数传递给函数,python,tensorflow,keras,tensorflow2.0,tf.data.dataset,Python,Tensorflow,Keras,Tensorflow2.0,Tf.data.dataset,我正在尝试规范化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.uint

我正在尝试规范化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':,'image':,'label':}
但是,在“我的函数”中打印此项会输出:

 '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>}
'id':,'image':,'label':}
因此,我无法对图像数组执行任何转换,因为我使用的不是张量数组,而是
'args_2:0'


如何将每个元素正确地传递给我的规范化功能?

我在标准数据集上尝试了你的代码,但它不起作用。图像['label']不正确,因为您应该给出一个整数。以下是我对您的代码的修改:

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

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


z = ds_train.map(normalization)