【问题标题】:How to train a tree classifier with string labels and features?如何用字符串标签和特征训练树分类器?
【发布时间】:2018-11-06 15:30:15
【问题描述】:

下面是我的代码:

import sklearn
#features = [[140,"smooth"],[130,"smooth"],[150,"bumpy"],[170,"bumpy"]]
#labels = ["apple","apple","orange","orange"]

# Now replace 1 for smooth & 0 for bumpy and 0 for apple & 1 for orange
features = [[140,1],[130,1],[150,0],[170,0]]
labels = [0,0,1,1]

# Now I train a classifier
from sklearn import tree

my_classifier = tree.DecisionTreeClassifier()
my_classifier.fit(features,labels)
predict = my_classifier.predict([[150,0]])
print(predict)

如何训练分类器而不将其转换为数字?

例如我想要下面的代码行来对我的分类器进行分类。请建议,提前谢谢:)

features = [[140,"smooth"],[130,"smooth"],[150,"bumpy"],[170,"bumpy"]]
labels = ["apple","apple","orange","orange"]

【问题讨论】:

  • 教程中说过。但是您可以使用任何类型作为标签或特征。
  • 对于不需要转换的目标(标签),它将由 scikit 处理。但是对于您需要转换的功能
  • 我删除了“...in supervised learning”,因为那是多余的。我将“字符串标签和特征”重新命名为“字符串标签和特征”,因为它们是不同的东西,它们的处理方式不同,无论是算法还是 sklearn 中的编码(取决于分类器的类型:基于树的、NN 等)。 (此外,字符串特征通常需要规范化,字符串标签不需要。)
  • 已经有124 questions for classifier string features,主要是Python。哪一个应该是规范的?

标签: python machine-learning artificial-intelligence classification decision-tree


【解决方案1】:

由于算法在后台工作的方式,您的标签和特征总是会在某个时候转换为 one-hot 向量。

您可以只维护一个字典,其中向量的哪个索引代表哪个标签,并在推断后将它们返回。

【讨论】:

  • 字符串特征应被视为分类,而不是整数。此外,我们通常首先进行一些规范化(去除无意义的大小写、空格、标点符号和数字,也许是词形还原)和容错查找(例如 Levenshtein 距离)
  • @smci 通常,当类别定义明确时,例如(困难、容易)或(平滑、颠簸)或(高、中、低)等,我们不需要您描述的其他规范化过程) ,但 Levenshtein 距离 +1 :)
  • @smci 是的,在里面它可能会被转换为单热向量而不是整数。但是,AFAIK scikit-learn 不接受标签的单热向量输入或输出,而是接受整数。如果我错了,请随时纠正我,我会更改答案。
  • 伙计们,已经在下面尝试过,它正在工作,但我相信会有另一种不错的方式来做到这一点,以防我的功能增加:from sklearn import preprocessing encoder = preprocessing.LabelEncoder() encodeValues = encoder.fit_transform(["smooth","smooth","bumpy","bumpy"]) print(encodeValues) features = [[140,1],[130,1],[150,0],[170, 0]] decodedValues = encoder.inverse_transform([1,1,0,0]) print(decodedValues)
  • @Ashish.k 你正朝着正确的方向前进。没有比这更好的方法了。只有正确的方法,那就是单热编码。这里当你说smooth=1 和bumpy=0 时,模型可能会假设smooth 的排序高于bumpy,这在你的类别中不包含任何顺序时是不相关的。
猜你喜欢
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 2015-08-24
  • 2015-09-14
  • 2012-09-17
  • 2019-10-21
  • 2021-03-16
相关资源
最近更新 更多