2016-12-19 2 views
4

convn net의 k 배 교차 유효성 검사는 신경 네트워크의 거대한 실행 시간 때문에 심각하게 취해지지 않은 것으로 보입니다. 나는 작은 데이터 세트를 가지고 있으며, here 예제를 사용하여 k- 배 교차 검증에 관심이 있습니다. 가능한가? 감사.케라를 사용하는 K 배 교차 유효성 확인

+0

예, 가능합니다. 나는 Keras에서 out-of-the-box k-fold 교차 검증이 있다고 생각하지 않는다. 데이터 세트를 직접 k 폴드로 분할하고 성능 측정 값을 추적해야합니다. –

+0

@SergiiGryshkevych에 추가하려면 k-fold 교차 유효성 검사를 구현하기 위해 keras/engine/training.py에서 fit() 및 _fit_loop()을 수정해야합니다. – indraforyou

+0

이 블로그 게시물을보십시오 http://machinelearningmastery.com/use-keras-deep-learning-models-scikit-learn-python/ – rob

답변

1

데이터 생성기가있는 이미지를 사용하는 경우 Keras 및 scikit-learn을 사용하여 10 배 교차 유효성 검사를 수행하는 한 가지 방법이 있습니다. 이 전략은 각 접기에 따라 training, validationtest 개의 하위 폴더에 파일을 복사하는 것입니다. 당신의 예측() 함수에서

import numpy as np 
import os 
import pandas as pd 
import shutil 
from sklearn.model_selection import StratifiedKFold 
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix 

# used to copy files according to each fold 
def copy_images(df, directory): 
    destination_directory = "{path to your data directory}/" + directory 
    print("copying {} files to {}...".format(directory, destination_directory)) 

    # remove all files from previous fold 
    if os.path.exists(destination_directory): 
     shutil.rmtree(destination_directory) 

    # create folder for files from this fold 
    if not os.path.exists(destination_directory): 
     os.makedirs(destination_directory) 

    # create subfolders for each class 
    for c in set(list(df['class'])): 
     if not os.path.exists(destination_directory + '/' + c): 
      os.makedirs(destination_directory + '/' + c) 

    # copy files for this fold from a directory holding all the files 
    for i, row in df.iterrows(): 
     try: 
      # this is the path to all of your images kept together in a separate folder 
      path_from = "{path to all of your images}" 
      path_from = path_from + "{}.jpg" 
      path_to = "{}/{}".format(destination_directory, row['class']) 

      # move from folder keeping all files to training, test, or validation folder (the "directory" argument) 
      shutil.copy(path_from.format(row['filename']), path_to) 
     except Exception, e: 
      print("Error when copying {}: {}".format(row['filename'], str(e))) 

# dataframe containing the filenames of the images (e.g., GUID filenames) and the classes 
df = pd.read_csv('{path to your data}.csv') 
df_y = df['class'] 
df_x = df 
del df_x['class'] 

skf = StratifiedKFold(n_splits = 10) 
total_actual = [] 
total_predicted = [] 
total_val_accuracy = [] 
total_val_loss = [] 
total_test_accuracy = [] 

for i, (train_index, test_index) in enumerate(skf.split(df_x, df_y)): 
    x_train, x_test = df_x.iloc[train_index], df_x.iloc[test_index] 
    y_train, y_test = df_y.iloc[train_index], df_y.iloc[test_index] 

    train = pd.concat([x_train, y_train], axis=1) 
    test = pd.concat([x_test, y_test], axis = 1) 

    # take 20% of the training data from this fold for validation during training 
    validation = train.sample(frac = 0.2) 

    # make sure validation data does not include training data 
    train = train[~train['filename'].isin(list(validation['filename']))] 

    # copy the images according to the fold 
    copy_images(train, 'training') 
    copy_images(validation, 'validation') 
    copy_images(test, 'test') 

    print('**** Running fold '+ str(i)) 

    # here you call a function to create and train your model, returning validation accuracy and validation loss 
    val_accuracy, val_loss = create_train_model(); 

    # append validation accuracy and loss for average calculation later on 
    total_val_accuracy.append(val_accuracy) 
    total_val_loss.append(val_loss) 

    # here you will call a predict() method that will predict the images on the "test" subfolder 
    # this function returns the actual classes and the predicted classes in the same order 
    actual, predicted = predict() 

    # append accuracy from the predictions on the test data 
    total_test_accuracy.append(accuracy_score(actual, predicted)) 

    # append all of the actual and predicted classes for your final evaluation 
    total_actual = total_actual + actual 
    total_predicted = total_predicted + predicted 

    # this is optional, but you can also see the performance on each fold as the process goes on 
    print(classification_report(total_actual, total_predicted)) 
    print(confusion_matrix(total_actual, total_predicted)) 

print(classification_report(total_actual, total_predicted)) 
print(confusion_matrix(total_actual, total_predicted)) 
print("Validation accuracy on each fold:") 
print(total_val_accuracy) 
print("Mean validation accuracy: {}%".format(np.mean(total_val_accuracy) * 100)) 

print("Validation loss on each fold:") 
print(total_val_loss) 
print("Mean validation loss: {}".format(np.mean(total_val_loss))) 

print("Test accuracy on each fold:") 
print(total_test_accuracy) 
print("Mean test accuracy: {}%".format(np.mean(total_test_accuracy) * 100)) 

, 당신은 데이터 생성, 테스트는 batch_size 1의 사용 때 나는 같은 순서로 예측을 유지하기 위해 찾을 수있는 유일한 방법은 사용하는 경우 :

generator = ImageDataGenerator().flow_from_directory(
     '{path to your data directory}/test', 
     target_size = (img_width, img_height), 
     batch_size = 1, 
     color_mode = 'rgb', 
     # categorical for a multiclass problem 
     class_mode = 'categorical', 
     # this will also ensure the same order 
     shuffle = False) 

이 코드를 사용하면 데이터 생성기를 사용하여 10 배 교차 유효성 검사를 수행 할 수 있었기 때문에 모든 파일을 메모리에 보관할 필요가 없었습니다. 수백만 개의 이미지를 가지고 있고 테스트 세트가 큰 경우 batch_size = 1이 병목 현상이 될 수있는 경우 많은 작업이 될 수 있지만 프로젝트의 경우 잘 수행됩니다.