我想实现我自己的伯努利类与自己契合的功能,以适应我的训练和测试列表包含单词(垃圾邮件检测)
这里是我的伯努利类:
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
代码重新创建运行。你需要一些诊断打印运行(注重形状和D型)。一般观察,运行numpy
代码时,永远不要假设你得到的东西形状和D型右侧。校验!