我仍在学习 tensorflow 和 keras,我怀疑这个问题有一个非常简单的答案,我只是因为不熟悉而错过了。
我有一个 PrefetchDataset
对象:
> print(tf_test)
$ <PrefetchDataset shapes: ((None, 99), (None,)), types: (tf.float32, tf.int64)>
…由功能和目标组成。我可以使用 for
循环对其进行迭代:
> for example in tf_test:
> print(example[0].numpy())
> print(example[1].numpy())
> exit()
$ [[-0.31 -0.94 -1.12 ... 0.18 -0.27]
[-0.22 -0.54 -0.14 ... 0.33 -0.55]
[-0.60 -0.02 -1.41 ... 0.21 -0.63]
...
[-0.03 -0.91 -0.12 ... 0.77 -0.23]
[-0.76 -1.48 -0.15 ... 0.38 -0.35]
[-0.55 -0.08 -0.69 ... 0.44 -0.36]]
[0 0 1 0 1 0 0 0 1 0 1 1 0 1 0 0 0
...
0 1 1 0]
然而,这是非常缓慢的。我想做的是访问对应于类标签的张量,并将其转换为一个 numpy 数组、一个列表或任何可以输入到 scikit-learn 的分类报告和/或混淆矩阵中的可迭代对象:
> y_pred = model.predict(tf_test)
> print(y_pred)
$ [[0.01]
[0.14]
[0.00]
...
[0.32]
[0.03]
[0.00]]
> y_pred_list = [int(x[0]) for x in y_pred] # assumes value >= 0.5 is positive prediction
> y_true = [] # what I need help with
> print(sklearn.metrics.confusion_matrix(y_true, y_pred_list)
…或访问数据,使其可用于张量流的混淆矩阵:
> labels = [] # what I need help with
> predictions = y_pred_list # could we just use a tensor?
> print(tf.math.confusion_matrix(labels, predictions)
在这两种情况下,以计算成本不高的方式从原始对象获取目标数据的一般能力将非常有帮助(并且可能有助于我的基本直觉:tensorflow 和 keras)。
任何建议将不胜感激。
原文由 jda 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用 --- 将其转换为列表,然后使用
list(ds)
tf.data.Dataset.from_tensor_slices(list(ds))
其重新编译为普通数据集。从那里你的噩梦又开始了,但至少这是其他人以前经历过的噩梦。请注意,对于更复杂的数据集(例如嵌套字典),您将需要在调用
list(ds)
后进行更多预处理,但这应该适用于您询问的示例。这远不是一个令人满意的答案,但不幸的是,该类完全没有记录,而且标准数据集技巧都不起作用。