【问题标题】:numpy TypeError: ufunc 'invert' not supported for the input types, and the inputsnumpy TypeError: 输入类型和输入不支持 ufunc 'invert'
【发布时间】:2018-03-09 21:11:40
【问题描述】:

下面的代码:

def makePrediction(mytheta, myx):
    # -----------------------------------------------------------------
    pr = sigmoid(np.dot(myx, mytheta))

    pr[pr < 0.5] =0
    pr[pr >= 0.5] = 1

    return pr

    # -----------------------------------------------------------------

# Compute the percentage of samples I got correct:
pos_correct = float(np.sum(makePrediction(theta,pos)))
neg_correct = float(np.sum(np.invert(makePrediction(theta,neg))))
tot = len(pos)+len(neg)
prcnt_correct = float(pos_correct+neg_correct)/tot
print("Fraction of training samples correctly predicted: %f." % prcnt_correct)

我收到此错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-f0c91286cd02> in <module>()
     13 # Compute the percentage of samples I got correct:
     14 pos_correct = float(np.sum(makePrediction(theta,pos)))
---> 15 neg_correct = float(np.sum(np.invert(makePrediction(theta,neg))))
     16 tot = len(pos)+len(neg)
     17 prcnt_correct = float(pos_correct+neg_correct)/tot

TypeError: ufunc 'invert' not supported for the input types, and the inputs

为什么会发生,我该如何解决?

【问题讨论】:

    标签: python numpy matrix machine-learning logistic-regression


    【解决方案1】:

    来自documentation

    参数:
    x : array_like.
    只处理整数和布尔类型。”

    你原来的数组是浮点型的(sigmoid()的返回值);将其中的值设置为 0 和 1 不会更改类型。你需要使用astype(np.int):

    neg_correct = float(np.sum(np.invert(makePrediction(theta,neg).astype(np.int))))
    

    应该这样做(未经测试)。


    这样做,您拥有的float() 演员表也更有意义。虽然我只会删除演员表,并依靠 Python 做正确的事情。
    如果您仍在使用 Python 2(但请使用 Python 3),只需添加
    from __future__ import division
    

    让 Python 做正确的事(如果你在 Python 3 中做这件事不会有什么坏处;它只是什么都不做)。有了它(或者在 Python 3 中),您可以删除代码中其他地方的许多其他 float() 强制转换,从而提高可读性。

    【讨论】:

      【解决方案2】:

      np.invert 需要整数或布尔值,请改用 np.linalg.inv 方法。

      【讨论】:

        猜你喜欢
        • 2020-07-21
        • 2020-09-29
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        • 2017-09-17
        • 2020-02-16
        • 2021-12-01
        相关资源
        最近更新 更多