zoukankan      html  css  js  c++  java
  • Keras 如何利用训练好的神经网络进行预测

    分成两种情况,一种是公开的训练好的模型,下载后可以使用的,一类是自己训练的模型,需要保存下来,以备今后使用。

    如果是第一种情况,则参考    http://keras-cn.readthedocs.io/en/latest/other/application/

    使用的是Application应用,文档中的例子如下

    利用ResNet50网络进行ImageNet分类

    from keras.applications.resnet50 import ResNet50
    from keras.preprocessing import image
    from keras.applications.resnet50 import preprocess_input, decode_predictions
    import numpy as np
    
    model = ResNet50(weights='imagenet')
    #仅仅这样就可以
    img_path = 'elephant.jpg'
    img = image.load_img(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    
    preds = model.predict(x)
    # decode the results into a list of tuples (class, description, probability)
    # (one such list for each sample in the batch)
    print('Predicted:', decode_predictions(preds, top=3)[0])
    # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458

    如果是自己的模型想保存下来,参考http://keras-cn.readthedocs.io/en/latest/for_beginners/FAQ/#keras_1

    又有两种方式,一种是:

    你可以使用model.save(filepath)将Keras模型和权重保存在一个HDF5文件中,该文件将包含:

    • 模型的结构,以便重构该模型
    • 模型的权重
    • 训练配置(损失函数,优化器等)
    • 优化器的状态,以便于从上次训练中断的地方开始

    使用keras.models.load_model(filepath)来重新实例化你的模型,如果文件中存储了训练配置的话,该函数还会同时完成模型的编译

    另外一种方式,可以分开保存模型结构和模型参数:

    如果你只是希望保存模型的结构,而不包含其权重或配置信息,可以使用:

    # save as JSON
    json_string = model.to_json()
    
    # save as YAML
    yaml_string = model.to_yaml()
    

    这项操作将把模型序列化为json或yaml文件,这些文件对人而言也是友好的,如果需要的话你甚至可以手动打开这些文件并进行编辑。

    当然,你也可以从保存好的json文件或yaml文件中载入模型:

    # model reconstruction from JSON:
    from keras.models import model_from_json
    model = model_from_json(json_string)
    
    # model reconstruction from YAML
    model = model_from_yaml(yaml_string)
    

    如果需要保存模型的权重,可通过下面的代码利用HDF5进行保存。注意,在使用前需要确保你已安装了HDF5和其Python库h5py

    model.save_weights('my_model_weights.h5')
    

    如果你需要在代码中初始化一个完全相同的模型,请使用:

    model.load_weights('my_model_weights.h5')
    

    如果你需要加载权重到不同的网络结构(有些层一样)中,例如fine-tune或transfer-learning,你可以通过层名字来加载模型:

    model.load_weights('my_model_weights.h5', by_name=True)


    例子:
    1. json_string = model.to_json()  
    2. open('my_model_architecture.json','w').write(json_string)  
    3. model.save_weights('my_model_weights.h5')  
    4.    
    5. model = model_from_json(open('my_model_architecture.json').read())  
    6. model.load_weights('my_model_weights.h5')  




    http://blog.csdn.net/johinieli/article/details/69367176
    http://blog.csdn.net/johinieli/article/details/69367434
  • 相关阅读:
    九九乘法表
    User-Agent的获取方法
    web前端【第一篇】HTML基础一(标签)
    SQLAlchemy的简单使用
    MongoDB的简单使用
    redis简单使用
    MySQL数据库学习【第十二篇】pymysql模块
    MySQL数据库学习【第十一篇】IDE工具介绍及数据备份
    MySQL数据库学习【第十篇】(视图、触发器、事物)
    MySQL数据库学习【补充】mysql老是停止运行该怎么解决
  • 原文地址:https://www.cnblogs.com/bnuvincent/p/7353887.html
Copyright © 2011-2022 走看看