【发布时间】:2021-01-13 12:39:03
【问题描述】:
我有以下场景:我需要从一个字符串列表(其中 500,000 个)中区分哪些字符串与企业相关,哪些是人员。
问题的简化示例:
- Stackoverflow LLC -> 业务
- John Doe -> 人
- John Doe Inc. -> 业务
幸运的是,我标记了 500,000 个名字,所以这变成了一个有监督的问题。耶。
我运行的第一个模型是一个简单的朴素贝叶斯(多项式),下面是代码:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df["CUST_NM_CLEAN"],
df["LABEL"],test_size=0.20,
random_state=1)
# Instantiate the CountVectorizer method
count_vector = CountVectorizer()
# Fit the training data and then return the matrix
training_data = count_vector.fit_transform(X_train)
# Transform testing data and return the matrix.
testing_data = count_vector.transform(X_test)
#in this case we try multinomial, there are two other methods
from sklearn.naive_bayes import cNB
naive_bayes = MultinomialNB()
naive_bayes.fit(training_data,y_train)
#MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)
predictions = naive_bayes.predict(testing_data)
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
print('Accuracy score: {}'.format(accuracy_score(y_test, predictions)))
print('Precision score: {}'.format(precision_score(y_test, predictions, pos_label='Org')))
print('Recall score: {}'.format(recall_score(y_test, predictions, pos_label='Org')))
print('F1 score: {}'.format(f1_score(y_test, predictions, pos_label='Org')))
我得到的结果:
- 准确度得分:0.9524850665857665
- 精度分数:0.9828196680932295
- 召回分数:0.8890405236039549
- F1分数:0.9335809546092653
第一次去还不算太破旧。但是,当我将结果导出到文件并将预测与标签进行比较时,我得到的准确度非常低,大约为 60%。这与 sklearn 输出的 95% 分数相差甚远......
有什么想法吗?
这是我输出文件的方式,可能是这种情况:
mnb_results = np.array(list(zip(df["CUST_NM_CLEAN"].values.tolist(),df["LABEL"],predictions)))
mnb_results = pd.DataFrame(mnb_results, columns=['name','predicted', 'label'])
mnb_results.to_csv('mnb_vectorized.csv', index = False)
附:我是这里的新手,如果这里有明确的解决方案,我很抱歉。
【问题讨论】:
-
需要注意的是导出到 csv。如果您使用 csv 进行验证,那么我认为您需要导出 x_test、y_test、预测。此外,还可以进行交叉验证以检查其是否按预期执行。
-
你先生是救世主。对于任何未来的观众,我将代码更改为:mnb_results = np.array(list(zip(X_test, y_test, predictions)))
-
我会添加这个作为答案,你可以接受它:)
标签: python scikit-learn naivebayes