사전 훈련 된 CNN을 사용하여 소수의 데이터 세트에서 특성을 추출 했으므로 특히 VGG16Animals, CALTECH-101 또는 _Flowers-17_이 아닌 ImageNet에서 훈련되었다는 점을 고려할 때 이러한 특성이 실제로 얼마나 발휘되는지 확인해보겠습니다.

간단한 선형 모델이 이러한 특징을 사용하여 이미지를 분류할 때 얼마나 그 효과는 얼마나 될까요?
새 파일을 열고 이름을 train_model.py로 지정하고 다음 코드를 작성합니다.

# USAGE
# python train_model.py --db ../datasets/animals/hdf5/features.hdf5 \
#    --model animals.cpickle
# python train_model.py --db ../datasets/caltech-101/hdf5/features.hdf5 \
#    --model caltech101.cpickle
# python train_model.py --db ../datasets/flowers17/hdf5/features.hdf5 \
#    --model flowers17.cpickle

# import the necessary packages
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
import argparse
import pickle
import h5py

GridSearchCV클래스는 매개 변수를 LogisticRegression 분류기로 바꾸는 데 사용됩니다. 학습 후에는 pickle을 사용하여 LogisticRegression 모델을 디스크에 직렬화합니다.

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--db", required=True,
    help="path HDF5 database")
ap.add_argument("-m", "--model", required=True,
    help="path to output model")
ap.add_argument("-j", "--jobs", type=int, default=-1,
    help="# of jobs to run when tuning hyperparameters")
args = vars(ap.parse_args())

스크립트에는 두 개의 명령 줄 인수와 세 번째 선택적 인수가 필요합니다.

  1. --db : 추출된 기능 및 클래스 레이블이 포함 된 HDF5 데이터 세트의 경로입니다.
  2. --model : 여기서 출력 로지스틱 회귀 분류기에 대한 경로를 제공합니다.
  3. --jobs : 하이퍼 파라미터를 로지스틱 회귀 모델에 맞게 조정하기 위해 그리드 검색을 실행할 때 동시 작업 수를 지정하는 데 사용되는 선택적 정수입니다.

HDF5 데이터 세트를 열고 학습/테스트 분할 위치를 결정하겠습니다.

# open the HDF5 database for reading then determine the index of
# the training and testing split, provided that this data was
# already shuffled *prior* to writing it to disk
db = h5py.File(args["db"], "r")
i = int(db["labels"].shape[0] * 0.75)

이 장의 앞부분에서 언급했듯이, 우리는 관련 이미지 / 특징 벡터를 HDF5 데이터 세트에 쓰기 전에 의도적으로 이미지 경로를 셔플했습니다.이 이유는 라인 22와 23에서 명확 해집니다.

데이터 세트가 너무 커서 메모리에 넣을 수 없기 때문에 훈련 및 테스트 분할을 결정하는 효율적인 방법이 필요합니다. HDF5 데이터 세트에 얼마나 많은 항목이 있는지 알고 있기 때문에 (그리고 데이터의 75 %를 훈련에 사용하고 25 %를 평가에 사용하고자 함을 알고 있으므로) 데이터베이스에 75 % 인덱스 i를 간단히 계산할 수 있습니다. 인덱스 i 이전의 모든 데이터는 훈련 데이터로 간주됩니다. i 이후의 모든 데이터는 데이터를 테스트합니다.

훈련 및 테스트 분할을 고려하여 로지스틱 회귀 분류기를 훈련 해 보겠습니다.

# define the set of parameters that we want to tune then start a
# grid search where we evaluate our model for each value of C
print("[INFO] tuning hyperparameters...")
params = {"C": [0.1, 1.0, 10.0, 100.0, 1000.0, 10000.0]}
model = GridSearchCV(LogisticRegression(solver="lbfgs",
    multi_class="auto"), params, cv=3, n_jobs=args["jobs"])
model.fit(db["features"][:i], db["labels"][:i])
print("[INFO] best hyperparameters: {}".format(model.best_params_))

# evaluate the model
print("[INFO] evaluating...")
preds = model.predict(db["features"][i:])
print(classification_report(db["labels"][i:], preds,
    target_names=db["label_names"]))

28-31 행은 최적 값이 무엇인지 결정하기 위해 로지스틱 회귀 분류기의 엄격함 인 매개 변수 C에 대한 그리드 검색을 실행합니다. Logistic Regression에 대한 자세한 검토는이 책의 범위를 벗어나므로 Logistic Regression 분류기 [13]에 대한 철저한 검토는 Andrew Ng의 메모를 참조하십시오.

배열 슬라이스를 통해 훈련 데이터와 훈련 레이블을 어떻게 표시하는지 확인하십시오.

# evaluate the model
print("[INFO] evaluating...")
preds = model.predict(db["features"][i:])
print(classification_report(db["labels"][i:], preds,
    target_names=db["label_names"]))

다시 말하지만, 인덱스 i 이전의 모든 데이터는 훈련 세트의 일부입니다. 최상의 하이퍼 파라미터가 발견되면 테스트 데이터에서 분류자를 평가합니다 (36-38 행).

여기에서 테스트 데이터와 테스트 레이블은 배열 슬라이스를 통해 액세스됩니다.

인덱스 i 이후의 모든 것은 테스트 세트의 일부입니다. HDF5 데이터 세트가 디스크에 있고 (메모리에 맞추기에는 너무 커서) NumPy 배열 인 것처럼 처리 할 수 있습니다. 이는 HDF5 및 h5py를 딥 러닝 및 머신에 함께 사용하는 것의 큰 장점 중 하나입니다. 학습 과제.

마지막으로 LogisticRegression 모델을 디스크에 저장하고 데이터베이스를 닫습니다.

# serialize the model to disk
print("[INFO] saving model...")
f = open(args["model"], "wb")
f.write(pickle.dumps(model.best_estimator_))
f.close()

# close the database
db.close()

 

'keras > 2. Feature Extractors' 카테고리의 다른 글

3. The Feature Extraction Process  (0) 2020.08.24
2. Writing Features to an HDF5 Dataset  (0) 2020.08.22
1. Networks as Feature Extractors  (0) 2020.08.22

+ Recent posts