加载模型、特征提取
根据InceptionV3提取图片特征
from keras.preprocessing import image
from keras.applications.inception_v3 import InceptionV3, preprocess_input
from keras.models import Model, load_model
from keras.layers import Input
import numpy as np
class Extractor():
def __init__(self, weights=None):
"""Either load pretrained from imagenet, or load our saved
weights from our own training."""
self.weights = weights # so we can check elsewhere which model
if weights is None:
# Get model with pretrained weights.
base_model = InceptionV3(
weights='imagenet',
include_top=True
)
# We'll extract features at the final pool layer.
self.model = Model(
inputs=base_model.input,
outputs=base_model.get_layer('avg_pool').output
)
else:
# Load the model first.
self.model = load_model(weights)
# Then remove the top so we get features not predictions.
# From: https://github.com/fchollet/keras/issues/2371
self.model.layers.pop()
self.model.layers.pop() # two pops to get to pool layer
self.model.outputs = [self.model.layers[-1].output]
self.model.output_layers = [self.model.layers[-1]]
self.model.layers[-1].outbound_nodes = []
def extract(self, image_path):
img = image.load_img(image_path, target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
# Get the prediction.
features = self.model.predict(x)
if self.weights is None:
# For imagenet/default network:
features = features[0]
else:
# For loaded network:
features = features[0]
return features
evaluate/test_on_batch
计算精度,不仅需要输入X,还需要输出y,给出的是最终的metric,top1精度或者top5之类的
evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None)
本函数返回一个测试误差的标量值(如果模型没有其他评价指标),或一个标量的list(如果模型还有其他的评价指标)。model.metrics_names将给出list中各个值的含义。
metric在函数compile的时候输入
test_on_batch(self, x, y, sample_weight=None)
evaluate_generator(self, generator, steps, max_q_size=10, workers=1, pickle_safe=False)
生成器应返回与test_on_batch的输入数据相同类型的数据。
generator:生成输入batch数据的生成器
val_samples:生成器应该返回的总样本数
steps:生成器要返回数据的轮数
max_q_size:生成器队列的最大容量
nb_worker:使用基于进程的多线程处理时的进程数
pickle_safe:若设置为True,则使用基于进程的线程。注意因为它的实现依赖于多进程处理,不可传递不可pickle的参数到生成器中,因为它们不能轻易的传递到子进程中。
return : [test loss, metrics]
def evaluate_model(weight_path,model_name):
rm=Total_Models(total_classes,model_name,optimizer,lr)
val_generator,train_generator,train_sample,test_sample = generator()
#6659 2737 9396
#39882 16390
rm.model.load_weights(weight_path,by_name=True) #
acc = rm.model.evaluate_generator(val_generator,2737/32+1)
print acc
**[mertics](https://keras.io/zh/metrics/)**
#### predict/predict_on_batch/predict_generator
只输入X,用法情形与evaluate相同