Deep Learning Save and Load model (yaml and json ) tutorial
Yaml file is a human-readable data-serialization language. It is commonly used for configuration files and in applications where data is being stored or transmitted.
save model h5 and yaml
from keras.models import Sequential
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD
import numpy as np
x=np.array([[0,0],[0,1],[1,0],[1,1]])
y=np.array([[0],[1],[1],[0]])
model=Sequential([
Dense(16, input_dim=2),
Activation('tanh'),
Dense(1),
Activation('sigmoid')
])
sgd=SGD(lr=0.1)
model.compile(loss='binary_crossentropy',optimizer=sgd)
model.fit(x,y,batch_size=1,nb_epoch=1000)
score=model.evaluate(x,y,batch_size=1000)
print('score :',score)
print(model.predict(x))
model_to_yaml=model.to_yaml()
with open('model.yaml','w') as yaml_file :
yaml_file.write(model_to_yaml)
model.save_weights('model.h5')
print('saved model two file first yaml , second h5 ')
load model
from keras.models import model_from_yaml
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD
import numpy as np
x=np.array([[0,0],[0,1],[1,0],[1,1]])
y=np.array([[0],[1],[1],[0]])
yaml_file = open('model.yaml','r')
load=yaml_file.read()
yaml_file.close()
load_model =model_from_yaml(load)
load_model.load_weights('model.h5')
print('Load model')
sgd=SGD(lr=0.1)
load_model.compile(loss='binary_crossentropy',optimizer=sgd)
print(load_model.predict_proba(x))
score=load_model.evaluate(x,y,verbose=1)
print(score)
Json is (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.
save model
from keras.models import Sequential
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD
import numpy as np
x=np.array([[0,0],[0,1],[1,0],[1,1]])
y=np.array([[0],[1],[1],[0]])
model=Sequential([
Dense(16, input_dim=2),
Activation('tanh'),
Dense(1),
Activation('sigmoid')
])
sgd=SGD(lr=0.1)
model.compile(loss='binary_crossentropy',optimizer=sgd)
model.fit(x,y,batch_size=1,nb_epoch=1000)
score=model.evaluate(x,y,batch_size=1000)
print('score :',score)
print(model.predict(x))
model_to_json=model.to_json()
with open('model.json','w') as json_file :
json_file.write(model_to_json)
model.save_weights('model.h5')
print('saved model two file first json , second h5 ')
load model
from keras.models import model_from_json
from keras.layers.core import Dense,Dropout,Activation
from keras.optimizers import SGD
import numpy as np
x=np.array([[0,0],[0,1],[1,0],[1,1]])
y=np.array([[0],[1],[1],[0]])
json_file = open('model.json','r')
load=json_file.read()
json_file.close()
load_model =model_from_json(load)
load_model.load_weights('model.h5')
print('Load model')
sgd=SGD(lr=0.1)
load_model.compile(loss='binary_crossentropy',optimizer=sgd)
print(load_model.predict(x))
score=load_model.evaluate(x,y,verbose=1)
print(score)
#GlobalAIandDataScience#GlobalDataScience#Hands-on#Hands-on-feature