【问题标题】:cross validation and text categorization交叉验证和文本分类
【发布时间】:2016-10-27 20:48:22
【问题描述】:

我有同样的问题,在here 中提出过:

我有一个关于在sklearn 的文本分类中使用交叉验证的问题。在交叉验证之前对所有数据进行向量化是有问题的,因为分类器会“看到”测试数据中出现的词汇。 Weka 有过滤分类器来解决这个问题。此函数的 sklearn 等效项是什么?我的意思是对于每个折叠,特征集都会不同,因为训练数据不同。

但是,因为我在分类步骤和分类步骤之间对数据进行了大量处理,所以我不能使用管道......并且试图通过我自己实现交叉验证作为整个过程的外循环...任何关于这方面的指导,因为我对python和sickitlearn都很陌生

【问题讨论】:

    标签: python scikit-learn cross-validation


    【解决方案1】:

    我认为使用交叉验证迭代器作为外循环是一个好主意,也是一个让您的步骤清晰易读的起点:

    from sklearn.cross_validation import KFold
    X = np.array(["Science today", "Data science", "Titanic", "Batman"]) #raw text
    y = np.array([1, 1, 2, 2]) #categories e.g., Science, Movies
    kf = KFold(y.shape[0], n_folds=2)
    for train_index, test_index in kf:
        x_train, y_train = X[train_index], y[train_index] 
        x_test, y_test = X[test_index], y[test_index]
        #Now continue with your pre-processing steps..
    

    【讨论】:

    • 谢谢..这正是我想要的。
    • 只是添加更新的代码! from sklearn.model_selection import KFoldimport numpy as npX = np.array(["Science today", "Data science", "Titanic", "Batman"]) #raw texty = np.array([1, 1, 2, 2]) #categories e.g., Science, Movieskf = KFold(n_splits=2)for train_index, test_index in kf.split(X):x_train, y_train = X[train_index], y[train_index] x_test, y_test = X[test_index], y[test_index]
    【解决方案2】:

    我可能错过了您的问题的含义并且不熟悉 Weka,但是您可以将词汇表作为字典传递到您在 sklearn 中使用的矢量化器中。这是一个示例,它将跳过测试集中的单词“second”,仅使用训练集中的特征。

    from sklearn.feature_extraction.text import CountVectorizer
    
    train_vectorizer = CountVectorizer()
    train = [
        'this is the first',
        'set of documents'
        ]
    
    train_matrix = train_vectorizer.fit_transform(train)
    train_vocab = train_vectorizer.vocabulary_
    
    test = [
        'this is the second',
        'set of documents'
        ]
    
    test_vectorizer = CountVectorizer(vocabulary=train_vocab)
    test_matrix = test_vectorizer.fit_transform(test)
    
    print(train_vocab)
    print(train_matrix.toarray())
    print('\n')
    print(test_vectorizer.vocabulary_)
    print(test_matrix.toarray())
    

    另请注意,您可以在矢量化器中使用自己的处理和/或标记化过程,例如:

    def preprocessor(string):
        #do logic here
    
    def tokenizer(string):
        # do logic here
    
    from sklearn.cross_validation import cross_val_score
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.pipeline import Pipeline
    from sklearn.svm import LinearSVC
    clf = Pipeline([('vect', TfidfVectorizer(processor=preprocessor, tokenizer=tokenizer)), ('svm', LinearSVC())])
    

    【讨论】:

    • 我正在向量化和分类步骤之间进行一些采样,因此我无法将其放入管道中。同时我想做交叉验证,这需要有一个管道,或者,作为一种解决方案,我正在考虑做一个外循环,对数据进行分区以进行交叉验证,然后我去处理/分类 cv 迭代中的每个数据
    猜你喜欢
    • 2018-11-15
    • 2020-08-29
    • 2021-08-05
    • 2014-05-05
    • 2017-05-07
    • 2016-03-10
    • 1970-01-01
    • 2012-09-30
    • 2016-10-17
    相关资源
    最近更新 更多