对于下面的代码:
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)/totprint("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)/totTypeError: ufunc 'invert' not supported for the input types, and the inputs
为什么会发生这种情况,我该如何修复它?
回答:
根据文档说明:
参数:
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()
转换,提高可读性。