python-3.x - 为什么使用 Gaussian NB 分类器查找测试数据的分数时得到 0.0 的分数?
问题描述
我有两个不同的数据集。一个用于训练我的分类器,另一个用于测试。两个数据集都是文本文件,两列由“,”分隔。第一列(数字)是自变量(组),第二列是因变量。
训练数据集
(例如只有几行。每行之间没有空行):
EMI3776438,1
EMI3776438,1
EMI3669492,1
EMI3752004,1
测试数据设置
(如您所见,我从训练数据中挑选数据以确保分数肯定不能为零)
EMI3776438,1
Python 3.6 中的代码:
# #all the import statements have been ignored to keep the code short
# #loading the training data set
training_file_path=r'C:\Users\yyy\Desktop\my files\python\Machine learning\Carepack\modified_columns.txt'
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
training_file_data = pandas.read_table(training_file_path,
header=None,
names=['numbers','group'],
sep=',')
training_file_data = training_file_data.apply(le.fit_transform)
features = ['numbers']
x = training_file_data[features]
y = training_file_data["group"]
from sklearn.model_selection import train_test_split
training_x,testing_x, training_y, testing_y = train_test_split(x, y,
random_state=0,
test_size=0.1)
from sklearn.naive_bayes import GaussianNB
gnb= GaussianNB()
gnb.fit(training_x, training_y)
# #loading the testing data
testing_final_path=r"C:\Users\yyy\Desktop\my files\python\Machine learning\Carepack\testing_final.txt"
testing_sample_data=pandas.read_table(testing_final_path,
sep=',',
header=None,
names=['numbers','group'])
testing_sample_data = testing_sample_data.apply(le.fit_transform)
category = ["numbers"]
testing_sample_data_x = testing_sample_data[category]
# #finding the score of the test data
print(gnb.score(testing_sample_data_x, testing_sample_data["group"]))
解决方案
首先,上述数据样本没有显示其中有多少类。你需要更多地描述它。
其次,您le.fit_transform
再次调用测试数据,这将忘记从字符串到数字的所有训练样本映射。该LabelEncoder
文件将从头开始重新编码测试数据,这将不等于它映射训练数据的方式。所以GaussianNB
现在的输入不正确,因此结果不正确。
将其更改为:
testing_sample_data = testing_sample_data.apply(le.transform)
更新:
很抱歉,我忽略了您的数据中有两列的事实。LabelEncoder
仅适用于单列数据。要使其一次在多个 pandas 列上工作,请查看以下问题的答案:
如果您使用的是最新版本的 scikit ( 0.20
) 或可以更新到它,那么您不需要任何此类 hack 并直接使用OrdinalEncoder
:
from sklearn.preprocessing import OrdinalEncoder
enc = OrdinalEncoder()
training_file_data = enc.fit_transform(training_file_data)
在测试期间:
training_file_data = enc.transform(training_file_data)
推荐阅读
- android - 如何在 Android 应用程序中包含不同的语言
- excel - 时间自动刷新
- wordpress - 在媒体 wp api 中上传图片
- c - 我打印学生详细信息的 c 程序不起作用
- python - 在 Django 的详细视图中获取方法
- sql - 如果我对另一个表执行 INNER JOIN,为什么一个表的 SUM 会上升?
- fortran - 在 Fortran 中生成随机数
- php - PhpStorm 无法与 Xdebug 3 一起使用:已配置但 PhpStorm 未检测到 Xdebug
- jakarta-ee - 针对 Micro 和嵌入式运行时的 javax.ejb.TransactionRolledbackLocalException
- python - 向 TestReport 对象添加新字段并在 pytest_html_results_table_html 挂钩中使用它