2017-09-24 7 views
2

ケラスを使って分類プログラムを実装しました。大きな画像があり、forループを使って各画像を予測したいと思います。ケラスは無限にメモリスワップの増加を予測します

ただし、新しいイメージが計算されるたびにスワップメモリ​​が増加します。私は、予測関数内のすべての変数を削除しようとしました(そして、私はそれが問題があるこの関数の内部であると確信しています)が、メモリはまだ増加します。

for img in images: 
    predict(img, model, categ_par, gl_par) 

と対応する関数:

def predict(image_path, model, categ_par, gl_par): 
    print("[INFO] loading and preprocessing image...") 

    orig = cv2.imread(image_path) 

    image = load_img(image_path, target_size=(gl_par.img_width, gl_par.img_height)) 
    image = img_to_array(image) 

    # important! otherwise the predictions will be '0' 
    image = image/255 

    image = np.expand_dims(image, axis=0) 

    # build the VGG16 network 
    if(categ_par.method == 'VGG16'): 
     model = applications.VGG16(include_top=False, weights='imagenet') 

    if(categ_par.method == 'InceptionV3'): 
     model = applications.InceptionV3(include_top=False, weights='imagenet') 

    # get the bottleneck prediction from the pre-trained VGG16 model 
    bottleneck_prediction = model.predict(image) 

    # build top model 
    model = Sequential() 
    model.add(Flatten(input_shape=bottleneck_prediction.shape[1:])) 
    model.add(Dense(256, activation='relu')) 
    model.add(Dropout(0.5)) 
    model.add(Dense(categ_par.n_class, activation='softmax')) 

    model.load_weights(categ_par.top_model_weights_path) 

    # use the bottleneck prediction on the top model to get the final classification 
    class_predicted = model.predict_classes(bottleneck_prediction) 
    probability_predicted = (model.predict_proba(bottleneck_prediction)) 

    classe = pd.DataFrame(list(zip(categ_par.class_indices.keys(), list(probability_predicted[0])))).\ 
    rename(columns = {0:'type', 1: 'prob'}).reset_index(drop=True) 
    #print(classe) 
    del model 
    del bottleneck_prediction 
    del image 
    del orig 
    del class_predicted 
    del probability_predicted 

    return classe.set_index(['type']).T 
+1

予測が行われるたびに新しいモデルを作成しているようです。あなたはそれが欲しいと確信していますか? –

答えて

2

あなたがforループ内の各IMGのモデルを構築しますTensorFlowバックエンドを使用している場合。 TensorFlowはグラフをグラフなどに追加し続けるだけで、メモリが単調に上昇します。これはよく知られていることであり、多くのモデルを構築する際のハイパーパラメータの最適化中に処理する必要があります。

from keras import backend as K 

と予測の終わり()でこれを置く:

K.clear_session() 

それとも、ただ一つのモデルを構築し、それぞれ新しいものを構築していないので、予測関数への入力としてあることを養うことができます時間。

関連する問題