【问题标题】:How to use One-hot Encode while using NaiveBayes algorithm?使用 NaiveBayes 算法时如何使用 One-hot Encode?
【发布时间】:2018-09-10 12:25:22
【问题描述】:

我正在尝试使用朴素贝叶斯算法来满足我的一项要求。在此,我计划对超平面使用“One-hot Encode”。我使用以下代码运行我的算法。但是,我不确定如何使用“One-hot Encode”。

请找到以下代码:

from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import BernoulliNB
from sklearn.metrics import confusion_matrix

def load_data(filename):

    x = list()
    y = list()
    with open(filename) as file:
        file.readline()
        for line in file:
            line = line.strip().split(',')
            y.append(line[1])
            x.append(line[0].split())

    return x, y

X_train, y_train = load_data('/Users/Desktop/abc/train.csv')
X_test, y_test = load_data('/Users/Desktop/abc/test.csv')

onehot_enc = MultiLabelBinarizer()
onehot_enc.fit(X_train)


bnbc = BernoulliNB(binarize=None)
bnbc.fit(onehot_enc.transform(X_train), y_train)

score = bnbc.score(onehot_enc.transform(X_test), y_test)
print("score of Naive Bayes algo is :" , score)

谁能建议我上面写的代码是否正确?

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    尝试使用CountVectorizer

    from sklearn.feature_extraction.text import CountVectorizer
    
    clf = CountVectorizer()
    X_train_one_hot =  clf.fit(X_train)
    X_test_one_hot = clf.transform(X_test)
    
    bnbc = BernoulliNB(binarize=None)
    bnbc.fit(X_train_one_hot, y_train)
    
    score = bnbc.score(X_test_one_hot, y_test)
    print("score of Naive Bayes algo is :" , score)
    

    如果您打算使用 TfIdf 文本特征化,您也可以尝试使用 TfidfVectorizer

    【讨论】:

    • 嗨 Kalsi,我遇到了这个错误:return lambda x: strip_accents(x.lower()) AttributeError: 'list' object has no attribute 'lower'
    • 您可以lowercase 文本而不是列表。这个问题在这里根本不相关。
    • 是的。非常感谢您的回答。
    • 你能看看这个网址并建议我stackoverflow.com/questions/52361183/…
    猜你喜欢
    • 2019-01-05
    • 2020-10-31
    • 1970-01-01
    • 2020-12-29
    • 2021-10-09
    • 2020-09-18
    • 2017-10-03
    • 2021-11-16
    • 2017-01-25
    相关资源
    最近更新 更多