keras-模型保存和载入

1.数据的载入与预处理

import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential,load_model
from keras.layers import *
from keras.optimizers import SGD

import os

import tensorflow as tf

# 载入数据
(x_train,y_train),(x_test,y_test) = mnist.load_data()

# 预处理
# 将(60000,28,28)转化为(600000,784),好输入展开层
x_train = x_train.reshape(x_train.shape[0],-1)/255.0
x_test= x_test.reshape(x_test.shape[0],-1)/255.0
# 将输出转化为one_hot编码
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10)

2.加载模型等应用

# 加载模型
if os.path.exists('model.h5'):
    print('--------load model-----------')
    model = load_model('model.h5')
else:
    # 创建网络
    model = Sequential([
        # 输入784输出10个
        Dense(units=10,input_dim=784,bias_initializer='one',activation='softmax')
    ])

    # 编译
    # 自定义优化器
    sgd = SGD(lr=0.1)
    model.compile(optimizer=sgd,
                  loss='mse',
                  # 得到训练过程中的准确率
                  metrics=['accuracy'])

    model.fit(x_train,y_train,batch_size=32,epochs=10,validation_split=0.2)



    # 保存模型
    model.save('model.h5')


# 评估模型
loss,acc = model.evaluate(x_test,y_test,)
print('ntest loss',loss)
print('test acc',acc)

# 保存参数
model.save_weights('my_model_weights.h5')
model.load_weights('my_model_weights.h5')

# 保存模型结构
from keras.models import  model_from_json
json_string = model.to_json()
model = model_from_json(json_string)
print(json_string)

out:

  

32/10000 [..............................] - ETA: 5s
2464/10000 [======>.......................] - ETA: 0s
4960/10000 [=============>................] - ETA: 0s
7456/10000 [=====================>........] - ETA: 0s
9856/10000 [============================>.] - ETA: 0s
10000/10000 [==============================] - 0s 23us/step

test loss 0.01504008845295757
test acc 0.9084
{"class_name": "Sequential", "config": [{"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "batch_input_shape": [null, 784], "dtype": "float32", "units": 10, "activation": "softmax", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Ones", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}], "keras_version": "2.1.5", "backend": "tensorflow"}

 

生成文件:

7.keras-模型保存和载入

7.keras-模型保存和载入