2016-12-07 75 views
0

SciKit-Learn KFoldを使用してデータを分割するKerasとTheanoバックエンドの画像分類ネットワークで相互検証を実行しようとしています。しかし、トレーニングは3回は正常に実行されており、GPUでメモリ不足エラーが発生します。Kerasを使用したクロスバリデーション中にGPUメモリを解放する

各折りたたみの最後にGPUメモリを解放するために何もしません。新しい折り畳みを開始する前にGPUのメモリをクリアすることができるかどうか知らせてもらえますか?

ありがとうございます。

答えて

0

私は最近この同じ問題にぶつかりました。これはメモリを本当にクリアしないため、これは素晴らしい解決策ではありません。

しかし私の提案は、モデルを一度コンパイルして最初の重みを保存することです。次に、各折り畳みの始めにウエイトをリロードします。

次のコードのようなもの:

from sklearn.model_selection import KFold 
from sklearn.model_selection import cross_val_score 
from functools import partial 
import numpy as np 
from keras.applications import VGG16 

# We create our model only once 
def create_model(): 
    model_vgg16_conv = VGG16(weights='imagenet', include_top=True) 

    model_vgg16_conv.compile(optimizer="adam", loss="mean_squared_error") 
    return model_vgg16_conv, model_vgg16_conv.get_weights() 

# we initialize it multiple times 
def init_weight(same_old_model, first_weights): 
    ## we can uncomment the line below to reshufle the weights themselves so they are not exactly the same between folds 
    ## weights = [np.random.permutation(x.flat).reshape(x.shape) for x in first_weights] 

    same_old_model.set_weights(weights) 


model_vgg16_conv, weights = create_model() 


# we create just random data compliant with the vgg16 architecture and the 1000 imagenet labels 
data = np.random.randint(0,255, size=(100, 224,224,3)) 
labels = np.random.randint(0,1, size=(100, 1000)) 

cvscores = [] 
kfold = KFold(n_splits=10, shuffle=True) 
for train, test in kfold.split(data, labels): 
    print("Initializing Weights...") 
    ## instead of creating a new model, we just reset its weights 
    init_weight(model_vgg16_conv, weights) 

    # fit as usual, but using the split that came from KFold 
    model_vgg16_conv.fit(data[train], labels[train], epochs=2) 

    scores = model_vgg16_conv.evaluate(data[test], labels[test]) 

    #evaluation 
    print("%s: %.2f%%" % (model_vgg16_conv.metrics_names[0], scores)) 
    cvscores.append(scores) 

print("%.2f (+/- %.2f)" % (np.mean(cvscores), np.std(cvscores))) 
関連する問題