对于以下代码:
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
为什么会这样?我该怎么解决?
从documentation:
原始数组是浮点类型(返回值
sigmoid()
);将其中的值设置为0和1不会更改类型。您需要使用astype(np.int)
:应该这样做(未经测试)。
这样做,您拥有的
float()
类型转换也更有意义。尽管我只是去掉了演员阵容,依靠Python做正确的事情。如果您仍在使用Python2(但请使用Python3),只需添加
让Python做正确的事情(在Python 3中这样做不会造成伤害;它只是什么都不做)。有了它(或者无论如何在Python 3中),您可以删除代码中其他地方的许多
float()
类型转换,从而提高可读性。invert需要int或bools,请改用np.linalg.inv方法。
相关问题 更多 >
编程相关推荐