2017-09-24 3 views
2

나는 keras를 사용하여 분류 프로그램을 구현했습니다. 큰 이미지 세트가 있고 for 루프를 사용하여 각 이미지를 예측하고 싶습니다.keras는 메모리 스왑 증가를 무기한 예측합니다

그러나 새 이미지가 계산 될 때마다 스왑 메모리가 증가합니다. 나는 예측 함수 내부의 모든 변수를 삭제하려고 시도했지만 (문제가있는 것은이 함수 내부에 있다고 확신 함) 메모리는 여전히 증가합니다.

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

당신이 루프의 각 IMG에 대한 모델을 구축 할 것입니다 TensorFlow 백엔드를 사용하는 경우. TensorFlow는 그래프를 그래프에 추가하는 것을 계속 유지합니다. 이는 단순히 메모리가 상승한다는 것을 의미합니다. 이것은 잘 알려진 현상이며 많은 모델을 작성할 때 하이퍼 매개 변수 최적화 중에 처리해야합니다. 여기에도 있습니다.

K.clear_session() 

을 또는 당신은 단지 하나 개의 모델을 구축하고 예측 기능에 대한 입력으로 당신이 새로운 각을 구축되지 않도록 있음을 공급할 수 :

from keras import backend as K 

등) (예측의 끝이를 넣어 시각.