keras 讀取模型進行測試的方式

2021-10-04 01:23:19 字數 2415 閱讀 1878

本篇部落格僅供自己查資料時使用。 

from keras.preprocessing import image

import numpy as np

from keras.models import load_model

import os

from shutil import copyfile

from keras.preprocessing.image import imagedatagenerator

work_dir = ''

#載入模型

def read_model():

model = load_model(work_dir + '/model_weight.h5')

return model

#單張讀取,並**

def read_model_predict(img_path,model):

img = image.load_img(img_path, target_size=(100, 100))

x = image.img_to_array(img)

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

#print(x)

#歸一化

amin, amax = x.min(), x.max() # 求最大最小值

x = (x-amin)/(amax-amin)

preds = model.predict(x)

return preds

#測試資料集讀取

def read_test(test_data_dir):

test_datagen = imagedatagenerator(rescale=1. / 255)

test_generator = test_datagen.flow_from_directory(

test_data_dir,

target_size=(100, 100),

batch_size=64,

class_mode='binary'

)model = load_model(work_dir + '/model_weight.h5')

score = model.evaluate_generator(test_generator,steps=1)

print("樣本準確率%s: %.2f%%" % (model.metrics_names[1], score[1] * 100))

#y = model.evaluate_generator(test_generator, 20, max_q_size=10,workers=1, use_multiprocessing=false)

#name_list = model.predict_generator.filenames()

#print(name_list)

#return y

#迭代讀取資料夾下的所有檔案,對每一張進行**

def read_file_all(data_dir_path,model):

right = 0

wrong = 0

for f in os.listdir(data_dir_path):

image_path = os.path.join(data_dir_path, f)

#print(f)

if os.path.isfile(image_path):

preds = read_model_predict(image_path,model)

print(preds[0][0])

if preds[0][0] >= 0.5:

#rdst = 'e:/pcb_image_data/data_2500/right/' + f

#copyfile(image_path, rdst)

right += 1

else:

#wdst = 'e:/pcb_image_data/data_2500/wrong/' + f

#copyfile(image_path, wdst)

#print(preds[0][0])

wrong += 1

else:

read_file_all(image_path)

all_num = right + wrong

tacc = right/all_num

facc = wrong/all_num

return tacc,facc

if __name__ == '__main__':

img_file = '/test'

model = read_model()

tc,fc = read_file_all(img_file,model)

print('true 識別率',tc,'\n','false 識別率',fc)

keras 讀取模型進行測試的方式

from keras.preprocessing import image import numpy as np from keras.models import load model import os from shutil import copyfile from keras.preproce...

keras的回歸模型

基於keras的神經網路回歸模型 import matplotlib.pyplot as plt from math import sqrt from matplotlib import pyplot import pandas as pd from numpy import concatenate...

Keras筆記 3 關於Keras的模型型別

keras有兩種型別的模型,序貫模型 sequential 和函式式模型 model 函式式模型應用更為廣泛,序貫模型是函式式模型的一種特殊情況。兩類模型有一些方法是相同的 config model.get config model model.from config config or,for s...