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

对于下面的代码:

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()转换,提高可读性。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注