首页 > 解决方案 > 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?甚至不知道如何解决它。

有人可以帮助我或向我解释如何实现拟合吗?

标签: pythonnumpymachine-learningdata-fittingbernoulli-probability

解决方案


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 之类的东西。核实!


推荐阅读