【问题标题】:'bitwise_and' not supported for the input types Numpy array输入类型 Numpy 数组不支持“bitwise_and”
【发布时间】:2018-07-25 03:12:08
【问题描述】:

我正在尝试使用下面的代码使用 numpy 数组计算 F1_Score

ypred = np.squeeze(imgs_mask_predict[jj,:,:,:])
ytrue = np.squeeze(imgs_test_mask[jj,:,:,:])

def f1_score_single(y_true, y_pred):
    y_true = y_true.flatten('F')
    y_pred = y_pred.flatten('F')
    cross_size = len(y_true & y_pred)
    if cross_size == 0: return 0.
    p = 1. * cross_size / len(y_pred)
    r = 1. * cross_size / len(y_true)
    return (2. * (p * r) / (p + r))

我收到一个错误

“输入类型不支持 ufunc 'bitwise_and',并且根据强制转换规则 ''safe'' 无法安全地将输入强制转换为任何支持的类型”在这行代码中

    cross_size = len(y_true & y_pred)

我试图搜索这个错误,但没有得到这个错误的原因和解决方案。我应该如何解决这个问题?

【问题讨论】:

  • y_true.dtypey_pred.dtype 是什么?
  • y_true type y_pred type y_true shape (256, 160) y_pred shape (256, 160)
  • 看起来像 type(y_true)y_true.shape。现在向我们展示y_true.dtypey_pred.dtypedtype属性告诉你numpy数组中数据的数据类型。
  • dtype 是 float32
  • 啊。为什么要尝试将 & 运算符(对于 numpy 数组是按位与)与浮点值一起使用?该运算符仅对整数值有意义(对于“意义”的某些定义)。

标签: python-3.x numpy deep-learning bitwise-and


【解决方案1】:

对于浮点数,您应该使用isclose

cross_size = np.isclose(y_true, y_pred).sum()

您还可以通过atolrtol 关键字参数you can see the documentation here 设置相似度阈值。

【讨论】:

    【解决方案2】:

    您可以尝试使用 intersect1d 而不是 &,例如,使用 np.intersect1d 将与您打算使用 & 做的一样

    import numpy as np
    y_true=np.array([1.0,2.0,4.0,1.0,2.0,4.0,1.0,2.0,4.0,1.0])
    y_score=np.array([1.0,1.0,2.0,4.0,1.0,2.0,4.0,1.0,2.0,4.0])
    x=np.intersect1d(y_true, y_score)
    print(x)
    

    结果将是 [1. 2. 4.]

    你可以在这里测试程序https://www.programiz.com/python-programming/online-compiler/

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2021-11-08
      • 2020-06-24
      • 1970-01-01
      • 2017-04-10
      • 2018-03-09
      • 2022-12-17
      相关资源
      最近更新 更多