zoukankan      html  css  js  c++  java
  • keras读取后缀名为.h5的文件

    keras读取后缀名为.h5的文件

    一、总结

    一句话总结:

    【hdf5存储,get_weights的函数可以查看】:Keras的模型是用hdf5存储的,如果想要查看模型,keras提供了get_weights的函数可以查看:
    for layer in model.layers:   
        weights = layer.get_weights()  # list of numpy array

    二、keras读取后缀名为.h5的文件

    转自或参考:keras读取后缀名为.h5的文件
    https://blog.csdn.net/cyh153296/article/details/80681132

    Keras的模型是用hdf5存储的,如果想要查看模型,keras提供了get_weights的函数可以查看:

    for layer in model.layers:   
    
     weights = layer.get_weights()  # list of numpy array

    而通过hdf5模块也可以读取:hdf5的数据结构主要是File - Group - Dataset三级,具体操作API可以看官方文档。weights的tensor保存在Dataset的value中,而每一集都会有attrs保存各网络层的属性:

    import h5py
    
    def print_keras_wegiths(weight_file_path):
        f = h5py.File(weight_file_path)  # 读取weights h5文件返回File类
        try:
            if len(f.attrs.items()):
                print("{} contains: ".format(weight_file_path))
                print("Root attributes:")
            for key, value in f.attrs.items():
                print("  {}: {}".format(key, value))  # 输出储存在File类中的attrs信息,一般是各层的名称
    
            for layer, g in f.items():  # 读取各层的名称以及包含层信息的Group类
                print("  {}".format(layer))
                print("    Attributes:")
                for key, value in g.attrs.items(): # 输出储存在Group类中的attrs信息,一般是各层的weights和bias及他们的名称
                    print("      {}: {}".format(key, value))  
    
                print("    Dataset:")
                for name, d in g.items(): # 读取各层储存具体信息的Dataset类
                    print("      {}: {}".format(name, d.value.shape)) # 输出储存在Dataset中的层名称和权重,也可以打印dataset的attrs,但是keras中是空的
                    print("      {}: {}".format(name. d.value))
        finally:
            f.close()

    而如果想修改某个值,则需要通过新建File类,然后用create_group, create_dataset函数将信息重新写入,具体操作可以查看以下链接

    1. http://download.nexusformat.org/sphinx/examples/h5py/index.html
    2. https://github.com/fchollet/keras/issues/91
    3. http://christopherlovell.co.uk/blog/2016/04/27/h5py-intro.html
    4. http://docs.h5py.org/en/latest/quick.html
    5. https://confluence.slac.stanford.edu/display/PSDM/How+to+access+HDF5+data+from+Python#HowtoaccessHDF5datafromPython-Example2:Extractandprintthetimevariables
    则是在一篇博客看到的,方便使用,且自己做好后再更新相关内容。
     
    我的旨在学过的东西不再忘记(主要使用艾宾浩斯遗忘曲线算法及其它智能学习复习算法)的偏公益性质的完全免费的编程视频学习网站: fanrenyi.com;有各种前端、后端、算法、大数据、人工智能等课程。
    博主25岁,前端后端算法大数据人工智能都有兴趣。
    大家有啥都可以加博主联系方式(qq404006308,微信fan404006308)互相交流。工作、生活、心境,可以互相启迪。
    聊技术,交朋友,修心境,qq404006308,微信fan404006308
    26岁,真心找女朋友,非诚勿扰,微信fan404006308,qq404006308
    人工智能群:939687837

    作者相关推荐

  • 相关阅读:
    单元测试
    软件测试计划
    软件杯A9的设计与实现
    阅读笔记7
    阅读笔记6
    阅读笔记5
    阅读笔记4
    阅读笔记3
    阅读笔记2
    阅读笔记1
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/13797469.html
Copyright © 2011-2022 走看看