我使用Keras制作深度学习模型以模仿XOR门。所以这里的模型:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.models import model_from_json
from keras.utils import np_utils
from keras.optimizers import SGD
import random
X_train = np.array([[0,0],[0,1],[1,0],[1,1]])
Y_train = np.array([[0],[1],[1],[0]])
print(X_train , Y_train )
model = Sequential()
model.add(Dense(8, input_dim=2, activation='tanh'))
model.add(Dense(1, activation='sigmoid'))
sgd = SGD(lr=0.1)
model.compile(loss='binary_crossentropy',
optimizer=sgd, metrics=['accuracy'])
model.fit(X_train, Y_train, nb_epoch=1000, batch_size=1)
scores = model.evaluate(X_train, Y_train)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1] * 100))
print( model.predict(X_train))
model_json = model.to_json()
with open("xor.json", "w") as json_file:
json_file.write(model_json)
inp=np.empty((1,2))
while 1:
inp[0,0]=random.randint(0,1)
inp[0,1]= random.randint(0,1)
prediction = model.predict_proba(inp)
print(inp, '=', prediction)
input('Press enter to continue: ')
它给我很好的准确性:acc:100.00% 和一个很好的预测:
[[ 0.00422836]
[ 0.99482214]
[ 0.99641317]
[ 0.00683813]]
当我尝试对Xor模型进行一些随机输入时,我得到了正确答案:
[[ 1. 0.]] = [[ 0.99641317]]
[[ 0. 1.]] = [[ 0.99482214]]
[[ 0. 1.]] = [[ 0.99482214]]
[[ 0. 1.]] = [[ 0.99482214]]
[[ 0. 0.]] = [[ 0.00422836]]
[[ 1. 1.]] = [[ 0.00683812]]
[[ 0. 0.]] = [[ 0.00422836]]
[[ 1. 1.]] = [[ 0.00683812]]
[[ 0. 1.]] = [[ 0.99482214]]
因此该部分正在工作,但当我将模型保存在Json文件中时,我将其加载到另一个脚本中时:
import numpy as np
from modelnumba import pop_General_6e
from numba import njit
import random
import matplotlib.pyplot as plt
from keras.models import model_from_json
json_file = open('xor.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
inp=np.empty((1,2))
while 1:
inp[0,0]=random.randint(0,1)
inp[0,1]= random.randint(0,1)
prediction = loaded_model.predict_proba(inp)
print(inp, '=', prediction)
input('Press enter to continue: ')
我没有得到正确的预测。
[[ 0. 1.]] = [[ 0.52390206]]
[[ 0. 0.]] = [[ 0.5]]
[[ 0. 1.]] = [[ 0.52390206]]
[[ 0. 0.]] = [[ 0.5]]
[[ 1. 0.]] = [[ 0.38872629]]
[[ 1. 1.]] = [[ 0.42139927]]
[[ 1. 1.]] = [[ 0.42139927]]
[[ 0. 1.]] = [[ 0.52390206]]
我在这里做错了什么?
答案 0 :(得分:1)
问题是您只保存模型的结构。这不包括训练模型时获得的权重。引用Keras FAQ:
如果您只需要保存模型的体系结构,而不是其权重或训练配置,您可以执行以下操作:
json_string = model.to_json()
或者,尝试model.save(filepath)
。这将保存模型结构和从训练模型到使用filepath
指定的文件中获得的权重。