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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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