【问题标题】:How can I alter the parameters in my algorithms for better performance?如何更改算法中的参数以获得更好的性能?
【发布时间】:2015-09-20 07:22:45
【问题描述】:

我在一组推文上运行了多项式和伯努利朴素贝叶斯,以及线性 SVC。他们在 60/40 的 1000 条训练推文中表现出色(分别为 80%、80%、90%)。

每个算法都有可以更改的参数,我想知道是否可以通过更改参数获得更好的结果。除了训练、测试和预测之外,我对机器学习了解不多,所以我想知道是否有人可以就我可以调整哪些参数给我一些建议。

这是我使用的代码:

import codecs
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB,BernoulliNB
from sklearn import svm

trainfile = 'training_words.txt'
testfile = 'testing_words.txt'

word_vectorizer = CountVectorizer(analyzer='word')  
trainset = word_vectorizer.fit_transform(codecs.open(trainfile,'r','utf8'))
tags = training_labels

mnb = svm.LinearSVC() #Or any other classifier
mnb.fit(trainset, tags)
codecs.open(testfile,'r','utf8')
testset = word_vectorizer.transform(codecs.open(testfile,'r','utf8'))
results = mnb.predict(testset)

print results

【问题讨论】:

    标签: python machine-learning scikit-learn classification


    【解决方案1】:

    您可以使用Grid Search Cross Validation 通过分层 K 折交叉验证拆分来调整模型参数。这是一个示例代码。

    import codecs
    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.naive_bayes import MultinomialNB,BernoulliNB
    from sklearn import svm
    from sklearn.grid_search import GridSearchCV
    
    testfile = 'testing_words.txt'
    
    word_vectorizer = CountVectorizer(analyzer='word')  
    trainset = word_vectorizer.fit_transform(codecs.open(trainfile,'r','utf8'))
    tags = training_labels
    
    
    mnb = svm.LinearSVC() # or any other classifier
    # check out the sklearn online docs to see what params choice we have for your
    # particular choice of estimator, for SVM, C, class_weight are important ones to tune 
    params_space = {'C': np.logspace(-5, 0, 10), 'class_weight':[None, 'auto']}
    # build a grid search cv, n_jobs=-1 to use all your processor cores
    gscv = GridSearchCV(mnb, params_space, cv=10, n_jobs=-1)
    # fit the model
    gscv.fit(trainset, tags)
    # give a look at your best params combination and best score you have
    gscv.best_estimator_
    gscv.best_params_
    gscv.best_score_
    
    
    codecs.open(testfile,'r','utf8')
    testset = word_vectorizer.transform(codecs.open(testfile,'r','utf8'))
    results = gscv.predict(testset)
    
    print results
    

    【讨论】:

    • 这给了我一个错误“这个 LinearSVC 实例还没有安装”
    • @user3600497 哪一行会引发此错误?另外,您是否可以通过保管箱共享链接上传您的testing.words.txt 文件?
    • results = mnb.predict(testset) 行导致出现问题。如果需要,我绝对可以上传测试词集。
    • @user3600497 我知道可能出了什么问题。您不需要mnb 来进行预测。相反,您应该使用gscv.predict(testset),因为最好的估计器(通过交叉验证存活的估计器)存储在gscv而不是mnb中。
    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 2011-11-26
    • 2016-08-13
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    相关资源
    最近更新 更多