【问题标题】:numpy method for tensors in TensorFlow 2.x and eager executionTensorFlow 2.x 中张量的 numpy 方法和急切执行
【发布时间】:2021-02-25 03:08:04
【问题描述】:

在 colab 上使用 TensorFlow 2.4.1

在下面运行此代码:

import tensorflow as tf
from tensorflow.keras.datasets import cifar100
import numpy as np

(train_data, train_labels), (test_data, test_labels) = cifar100.load_data(label_mode='fine')
train_dataset = tf.data.Dataset.from_tensor_slices((train_data, train_labels))
for (train, label) in train_dataset.take(1):
    print(label)
    print(label.numpy()[0])

# tf.Tensor([19], shape=(1,), dtype=int64)
# 19

这一切都很好,但是在下面的代码中尝试使用 keras.Dataset 对象的过滤方法时,numpy 方法不起作用:

def filter_classes(dataset, classes):
    def match_class(data, label):
        print(label)      
        print(label.numpy()[0])            
        return label.numpy()[0] in classes
    return dataset.filter(match_class)

cifar_classes = [0, 29, 99] 
train_dataset = filter_classes(train_dataset, cifar_classes)

# Tensor("args_1:0", shape=(1,), dtype=int64)
# AttributeError: 'Tensor' object has no attribute 'numpy'

通过阅读一些相关问题,错误似乎是由于后一个张量没有被急切执行。

  1. 张量“arg_1:0”中的属性而不是一个 numpy 数组是否表示该张量尚未被评估?
  2. 使用过滤器方法时,数据集对象中的张量不会被热切评估是设计使然吗?

谢谢。

【问题讨论】:

    标签: numpy tensorflow keras


    【解决方案1】:

    tf.data.Dataset 函数出于性能原因不在 EagerMode 下运行。您不能在 tf.data.Dataset 使用的函数中使用 .numpy 方法。

    在您的情况下,您可以结合使用 tf.math.equaltf.math.reduce_any 来过滤数据集并仅保留所需的类:

    ds_filtered = train_dataset.filter(lambda x:tf.math.reduce_any(tf.equal(x,cifar_classes)))
    

    【讨论】:

      猜你喜欢
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多