python - 类(class)要求我为朴素贝叶斯模型 python 提供 self

标签 python class machine-learning prediction naivebayes

我尝试使用以下代码,但是当我尝试将 fit 函数与我的 X_train 和 y_train 一起使用时 我收到以下错误

fit() 缺少 1 个必需的位置参数:'self'

我对类不太了解,但我知道它不应该问我自己。我发现了一些关于实例化的东西,但无法弄清楚。

class BernoulliNB(object):
    def __init__(self, alpha=1.0):
        self.alpha = alpha

    def fit(self, X, y):
        count_sample = X.shape[0]
        # group by class
        separated = [[x for x, t in zip(X, y) if t == c] for c in np.unique(y)]
        # class prior
        self.class_log_prior_ = [np.log(len(i) / count_sample) for i in separated]
        # count of each word
        count = np.array([np.array(i).sum(axis=0) for i in separated]) + self.alpha

        smoothing = 2 * self.alpha
        # number of documents in each class + smoothing
        n_doc = np.array([len(i) + smoothing for i in separated])
        print(n_doc)

    def predict(self, X):
        return np.argmax(self.predict_log_proba(X), axis=1)

当我尝试

b = BernoulliNB() 
b.fit(b, X_train,y_train) 

这次我收到

fit() takes 3 positional arguments but 4 were given

然后我把它改为

BernoulliNB().fit(X_train,y_train)

但是这次出现这个错误

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

最佳答案

您正在调用 BernoulliNB.fit(...) 而不是

b = BernoulliNB()
b.fit(...)
<小时/>

在上面的代码示例中,bBernoulliNB实例,因此将其自身作为 self 传递.

您还可以使用

b = BernoulliNB()
BernoulliNB.fit(b,...)

或者(按照盖伊的建议)

BernoulliNB().fit(...)

关于python - 类(class)要求我为朴素贝叶斯模型 python 提供 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60189467/

相关文章:

python - 检查 psycopg2 客户端是否正在收听主题

python - 是否可以获取 XSD 中定义的 XML 节点类型?

class - 在Flutter中的两个类之间传递变量

php - 范围解析运算符和类方法

html - 当类悬停时更改 div 的背景,反之亦然

python - 使用 2 个分类器进行集成学习

Python 记录到标准输出和 StringIO

python - Pandas Data Frame 函数应用到特定行

matlab - Kmeans在matlab中绘图

python - 使用 k-Means 聚类算法预测值