问题描述
我正在使用Keras顺序模型来训练许多多类分类器.
I am using the Keras Sequential model to train a number of multiclass classifiers.
在评估中,Keras输出置信度向量,我可以使用argmax推断出正确的类ID.然后,我可以使用查找表来接收实际的类标签(例如字符串).
On evaluation, Keras outputs a vector of confidences and I can infer the correct class id from that using argmax. I can then use a lookup table to receive the actual class label (e.g. a string).
到目前为止,解决方案是加载训练后的模型,然后分别加载查找表.由于我有很多分类器,因此我希望将两个结构都保存在一个文件中.
So far the solution is to load the trained model, and then to load a lookup table separately. Since I have quite a number of classifiers I would prefer to keep both structures in one file.
所以我正在寻找一种将实际标签查找向量集成到Keras模型中的方法.这样一来,我就可以拥有一个分类器文件,该文件能够获取一些输入数据并为该数据返回正确的类标签.
So what I am looking for is a way to integrate the actual label lookup vector into the Keras model. That would allow me to have a single classifier file that is capable of taking some input data and returning the correct class label for that data.
解决此问题的一种方法是将模型和查找表都存储在一个元组中,然后将该元组写入一个pickle中,但这似乎不是很优雅.
One way to solve this would be to store both the model and the lookup table in a tuple and write that tuple into a pickle, but this doesn't seem very elegant.
推荐答案
所以我亲自尝试了一个解决方案,这似乎可行.我希望有一些更简单的方法.
So I tried my hand at a solution myself and this seems to work. I was hoping for something simpler though.
我认为第二次打开模型文件并不是最佳选择.如果任何人都可以做得更好,那就做.
Opening the model file a second time is not really optimal I think. If anyone can do better, by all means, do.
import h5py
from keras.models import load_model
from keras.models import save_model
def load_model_ext(filepath, custom_objects=None):
model = load_model(filepath, custom_objects=None)
f = h5py.File(filepath, mode='r')
meta_data = None
if 'my_meta_data' in f.attrs:
meta_data = f.attrs.get('my_meta_data')
f.close()
return model, meta_data
def save_model_ext(model, filepath, overwrite=True, meta_data=None):
save_model(model, filepath, overwrite)
if meta_data is not None:
f = h5py.File(filepath, mode='a')
f.attrs['my_meta_data'] = meta_data
f.close()
这篇关于将类别标签附加到Keras模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!