• TensorFlow2_200729系列---21、Keras模型保存与加载


    TensorFlow2_200729系列---21、Keras模型保存与加载

    一、总结

    一句话总结:

    模型保存:save方法:network.save('model.h5')
    模型加载:load_model方法:network = tf.keras.models.load_model('model.h5', compile=False)

    二、Keras模型保存与加载

    博客对应课程的视频位置:

    import  os
    os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
    
    import  tensorflow as tf
    from    tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
    
    
    def preprocess(x, y):
        """
        x is a simple image, not a batch
        """
        x = tf.cast(x, dtype=tf.float32) / 255.
        x = tf.reshape(x, [28*28])
        y = tf.cast(y, dtype=tf.int32)
        y = tf.one_hot(y, depth=10)
        return x,y
    
    
    batchsz = 128
    (x, y), (x_val, y_val) = datasets.mnist.load_data()
    print('datasets:', x.shape, y.shape, x.min(), x.max())
    
    
    
    db = tf.data.Dataset.from_tensor_slices((x,y))
    db = db.map(preprocess).shuffle(60000).batch(batchsz)
    ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
    ds_val = ds_val.map(preprocess).batch(batchsz) 
    
    sample = next(iter(db))
    print(sample[0].shape, sample[1].shape)
    
    
    network = Sequential([layers.Dense(256, activation='relu'),
                         layers.Dense(128, activation='relu'),
                         layers.Dense(64, activation='relu'),
                         layers.Dense(32, activation='relu'),
                         layers.Dense(10)])
    network.build(input_shape=(None, 28*28))
    network.summary()
    
    
    
    
    network.compile(optimizer=optimizers.Adam(lr=0.01),
    		loss=tf.losses.CategoricalCrossentropy(from_logits=True),
    		metrics=['accuracy']
    	)
    
    network.fit(db, epochs=3, validation_data=ds_val, validation_freq=2)
     
    network.evaluate(ds_val)
    
    network.save('model.h5')
    print('saved total model.')
    del network
    
    print('loaded model from file.')
    network = tf.keras.models.load_model('model.h5', compile=False)
    network.compile(optimizer=optimizers.Adam(lr=0.01),
            loss=tf.losses.CategoricalCrossentropy(from_logits=True),
            metrics=['accuracy']
        )
    x_val = tf.cast(x_val, dtype=tf.float32) / 255.
    x_val = tf.reshape(x_val, [-1, 28*28])
    y_val = tf.cast(y_val, dtype=tf.int32)
    y_val = tf.one_hot(y_val, depth=10)
    ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val)).batch(128)
    network.evaluate(ds_val)
    
    datasets: (60000, 28, 28) (60000,) 0 255
    (128, 784) (128, 10)
    Model: "sequential"
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    dense (Dense)                multiple                  200960    
    _________________________________________________________________
    dense_1 (Dense)              multiple                  32896     
    _________________________________________________________________
    dense_2 (Dense)              multiple                  8256      
    _________________________________________________________________
    dense_3 (Dense)              multiple                  2080      
    _________________________________________________________________
    dense_4 (Dense)              multiple                  330       
    =================================================================
    Total params: 244,522
    Trainable params: 244,522
    Non-trainable params: 0
    _________________________________________________________________
    Epoch 1/3
    469/469 [==============================] - 2s 4ms/step - loss: 0.2773 - accuracy: 0.9168
    Epoch 2/3
    469/469 [==============================] - 3s 7ms/step - loss: 0.1314 - accuracy: 0.9639 - val_loss: 0.1501 - val_accuracy: 0.9580
    Epoch 3/3
    469/469 [==============================] - 2s 4ms/step - loss: 0.1028 - accuracy: 0.9711
    79/79 [==============================] - 1s 10ms/step - loss: 0.1232 - accuracy: 0.9662
    saved total model.
    loaded model from file.
    79/79 [==============================] - 0s 2ms/step - loss: 0.1232 - accuracy: 0.9662
    
    Out[1]:
    [0.12320274859666824, 0.9661999940872192]
    In [ ]:
     
     
    我的旨在学过的东西不再忘记(主要使用艾宾浩斯遗忘曲线算法及其它智能学习复习算法)的偏公益性质的完全免费的编程视频学习网站: fanrenyi.com;有各种前端、后端、算法、大数据、人工智能等课程。
    博主25岁,前端后端算法大数据人工智能都有兴趣。
    大家有啥都可以加博主联系方式(qq404006308,微信fan404006308)互相交流。工作、生活、心境,可以互相启迪。
    聊技术,交朋友,修心境,qq404006308,微信fan404006308
    26岁,真心找女朋友,非诚勿扰,微信fan404006308,qq404006308
    人工智能群:939687837

    作者相关推荐

  • 相关阅读:
    Django-model聚合查询与分组查询
    Django-model基础
    tempalte模板
    Nginx配置TCP请求转发
    使用python调用email模块发送邮件附件
    将txt文本转换为excel格式
    Linux系统
    Aws云服务EMR使用
    SHELL打印两个日期之间的日期
    02-模板字符串
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/13443982.html
Copyright © 2020-2023  润新知