首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >numpy TypeError:输入类型和输入不支持ufunc 'invert‘

numpy TypeError:输入类型和输入不支持ufunc 'invert‘
EN

Stack Overflow用户
提问于 2017-09-28 15:54:32
回答 2查看 24.7K关注 0票数 4

对于下面的代码:

代码语言:javascript
复制
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)

我得到了这个错误:

代码语言:javascript
复制
---------------------------------------------------------------------------
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

为什么会发生这种情况?我如何修复它?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-28 15:59:52

documentation中:

参数:

X: array_like。

仅处理整型和布尔类型。“

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

代码语言:javascript
复制
neg_correct = float(np.sum(np.invert(makePrediction(theta,neg).astype(np.int))))

应该这样做(未测试)。

这样做,您拥有的float()类型转换也更有意义。虽然我只是删除了强制转换,并依赖于Python做正确的事情。

如果您仍在使用Python 2(但请使用Python 3),只需添加

代码语言:javascript
复制
from __future__ import division

让Python做正确的事情(如果你在Python3中做,也不会有什么坏处;它什么也不做)。有了它(或者至少在Python3中),您可以删除代码中其他地方的许多其他float()类型转换,从而提高可读性。

票数 3
EN

Stack Overflow用户

发布于 2019-11-02 02:10:25

np.invert需要int或bools,请改用np.linalg.inv方法。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46463822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档