クロス検証

9987 ワード

1.面白くて有益なクロス検証


validate your machine learning in a better wayはテスト、検証を通じて、あなたのアルゴリズムがやりたいことができるかどうかを評価します.

2.テストのメリット


why use training&testing data? it helps us understand our results better □ gives estimate of performance on an independent data set □ serves as check on overfitting

3.Sklearnでのトレーニング/テスト分離


sklearnのいくつかのツールを使用して、トレーニングセットとテストセットを分割する方法
import numpy as np
from sklearn import corss_validation
from sklearn import datasets
from sklearn import svm 

X_train,X_test,y_train,y_test = cross_validation.train_test_split(
    iris.data,iris.target,test_size = 0.4,random_state=0) #             
print X_train.shape,y_train.shape
print X_test.shape,y_test.shape
X_train訓練セットの特徴X_test試験セットの特徴y_train訓練セットのラベルy_test試験セットのラベル.shape how many events fall each of these two data sets,the training and the testing特徴ラベル

4.トレーニングおよびテストデータの使用方法1


the overall analysis flow:
  • train/test split train_features/test_features/train_labels/test_labels
  • PCA a feature transform pca.fit(train_features)#データ主成分pca.transform(train_features)#変換主成分表示
  • SVM a classification algorithm svc.fit svc.predict

  • pca.fit(train_features) looking for patterns in the training data testing data is only something we are going to be using as a tool for validating the steps we are talking about if we fit our PCA using our testing data,we are sort of giving ourselves a little bit of an unfair advantage.

    6.トレーニングおよびテストデータの使用方法3

    pca.fit(train_features)#データ発見主成分pca.transform(train_features)#変換主成分表示svc.train(train_features)pca.transform(test_features)#トレーニングデータで発見された主成分を使用して、私のテスト特徴を表します.

    7.トレーニングおよびテストデータの使用方法4


    after the pca.transform(test_features) ,your test data is now in the same form as your training data set.
    pca.fit(train_features)  
    pca.transform(train_features)
    svm.train(train_features)
    pca.transform(test_features)
    svc.predict(test_features)
    

    8.k-fold cross validation


    データセットをトレーニングセットとテストセットに分割するときは、トレーニングセットを最大化して最高の学習結果を得ることを望んでいます.また、テストセットを最大化して最適な検証を得ることを望んでいます.ここではトレードオフがあります.クロス検証/cross validation the basic idea is thatは、データをK個の同じサイズの容器に分割します.これまでの操作では、私たちはただその中の1つの容器を試験容器として選んで、もう1つは訓練容器として、これは静的訓練-試験方法k-fold交差検証の中で、あなたはK回の単独の学習試験learning experimentを実行して、毎回試験の中で、あなたはこのKのサブセットから1つを試験セットとして選んで、残りのK-1のサブセットを一緒に訓練セットとして置いて、それからあなたの機械の学習アルゴリズムを訓練して、以前と同じように、テストセットで性能を検証し、k-foldでクロス検証すると、この操作はK回実行され、K個のテストセットの表現を平均し、K回のテスト結果を平均値にします.K回の単独learning experimentを実行するので、計算時間がかかりますが、機械学習アルゴリズムの評価はより正確になります.ある程度、トレーニングセットにほとんどのデータを使用しているので、ほとんどのデータがテストセットに使用されています
    static train test methodology --min training time k- fold cross validation -- min run time/max accuracy

    9.SklearnのK-fold cross validation

    from sklearn.cross_validation import KFold
    t0= time()
    cv = KFold( len(authors), 2, shuffle=True ) #  shuffle       true     Sklearn K-fold cross validation     
    for train_indices,test_indices in kf:
        # make training and testing datasets
        features_train = [word_data[ii] for ii in train_indices] #           
        features_test = [word_data[ii] for ii in test_indices]
        authors_train = [authors[ii] for ii in train_indices]
        authors_test = [authors[ii] for ii in train_indices]
    
        # TFIDF and feature selection
        vectorizer = TfidfVectorizer(sublinear_tf = True,max_df=0.5,
                                     stop_words = 'english')
        feature_train_transformed = vectorizer.fit_transform(features_train)
        feature_test_transformed = vectorizer.transform(features_test)
        selector = SelectPercentile(f_classif,percentile = 10)
        selector.fit(features_train_transformed,authors_train)
        features_train_transformed = selector.transform(features_train_transformed).toarray()
        features_test_transformed = selector.transform(features_test_transformed).toarray()
    
    clf = GaussianNB()
    clf.fit(features_train_transformed,authors_train)
    print "training time:" ,round(time() - t0,3),'s'
    t0=time()
    pred = clf.predict(features_test_transfomed)
    print "predicting time",round(time() - t0,3),'s'
    acc = accuracy_score(pred,authors_test)
    print "accuracy:", round(acc,3)
    
    len(authors) the number of items in the total data set train_indices a set of indices of all the data points that i'm going to use in the training set

    10.Sklearnのk-fold cross validationに対する実用的な提案

    cv = KFold( len(authors), 2, shuffle=True ) shuffle=Trueは、特定のタイプのすべてのイベントがトレーニングセットに属することを回避し、別の特定のタイプのイベントがテストセットに属する場合、あるタイプのイベントに対するトレーニングは、別のタイプのイベントの分類に成功するのに役立ちません.

    11.パラメータを調整するためのクロス検証


    クロス検証最適なパフォーマンスを実現するためのパラメータ調整方法の選択

    12.klearnのGridSearchCV


    GridSearchCVは、クロス検証によって最適な効果パラメータを決定するために、複数のパラメータの組み合わせを系統的に巡回するために使用される.コードを数行増やすだけで、複数の組み合わせを巡ることができるというメリットがあります.
    次に、sklearnドキュメントの例を示します.
    parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
    svr = svm.SVC()
    clf = grid_search.GridSearchCV(svr, parameters)
    clf.fit(iris.data, iris.target)
    print clf.best_params_
    

    逐行説明しましょう.parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}パラメータ辞書およびその値.この場合、kernel(可能な選択は「linear」と「rbf」)とC(可能な選択は1と10)の最適な組み合わせを見つけようとします.
    この場合、異なる(kernel、C)パラメータ値からなるメッシュが自動的に生成されます.
    ('rbf', 1)
    ('rbf', 10)
    ('linear', 1)
    ('linear', 10)
    各組合せはSVMを訓練するために用いられ,交差検証を用いて表現を評価した.svr = svm.SVC()これは分類器の作成と少し似ています.最初の授業からずっとやっていたように.しかし、「clf」は次の行に生成されることに注意してください.ここでは、どのアルゴリズムを採用するかを説明しているだけです.もう1つの考え方は、「分類器」がこの場合、アルゴリズムだけでなく、アルゴリズムにパラメータ値を加えることです.ここでkernelやCに対していろいろな試みをする必要はありません.次の行でこの問題を処理します.clf = grid_search.GridSearchCV(svr, parameters)これが最初の不思議な点で、分類器が作成されました.メッシュのパラメータの組合せを生成して試みるアルゴリズム(svr)とパラメータ(parameters)辞書を伝達した.clf.fit(iris.data, iris.target)の2番目の不思議なところ.フィット関数は、すべてのパラメータの組合せを試み、適切な分類器を返し、最適なパラメータの組合せに自動的に調整します.パラメータ値はclf.best_params_で取得できます.

    15.ミニプロジェクトの概要を検証する


    安然データセットに基づいて、会社が破産したときに発生した詐欺事件のうち、利益関係者が第1版の容疑者識別器を作成した人を判断する監督学習アルゴリズムを構築する.

    16.ミニプロジェクトの検証


    このミニプロジェクトでは、トレーニングデータの分割とテストデータから始めます.「POI識別子の構築」という最終プロジェクトへの第一歩です.

    17.最初の(オーバーフィット)POI識別子


    まず、想像していた最も簡単な(検証されていない)POI識別子の構築を開始します.このレッスンの初期コード(validation/validate_poi.py)はかなり真っ白です.データを読み込み、ラベルと特徴のリストにフォーマットする役割を果たします.決定ツリー分類器を作成し(デフォルトパラメータのみを使用)、すべてのデータ(次のセクションでこの問題を修正します!)それを訓練し、精度を印刷します.これはフィッティングツリーです.この数字を信じないでください.それでも正確率はいくらですか?
    import pickle
    import sys
    sys.path.append("../tools/")
    from feature_format import featureFormat, targetFeatureSplit
    
    data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") )
    
    ### first element is our labels, any added elements are predictor
    ### features. Keep this the same for the mini-project, but you'll
    ### have a different feature list when you do the final project.
    features_list = ["poi", "salary"]
    
    data = featureFormat(data_dict, features_list)
    labels, features = targetFeatureSplit(data)
    
    
    
    ### it's all yours from here forward!  
    from sklearn import svm
    from sklearn.metrics import accuracy_score
    clf = svm.SVC()
    clf.fit(features,labels)
    pred = clf.predict(features)
    acc = accuracy_score(pred,labels)
    print acc #0.9894
    

    あなたの最初の(オーバーフィット)POI識別子の精度はいくらですか?0.9894
    Python 3.3からディクショナリキーが処理される順序が変化し,コードが実行されるたびに順序がランダム化される.これにより、スコアリングツールとプロジェクトコード(いずれもPython 2.7で実行される)との互換性の問題が発生します.この問題を修正するには、validate_poi.pyの25行目に呼び出されたfeatureFormatに次のパラメータを追加します.sort_keys = '../tools/python2_lesson13_keys.pkl'
    これにより、toolsフォルダのファイルがPython 2のキー順に開きます.
    注意:スコアツールが期待する結果を得ていない場合は、tools/feature_format.pyファイルを表示したい場合があります.最終プロジェクトの変更により、一部のファイルの変更は、ここに記載されているタスクの数の出力に影響します.リポジトリから最新バージョンのファイルを取得したかどうかを確認して、featureFormatsort_keys = Falseのデフォルトパラメータを有し、keys = dictionary.keys()が結果を生成できるようにします.

    18.配置訓練/テストメカニズム


    信頼できる精度の数字を得るために、トレーニングとテストを追加します.sklearnを使用します.cross_validationのtrain_test_split検証;30%のデータをテストに使用し、random_を設定します.stateパラメータは42です(random_stateは、テストのためにどのポイントがトレーニングセットに入るか、どのポイントが使用されるかを制御します.42に設定すると、どのイベントがどのセットにあるかを正確に知ることができ、結果を確認することができます).更新後の精度はいくらですか?
    適切に導入されたテスト範囲の精度はどのくらいですか?
    #!/usr/bin/python
    """
        Starter code for the validation mini-project.
        The first step toward building your POI identifier!
    
        Start by loading/formatting the data
    
        After that, it's not our code anymore--it's yours!
    """
    import pickle
    import sys
    sys.path.append("../tools/")
    from feature_format import featureFormat, targetFeatureSplit
    
    data_dict = pickle.load(open("../final_project/final_project_dataset.pkl", "r") )
    
    ### first element is our labels, any added elements are predictor
    ### features. Keep this the same for the mini-project, but you'll
    ### have a different feature list when you do the final project.
    features_list = ["poi", "salary"]
    
    data = featureFormat(data_dict, features_list)
    labels, features = targetFeatureSplit(data)
    
    ### it's all yours from here forward!  
    from sklearn import tree
    from sklearn.metrics import accuracy_score
    from sklearn.model_selection import train_test_split
    
    features_train, features_test, labels_train, labels_test = \
        train_test_split(features,labels,test_size=0.3,
        random_state = 42)
    
    clf = tree.DecisionTreeClassifier()
    clf.fit(features_train,labels_train)
    pred = clf.predict(features_test)
    acc = accuracy_score(pred,labels_test)
    print acc