[英]numpy TypeError: ufunc 'invert' not supported for the input types, and the inputs
For the code below:对于下面的代码:
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)
I get this error:我收到此错误:
---------------------------------------------------------------------------
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
Why is it happening and how can I fix it?为什么会发生这种情况,我该如何解决?
From the documentation :从文档:
Parameters:
参数:
x : array_like.x :array_like。
Only integer and boolean types are handled."只处理整数和布尔类型。”
Your original array is floating point type (the return value of sigmoid()
);您的原始数组是浮点类型(
sigmoid()
的返回值); setting values in it to 0 and 1 won't change the type.将其中的值设置为 0 和 1 不会改变类型。 You need to use
astype(np.int)
:您需要使用
astype(np.int)
:
neg_correct = float(np.sum(np.invert(makePrediction(theta,neg).astype(np.int))))
should do it (untested).应该这样做(未经测试)。
float()
cast you have also makes more sense.
float()
也更有意义。
Though I would just remove the cast, and rely on Python doing the right thing.
from __future__ import division
to let Python do the right thing (it won't hurt if you do it in Python 3; it just doesn't do anything).让 Python 做正确的事情(如果你在 Python 3 中做它不会有什么坏处;它只是什么都不做)。 With that (or in Python 3 anyway), you can remove numerous other
float()
casts you have elsewhere in your code, improving readability.有了它(或无论如何在 Python 3 中),您可以删除代码中其他地方的许多其他
float()
强制转换,从而提高可读性。
np.invert 需要整数或布尔值,请改用np.linalg.inv方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.