我正在尝试将Naive Bayes算法用于我的要求之一。在此,我计划对超平面使用“一次性编码”。我已使用以下代码运行算法。但是,我不确定如何使用“一次性编码”。
请找到以下代码:
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)
任何人都可以建议我以上编写的代码是否正确吗?
答案 0 :(得分: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。