python - TypeError:在列表上应用自制伯努利拟合时无法使用灵活类型执行减少
问题描述
我正在尝试使用自己的 fit 函数实现我自己的 Bernoulli 类,以适应包含单词的训练和测试列表(垃圾邮件检测)
这是我的伯努利课程:
class BernoulliNB(object):
def __init__(self, alpha=1.0):
self.alpha = alpha
def fit(self, X, y):
count_sample = len(X)
separated = [[x for x, t in zip(X, y) if t == c] for c in np.unique(y)]
self.class_log_prior_ = [np.log(len(i) / count_sample) for i in separated]
count = np.array([np.array(i).sum(axis=0) for i in separated]) + self.alpha
smoothing = 2 * self.alpha
n_doc = np.array([len(i) + smoothing for i in separated])
self.feature_prob_ = count / n_doc[np.newaxis].T
return self
def predict_log_proba(self, X):
return [(np.log(self.feature_prob_) * x + \
np.log(1 - self.feature_prob_) * np.abs(x - 1)
).sum(axis=1) + self.class_log_prior_ for x in X]
def predict(self, X):
return np.argmax(self.predict_log_proba(X), axis=1)
这是我的实现:
nb = BernoulliNB(alpha=1).fit(train_list, test_list)
预期结果:
能够适应我的班级我的火车和测试列表但是我收到以下错误:
TypeError: cannot perform reduce with flexible type
在以下行:
count = np.array([np.array(i).sum(axis=0) for i in separated]) + self.alpha
我不知道为什么它会失败,也许是因为我有列表而不是 np?甚至不知道如何解决它。
有人可以帮助我或向我解释如何实现拟合吗?
解决方案
sum
我通过应用于结构化数组收到此错误消息:
In [754]: np.array([(1,.2),(3,.3)], dtype='i,f')
Out[754]: array([(1, 0.2), (3, 0.3)], dtype=[('f0', '<i4'), ('f1', '<f4')])
In [755]: _.sum(axis=0)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-755-69a91062a784> in <module>()
----> 1 _.sum(axis=0)
/usr/local/lib/python3.6/dist-packages/numpy/core/_methods.py in _sum(a, axis, dtype, out, keepdims, initial)
34 def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
35 initial=_NoValue):
---> 36 return umr_sum(a, axis, dtype, out, keepdims, initial)
37
38 def _prod(a, axis=None, dtype=None, out=None, keepdims=False,
TypeError: cannot perform reduce with flexible type
我猜你的错误发生在
np.array(i).sum(axis=0)
并且i
产生或者是结构化数组。
我无法仅通过阅读您的fit
代码来重新创建您的运行。您需要使用一些诊断打印来运行它(专注于形状和 dtype)。一般的观察,在运行numpy
代码时,永远不要假设你得到了正确的 shape 和 dtype 之类的东西。核实!
推荐阅读
- git - 更改 git 的代理配置以实现一推或一拉
- r - 更改闪亮仪表板选项卡中选定选项卡的颜色
- java - 我在查询presto数据时mybatis有一些问题
- python - 使用 Django 的用户帐户激活电子邮件
- python-3.x - Pandas JOIN/MERGE/CONCAT 特定索引上的数据帧
- php - 如何将 PHP 版本更改为 php5.6 并在 php5.6 中安装所有模块
- asp.net - 如何在 asp.net web api 中获取模型包含文本 json 属性的 json 数据?
- excel - 动态调整绘图区域大小以查看聚集条形图的类别轴中的截断文本
- r - setwd() 在函数内部工作很奇怪?
- jms - Weblogic 12c JMS 队列到 SAP PI 服务器