【问题标题】:TypeError: cannot perform reduce with flexible type while applying a selfmade Bernoulli fitting on a listTypeError:在列表上应用自制伯努利拟合时无法使用灵活类型执行减少
【发布时间】:2019-07-04 12:15:44
【问题描述】:

我正在尝试使用自己的 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?甚至不知道如何解决它。

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

【问题讨论】:

    标签: python numpy machine-learning data-fitting bernoulli-probability


    【解决方案1】:

    我通过将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 代码时,永远不要假设你得到了正确的形状和数据类型。验证!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2014-05-07
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 2017-09-12
      相关资源
      最近更新 更多