如何在 Python 的 SciKitLearn 模块中为输入字符串创建矩阵?
How to create a matrix for input string in SciKitLearn module of Python?
我已经使用 https://github.com/yassersouri/classify-text 检查了 Scikitlearn 中可用的各种算法的效率。现在,我知道分类有以下步骤
- Create a matrix of training data and corresponding classes
- Train a classifier on the basis of these matrices
- Divide the training set into training/test
现在,我想跳过第 3 步(我已经完成了)并获取用户的输入并根据训练变量对其进行测试。
现在我不确定从控制台输入后下一步是什么,我是否也需要为这个字符串构建 BOW 矩阵?
是的,您确实需要为要 运行 预测的每个新示例构建词袋表示,使用您创建的用于训练模型的相同管道转换示例。
简短回答:您需要运行通过您用于训练数据的相同词袋变换器来运行您的新字符串。
如果您使用的是 scikit-learn,我建议您直接使用 scikit-learn 特征提取工具,而不是您提供的 link 中的实用程序。如果您 click through that repository, you'll find it uses scikit-learn's CountVectorizer
计算词袋表示。
使用这种矢量化器的规范方法是在管道内,此时对新数据的预测很简单。这是一个简单的例子,为了简单起见,我省略了交叉验证方面:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.naive_bayes import MultinomialNB
corpus = ['this document is about cheese',
'this is about snakes',
'another one about cheese',
'and another one about snakes']
label = ['cheese', 'snakes', 'cheese', 'snakes']
clf = make_pipeline(CountVectorizer(), MultinomialNB())
clf.fit(corpus, label)
predicted = clf.predict(['one about cheese'])
print(predicted)
# ['cheese']
我已经使用 https://github.com/yassersouri/classify-text 检查了 Scikitlearn 中可用的各种算法的效率。现在,我知道分类有以下步骤
- Create a matrix of training data and corresponding classes
- Train a classifier on the basis of these matrices
- Divide the training set into training/test
现在,我想跳过第 3 步(我已经完成了)并获取用户的输入并根据训练变量对其进行测试。
现在我不确定从控制台输入后下一步是什么,我是否也需要为这个字符串构建 BOW 矩阵?
是的,您确实需要为要 运行 预测的每个新示例构建词袋表示,使用您创建的用于训练模型的相同管道转换示例。
简短回答:您需要运行通过您用于训练数据的相同词袋变换器来运行您的新字符串。
如果您使用的是 scikit-learn,我建议您直接使用 scikit-learn 特征提取工具,而不是您提供的 link 中的实用程序。如果您 click through that repository, you'll find it uses scikit-learn's CountVectorizer
计算词袋表示。
使用这种矢量化器的规范方法是在管道内,此时对新数据的预测很简单。这是一个简单的例子,为了简单起见,我省略了交叉验证方面:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.naive_bayes import MultinomialNB
corpus = ['this document is about cheese',
'this is about snakes',
'another one about cheese',
'and another one about snakes']
label = ['cheese', 'snakes', 'cheese', 'snakes']
clf = make_pipeline(CountVectorizer(), MultinomialNB())
clf.fit(corpus, label)
predicted = clf.predict(['one about cheese'])
print(predicted)
# ['cheese']