【问题标题】:how can i use SVM for text classification without using Tf-idf如何在不使用 Tf-idf 的情况下使用 SVM 进行文本分类
【发布时间】:2019-05-28 12:13:14
【问题描述】:

我想对每个条目消息进行分类。我使用波斯文本。我已经用朴素贝叶斯实现了一个文本分类器。我没有使用Tf-idf,因为每个功能对我来说都很重要。但我做了一些技巧来删除stop-wordspouncs 以获得更好的准确性。

我想用 SVM 实现一个文本分类器,但我搜索了很多。我发现的所有内容都与使用Tf-idf 的管道功能有关。如下:

model = Pipeline([(‘vectorizer’, CountVectorizer()),
(‘tfidf’, TfidfTransformer()),
(‘clf’, OneVsRestClassifier(LinearSVC(class_weight=”balanced”)))])

现在,我如何在没有 Tf-idf 的情况下使用 SVM?

谢谢

【问题讨论】:

  • 您能否提供更多有关您正在尝试构建的模型的信息?你有什么特点?字?您是否使用按摩词袋作为您的数据?
  • 我的模型包括正文作为消息文本和标签。我有 6 个标签。是的,我的数据是由一些构成句子的单词组成的。@thebeancounter

标签: python svm


【解决方案1】:

在此处查看Sklearn page关于SVM,您有一个用于使用SVM的多字符分类部分。首先,您必须将文本转换为特征向量(数字,如果您希望使用SVM),如果您想使用您可以使用的单词this SO Quity and this手册页@ sklearn

您可以使用预先写的python代码从您的文本创建弓,这些文本做出了类似的事情 - 介意你,我把妨碍了OP的相关信息 - 这是不清楚的,而且与所以的STRANDARTS不兼容,所以你可能需要工作为它编写代码以适应您的确切用法。

>>> from sklearn.feature_extraction.text import CountVectorizer

>>> vectorizer = CountVectorizer()
>>> vectorizer                     
CountVectorizer(analyzer=...'word', binary=False, decode_error=...'strict',
        dtype=<... 'numpy.int64'>, encoding=...'utf-8', input=...'content',
        lowercase=True, max_df=1.0, max_features=None, min_df=1,
        ngram_range=(1, 1), preprocessor=None, stop_words=None,
        strip_accents=None, token_pattern=...'(?u)\\b\\w\\w+\\b',
        tokenizer=None, vocabulary=None)


>>> corpus = [
...     'This is the first document.',
...     'This is the second second document.',
...     'And the third one.',
...     'Is this the first document?',
... ]
>>> X = vectorizer.fit_transform(corpus)
>>> X                              
<4x9 sparse matrix of type '<... 'numpy.int64'>'
    with 19 stored elements in Compressed Sparse ... format>

然后您可能需要将 x 转换为密集矩阵(取决于 sklearn 版本) 然后你可以将 x 输入 SVM 模型,你可以像这样创建

>>>>from sklearn import svm
>>> X = [[0], [1], [2], [3]]
>>> Y = [0, 1, 2, 3]
>>> clf = svm.SVC(gamma='scale', decision_function_shape='ovo')
>>> clf.fit(X, Y) 
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
    decision_function_shape='ovo', degree=3, gamma='scale', kernel='rbf',
    max_iter=-1, probability=False, random_state=None, shrinking=True,
    tol=0.001, verbose=False)
>>> dec = clf.decision_function([[1]])
>>> dec.shape[1] # 4 classes: 4*3/2 = 6
6
>>> clf.decision_function_shape = "ovr"
>>> dec = clf.decision_function([[1]])
>>> dec.shape[1] # 4 classes

【讨论】:

    猜你喜欢
    • 2018-10-24
    • 2020-03-22
    • 2017-05-08
    • 2017-02-27
    • 2021-03-25
    • 2014-08-24
    • 2019-04-27
    • 2013-07-16
    • 2019-12-12
    相关资源
    最近更新 更多