我有一个包含200条数据的小数据集。这个数据集非常简单:每一行包含一个在[0, 1]范围内的实数值,并映射到一个标签。总共有24个标签,我的任务本质上是训练一个分类器来找到映射到每个标签的范围。
我想到了两种方法。第一种是使用支持向量分类器(SVC),因为它们能够将输入平面分成24个区域,这正是我所需要的。然而,当我尝试编写代码时,结果非常糟糕:分类器没有学到任何东西,无论输入值是什么,它都会输出相同的标签。
我正在考虑的第二种方法是使用神经网络,但考虑到特征和训练数据的缺乏,我非常怀疑这种方法的可行性。
如果需要,我可以分享我使用scikit-learn开发的SVC代码。
以下是我在终端上导出的数据预览:
Label: Min, Mean, Max{0: [0.96, 0.98, 1.0], 1: [0.15, 0.36, 0.92], 2: [0.14, 0.56, 0.98], 3: [0.37, 0.7, 1.0], 4: [0.23, 0.23, 0.23], 6: [0.41, 0.63, 0.97], 7: [0.13, 0.38, 0.61], 8: [0.11, 0.68, 1.0], 9: [0.09, 0.51, 1.0], 10: [0.19, 0.61, 0.97], 11: [0.26, 0.41, 0.57], 12: [0.29, 0.72, 0.95], 13: [0.63, 0.9, 0.99], 14: [0.06, 0.55, 1.0], 15: [0.1, 0.64, 1.0], 16: [0.26, 0.58, 0.95], 17: [0.29, 0.88, 1.0], 21: [0.58, 0.79, 1.0], 22: [0.24, 0.59, 0.94], 23: [0.12, 0.62, 0.95]}
如你所见,数据分布非常分散,但我希望找出每个标签最能代表的范围是否存在。
如果有人能告诉我我是否走在正确的道路上,我将不胜感激。谢谢!
回答:
如果我们假设每个类别的样本是大致集中(但仍然有噪声;可以有重叠),那么在sklearn中最自然的分类器可能是高斯朴素贝叶斯,我们假设每个类别的点遵循正态分布。
以下是一些代码,用于构建一些假数据,对其进行分类并评估:
import numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import accuracy_scorenp.random.seed(1)""" Data-params + Data-generation """N_CLASSES = 24N_SAMPLES_PER_CLASS = 10SIGMA = 0.01class_centers = np.random.random(size=N_CLASSES)# ugly code with bad numpy-styleX = []for class_center in class_centers: samples = np.random.normal(size=N_SAMPLES_PER_CLASS)*SIGMA for sample in samples + class_center: X.append(sample)Y = []for ind, c in enumerate(class_centers): for s in range(N_SAMPLES_PER_CLASS): Y.append(ind)X = np.array(X).reshape(-1, 1)Y = np.array(Y)""" Split & Fit & Eval """X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.1, random_state=0)et = GaussianNB()et.fit(X_train, y_train)print('Prediction on test')preds = et.predict(X_test)print(preds)print('Original samples')print(y_test)print('Accuracy-score')print(accuracy_score(y_test, preds))
输出
Prediction on test[10 7 3 7 8 3 23 3 11 19 7 20 8 15 11 13 18 11 3 16 8 9 8 12]Original samples[10 7 3 7 10 22 15 22 15 19 7 20 8 15 23 13 18 11 22 0 10 17 8 12]Accuracy-score0.583333333333
当然,结果高度依赖于N_SAMPLES_PER_CLASS
和SIGMA
。
编辑:
由于你现在展示了你的数据,很明显我的假设不成立。请看以下由这段代码生成的图表(文件已从[]()
中删除;人们真的应该发布csv兼容的数据!):
import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsdata = pd.read_csv('idVXjwgZ.txt', usecols=[0,1], names=['x', 'y'])sns.swarmplot(data=data, x='y', y='x')plt.show()
图表:
现在想象一下观察到某个x
值,你需要决定y
值。对于大多数x
范围来说,这非常困难。
显然还有类别平衡问题,这解释了为什么大多数预测输出的是类别14。