Tensorflow TypeError: Cannot convert 1e-12 to EagerTensor of dtype int32
Tensorflow TypeError: Cannot convert 1e-12 to EagerTensor of dtype int32
我有一个多类分类机器学习应用程序,我想使用 tensorflow 为其计算 f1 分数。预测值和实际值分别存储在 pandas 数据帧 y_pred
和 y_act
中。两者都填充有 1 和 0。所以我做了这样的事情:
# convert dataframes to numpy
pred_numpy = numpy.asarray([y_pred], numpy.int32)
act_numpy = numpy.asarray([y_act], numpy.int32)
# compute multiclass f1
metric = tfa.metrics.F1Score(num_classes=num_classes, average="macro")
metric.update_state(act_numpy, pred_numpy)
print(metric.result().numpy())
但是我得到以下错误
TypeError: Cannot convert 1e-12 to EagerTensor of dtype int32
一定是某些东西从 pandas 到 tensorflow 的类型转换引发了错误。我尝试了一系列缓解措施都无济于事。
我尝试将 numpy 数组转换为张量,如下所示:
pred_tf = tf.convert_to_tensor(pred_numpy, numpy.int32)
我尝试确保 pandas 数据框没有 1e-12 个实例:
y_pred = y_pred.replace(1e-12, 0)
我尝试在没有 numpy.int32
选项的情况下转换为 numpy。
但是我仍然遇到同样的错误。在不出现此错误的情况下成功从 pandas 转换为张量的任何提示?
这是 tfa api 文档中提供的代码示例:
metric = tfa.metrics.F1Score(num_classes=3, threshold=0.5)
y_true = np.array([[1, 1, 1],
[1, 0, 0],
[1, 1, 0]], np.int32)
y_pred = np.array([[0.2, 0.6, 0.7],
[0.2, 0.6, 0.6],
[0.6, 0.8, 0.0]], np.float32)
metric.update_state(y_true, y_pred)
result = metric.result()
result.numpy()
请注意,y_pred
数组是模型的原始输出并且是 float
,可能来自 softmax 激活。如果您查看该函数的 code ,它是受支持的,因为它沿最终维度执行 argmax,或阈值概率。因此,如果您将这些转换为 int
,概率将全部被截断为 0
,尽管我怀疑您无论如何都传递了已经 argmaxed 的值。
我怀疑这个特定错误来自 API:
中的这一行
y_pred = tf.logical_and(y_pred >= threshold, tf.abs(y_pred) > 1e-12)
因为它无法将您提供的 int32 与 1e-12 进行比较,并尝试转换第二个值。
我有一个多类分类机器学习应用程序,我想使用 tensorflow 为其计算 f1 分数。预测值和实际值分别存储在 pandas 数据帧 y_pred
和 y_act
中。两者都填充有 1 和 0。所以我做了这样的事情:
# convert dataframes to numpy
pred_numpy = numpy.asarray([y_pred], numpy.int32)
act_numpy = numpy.asarray([y_act], numpy.int32)
# compute multiclass f1
metric = tfa.metrics.F1Score(num_classes=num_classes, average="macro")
metric.update_state(act_numpy, pred_numpy)
print(metric.result().numpy())
但是我得到以下错误
TypeError: Cannot convert 1e-12 to EagerTensor of dtype int32
一定是某些东西从 pandas 到 tensorflow 的类型转换引发了错误。我尝试了一系列缓解措施都无济于事。
我尝试将 numpy 数组转换为张量,如下所示:
pred_tf = tf.convert_to_tensor(pred_numpy, numpy.int32)
我尝试确保 pandas 数据框没有 1e-12 个实例:
y_pred = y_pred.replace(1e-12, 0)
我尝试在没有 numpy.int32
选项的情况下转换为 numpy。
但是我仍然遇到同样的错误。在不出现此错误的情况下成功从 pandas 转换为张量的任何提示?
这是 tfa api 文档中提供的代码示例:
metric = tfa.metrics.F1Score(num_classes=3, threshold=0.5)
y_true = np.array([[1, 1, 1],
[1, 0, 0],
[1, 1, 0]], np.int32)
y_pred = np.array([[0.2, 0.6, 0.7],
[0.2, 0.6, 0.6],
[0.6, 0.8, 0.0]], np.float32)
metric.update_state(y_true, y_pred)
result = metric.result()
result.numpy()
请注意,y_pred
数组是模型的原始输出并且是 float
,可能来自 softmax 激活。如果您查看该函数的 code ,它是受支持的,因为它沿最终维度执行 argmax,或阈值概率。因此,如果您将这些转换为 int
,概率将全部被截断为 0
,尽管我怀疑您无论如何都传递了已经 argmaxed 的值。
我怀疑这个特定错误来自 API:
中的这一行y_pred = tf.logical_and(y_pred >= threshold, tf.abs(y_pred) > 1e-12)
因为它无法将您提供的 int32 与 1e-12 进行比较,并尝试转换第二个值。