【问题标题】:How to test unseen test data with cross validation and predict labels?如何使用交叉验证测试看不见的测试数据并预测标签?
【发布时间】:2020-06-21 10:50:12
【问题描述】:

1.包含数据(即文本描述)以及分类标签的CSV

df = pd.read_csv('./output/csv_sanitized_16_.csv', dtype=str)
X = df['description_plus']
y = df['category_id']

2.此 CSV 包含需要预测标签的看不见的数据(即文本描述)

df_2 = pd.read_csv('./output/csv_sanitized_2.csv', dtype=str)
X2 = df_2['description_plus']

对上述训练数据(项目 #1)进行操作的交叉验证函数。

def cross_val():
    cv = KFold(n_splits=20)
    vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5,
                                     stop_words='english')
    X_train = vectorizer.fit_transform(X) 
    clf = make_pipeline(preprocessing.StandardScaler(with_mean=False), svm.SVC(C=1))
    scores = cross_val_score(clf, X_train, y, cv=cv)
    print(scores)
    print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
cross_val()

我需要知道如何将看不见的数据(项目 #2)传递给交叉验证函数以及如何预测标签?

【问题讨论】:

    标签: python-3.x pandas scikit-learn sklearn-pandas


    【解决方案1】:

    使用scores = cross_val_score(clf, X_train, y, cv=cv)只能得到模型的交叉验证分数。 cross_val_score 将根据cv 参数在内部将数据拆分为训练和测试。

    因此,您获得的值是 SVC 的交叉验证准确性。

    要获得看不见的数据的分数,您可以首先拟合模型,例如

    clf = make_pipeline(preprocessing.StandardScaler(with_mean=False), svm.SVC(C=1))
    clf.fit(X_train, y) # the model is trained now
    

    然后做clf.score(X_unseen,y)

    最后一个将返回模型在看不见的数据上的准确性。


    编辑:做你想做的最好的方法是使用 GridSearch 首先使用训练数据找到最佳模型,然后使用看不见的(测试)数据评估最佳模型:

    from sklearn import svm, datasets
    from sklearn.model_selection import GridSearchCV
    from sklearn.model_selection import train_test_split
    from sklearn.model_selection import cross_val_score
    
    # load some data
    iris = datasets.load_iris()
    X, y = iris.data, iris.target
    
    #split data to training and test sets
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
    
    # hyperparameter tunig of the SVC model
    parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
    svc = svm.SVC()
    
    # fit the GridSearch using the TRAINING data
    grid_searcher = GridSearchCV(svc, parameters)
    grid_searcher.fit(X_train, y_train)
    
    #recover the best estimator (best parameters for the SVC, based on the GridSearch)
    best_SVC_model = grid_searcher.best_estimator_
    
    # Now, check how this best model behaves on the test set
    cv_scores_on_unseen = cross_val_score(best_SVC_model, X_test, y_test, cv=5)
    print(cv_scores_on_unseen.mean())
    

    【讨论】:

    • 我们是否通过这种方法利用了交叉验证?如果我们想要执行交叉验证然后拟合模型并预测分数,是否应该在 cross_val_score 函数之后添加您建议的行?
    • 您也可以使用此功能,但您将获得的分数将是未见集上 cv 下的交叉验证分数(如前所述,这将在内部再次拆分)
    • 因此您可以仅预测或再次实际使用 cross_val_score,然后将这些值报告为未见数据集上的 CV 分数。
    • 所以如果我理解正确,我们可以使用 k 折验证来为我的测试分类问题选择哪个是好的模型(通过将不同的模型传递给 k 折验证),然后使用该模型进行训练使用标记的数据并预测看不见的数据。对吗?
    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 2021-03-29
    • 2018-05-07
    • 1970-01-01
    • 2016-09-02
    • 2017-12-20
    • 2011-01-24
    • 2017-12-03
    相关资源
    最近更新 更多