이 훈련 된 모델을 어떻게 예측할 수 있습니까?

오마르 이누와

저는 기계 학습을 처음 접했고이 전이 학습 모델을 온라인에서 찾았습니다. 사소한 질문처럼 보일 수 있지만 단일 이미지로 어떻게 예측을 할 수 있습니까? 지금은 코드에 익숙하지 않지만 훈련 된 모델이 잘 작동하는 것 같습니다 (Google colab을 사용하고 있습니다).

import pandas as pd
import numpy as np
import os
import keras
import matplotlib.pyplot as plt
from keras.layers import Dense,GlobalAveragePooling2D
from keras.applications import MobileNet
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam

base_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(4,activation='softmax')(x) #final layer with softmax activation

model=Model(inputs=base_model.input,outputs=preds)
#specify the inputs
#specify the outputs
#now a model has been created based on our architecture

for layer in model.layers[:20]:
    layer.trainable=False
for layer in model.layers[20:]:
    layer.trainable=True

from zipfile import ZipFile
file_name = 'thecar.zip'

with ZipFile(file_name, 'r') as zip:
  zip.extractall()
  print('Done')

train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependencies

train_generator=train_datagen.flow_from_directory('thecar', # this is where you specify the path to the main data folder
                                                 target_size=(224,224),
                                                 color_mode='rgb',
                                                 batch_size=5,
                                                 class_mode='categorical',
                                                 shuffle=True)


model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
# Adam optimizer
# loss function will be categorical cross entropy
# evaluation metric will be accuracy

step_size_train=train_generator.n//train_generator.batch_size
model.fit_generator(generator=train_generator,
                   steps_per_epoch=step_size_train,
                   epochs=5)

제리 P

이것은 귀하의 질문에 대한 약간의 확장 일 수 있습니다. 여전히 모델을 사용할 수있는 경우에는 물론로드 할 필요가 없습니다. 또한 하나의 이미지 만있는 경우 단일 이미지에 대한 경로를 정의 할 수 있습니다. 아래 코드에서는 모델을 저장하고 이제 하나 이상의 이미지를 예측하는 데 사용하는 경우를 다루었습니다. 예측하려는 하나 이상의 이미지를 디렉토리에 배치하십시오. 그런 다음 아래 코드를 실행하십시오.

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import  load_model
import numpy as np
import cv2
import os
model_location =r'c:\temp\people\Mobilenet-99.00.h5' # location of the saved model
model=load_model(model_location) # load the saved model
image_location=r'c:\temp\people\storage' # directory storing the images that you want to predict
file_list=os.listdir(image_location)  # list of files
for f in file_list: # iterate through the files in the directory list
    f_path=os.path.join(image_location, f)  # create the path to the image file
    img=cv2.imread(f_path)    # read in the image - note cv2 reads in images in BGR format
    img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # model was trained on RGB images so convert to RGB
    img=cv2.resize(img, (128,128)) # model was trained on images of size 128  X 128 X 3 so resize the images
    img=img/127.5-1 # model was trained with pixel value scalled between -1 to +1 so convert the pixel range    
    img=np.expand_dims(img, axis=0) # model predict expects the input to have dimension (batch_size, width, height, bands)
    #print (img.shape)  # uncomment to see effect of expanding dimension
    prediction =model.predict (img, batch_size=1, verbose=0) # make predictions    
    pred=np.argmax(prediction)# find the index of the column with the highest probability
    print ('for file ', f_path, ' the index of the predicted class is ', pred, ' with a probability of ', prediction[0][pred]  )

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

사전 훈련 된 caffe 모델의 하위 집합을 어떻게 저장할 수 있습니까?

분류에서Dev

Torch에서 훈련 시간에 사전 훈련 된 임베딩을 어떻게 수정할 수 있습니까?

분류에서Dev

어떻게 Keras 만들 예측에 HDF5 파일에 저장 모델을 훈련 사용할 수 있습니까?

분류에서Dev

gensim 사전 훈련 된 모델을 doc2vec 모델에 사용할 수 있습니까?

분류에서Dev

훈련 된 신경망을 MATLAB의 메모리에 저장할 수있는 방법이 있습니까?

분류에서Dev

잘 훈련 된 ANN이 여러 클래스를 나타낼 수있는 단일 가중치 집합을 어떻게 가질 수 있습니까?

분류에서Dev

이미지가 첨부 된 모델을 어떻게 업데이트 할 수 있습니까?

분류에서Dev

iOS 용 C ++에서 훈련 된 sklearn.mixture.GMM 모델을 사용할 수 있습니까?

분류에서Dev

사전 훈련 된 기존 토치 모델은 어디에서 찾을 수 있습니까?

분류에서Dev

하나의 이미지로 훈련 된 모델을 예측하는 방법은 무엇입니까?

분류에서Dev

내 모델에서 이미 생성 된 항목을 어떻게 확인할 수 있습니까?

분류에서Dev

PyTorch로 사전 훈련 된 모델에 새 레이어를 추가하려면 어떻게해야합니까? (주어진 케 라스 예.)

분류에서Dev

내 자신의 훈련 된 Keras 모델에서 내 이미지 예측에 문제가 있습니다.

분류에서Dev

깊이 중첩되었지만 예측 가능하게 배치 된 속성에 대해 eqJoin ()을 어떻게 수행 할 수 있습니까?

분류에서Dev

사전 훈련 된 Gensim 구문 모델이 있습니까?

분류에서Dev

누락 된 CoreData 모델 버전을 어떻게 복원 할 수 있습니까?

분류에서Dev

keras 라이브러리를 사용하여 RNN을 훈련 할 때 계속 발생하는 차원 오류를 어떻게 수정할 수 있습니까?

분류에서Dev

훈련 된 모델을 kedro에 저장하는 IO 기능이 있습니까?

분류에서Dev

sklearn에서 학습 알고리즘의 훈련 임계 값을 어떻게 변경할 수 있습니까?

분류에서Dev

keras에서 훈련 할 때 기울기 계산을 어떻게 사용자 정의 할 수 있습니까?

분류에서Dev

RNN 모델 학습 후 다음 값을 어떻게 예측할 수 있습니까?

분류에서Dev

RNN 모델 학습 후 다음 값을 어떻게 예측할 수 있습니까?

분류에서Dev

Django에서이 동작을 어떻게 모델링 할 수 있습니까?

분류에서Dev

모델 데이터가 업데이트 된 후 어떻게 jQuery 함수를 호출 할 수 있습니까?

분류에서Dev

단일 클래스의 훈련 데이터로 신경망을 훈련 할 수 있습니까?

분류에서Dev

Playground (Xcode)로 훈련 된 Android에서 .mlmodel을 사용할 수 있습니까?

분류에서Dev

이 부정적인 예측을 어떻게 수정하여 작동하도록 할 수 있습니까?

분류에서Dev

메모리에 들어갈 수있는 것보다 더 많은 데이터로 신경망을 어떻게 훈련시킬 수 있습니까?

분류에서Dev

새 엔티티로 Spacy 모델을 훈련 한 후 훈련 된 NER 모델은 어디에 저장됩니까?

Related 관련 기사

  1. 1

    사전 훈련 된 caffe 모델의 하위 집합을 어떻게 저장할 수 있습니까?

  2. 2

    Torch에서 훈련 시간에 사전 훈련 된 임베딩을 어떻게 수정할 수 있습니까?

  3. 3

    어떻게 Keras 만들 예측에 HDF5 파일에 저장 모델을 훈련 사용할 수 있습니까?

  4. 4

    gensim 사전 훈련 된 모델을 doc2vec 모델에 사용할 수 있습니까?

  5. 5

    훈련 된 신경망을 MATLAB의 메모리에 저장할 수있는 방법이 있습니까?

  6. 6

    잘 훈련 된 ANN이 여러 클래스를 나타낼 수있는 단일 가중치 집합을 어떻게 가질 수 있습니까?

  7. 7

    이미지가 첨부 된 모델을 어떻게 업데이트 할 수 있습니까?

  8. 8

    iOS 용 C ++에서 훈련 된 sklearn.mixture.GMM 모델을 사용할 수 있습니까?

  9. 9

    사전 훈련 된 기존 토치 모델은 어디에서 찾을 수 있습니까?

  10. 10

    하나의 이미지로 훈련 된 모델을 예측하는 방법은 무엇입니까?

  11. 11

    내 모델에서 이미 생성 된 항목을 어떻게 확인할 수 있습니까?

  12. 12

    PyTorch로 사전 훈련 된 모델에 새 레이어를 추가하려면 어떻게해야합니까? (주어진 케 라스 예.)

  13. 13

    내 자신의 훈련 된 Keras 모델에서 내 이미지 예측에 문제가 있습니다.

  14. 14

    깊이 중첩되었지만 예측 가능하게 배치 된 속성에 대해 eqJoin ()을 어떻게 수행 할 수 있습니까?

  15. 15

    사전 훈련 된 Gensim 구문 모델이 있습니까?

  16. 16

    누락 된 CoreData 모델 버전을 어떻게 복원 할 수 있습니까?

  17. 17

    keras 라이브러리를 사용하여 RNN을 훈련 할 때 계속 발생하는 차원 오류를 어떻게 수정할 수 있습니까?

  18. 18

    훈련 된 모델을 kedro에 저장하는 IO 기능이 있습니까?

  19. 19

    sklearn에서 학습 알고리즘의 훈련 임계 값을 어떻게 변경할 수 있습니까?

  20. 20

    keras에서 훈련 할 때 기울기 계산을 어떻게 사용자 정의 할 수 있습니까?

  21. 21

    RNN 모델 학습 후 다음 값을 어떻게 예측할 수 있습니까?

  22. 22

    RNN 모델 학습 후 다음 값을 어떻게 예측할 수 있습니까?

  23. 23

    Django에서이 동작을 어떻게 모델링 할 수 있습니까?

  24. 24

    모델 데이터가 업데이트 된 후 어떻게 jQuery 함수를 호출 할 수 있습니까?

  25. 25

    단일 클래스의 훈련 데이터로 신경망을 훈련 할 수 있습니까?

  26. 26

    Playground (Xcode)로 훈련 된 Android에서 .mlmodel을 사용할 수 있습니까?

  27. 27

    이 부정적인 예측을 어떻게 수정하여 작동하도록 할 수 있습니까?

  28. 28

    메모리에 들어갈 수있는 것보다 더 많은 데이터로 신경망을 어떻게 훈련시킬 수 있습니까?

  29. 29

    새 엔티티로 Spacy 모델을 훈련 한 후 훈련 된 NER 모델은 어디에 저장됩니까?

뜨겁다태그

보관