【发布时间】:2021-09-08 00:04:15
【问题描述】:
你好,我是神经网络中的新手,我在训练我的模型后使用 google colab 编写了一个模型 CNN 架构 Resnet50,然后保存模型,然后加载模型而不重新启动运行时间得到相同的结果,但是为什么当重新启动运行时 google colab 并运行 xtrain,ytest ,x_val,y_val 然后再次加载模型得到不同的结果
这里是我设置参数的代码
#hyperparameter and callback
batch_size = 128
num_epochs = 120
input_shape = (48, 48, 1)
num_classes = 7
#Compile the model.
from keras.optimizers import Adam, SGD
model = ResNet50(input_shape = (48, 48, 1), classes = 7)
optimizer = SGD(learning_rate=0.0005)
model.compile(optimizer= optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
history = model.fit(
data_generator.flow(xtrain, ytrain,),
steps_per_epoch=len(xtrain) / batch_size,
epochs=num_epochs,
verbose=1,
validation_data= (x_val,y_val))
import matplotlib.pyplot as plt
model.save('Fix_Model_resnet50editSGD5st.h5')
#plot graph
accuracy = history.history['accuracy']
val_accuracy = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
num_epochs = range(len(accuracy))
plt.plot(num_epochs, accuracy, 'r', label='Training acc')
plt.plot(num_epochs, val_accuracy, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend()
plt.figure()
plt.plot(num_epochs, loss, 'r', label='Training loss')
plt.plot(num_epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend()
plt.show()
#load model
from keras.models import load_model
model_load = load_model('Fix_Model_resnet50editSGD5st.h5')
model_load.summary()
testdatamodel = model_load.evaluate(xtest, ytest)
print("Test Loss " + str(testdatamodel[0]))
print("Test Acc: " + str(testdatamodel[1]))
traindata = model_load.evaluate(xtrain, ytrain)
print("Test Loss " + str(traindata[0]))
print("Test Acc: " + str(traindata[1]))
valdata = model_load.evaluate(x_val, y_val)
print("Test Loss " + str(valdata[0]))
print("Test Acc: " + str(valdata[1]))
-在训练和保存模型之后运行加载模型而不重新启动运行时 google colab: 如您所见 测试得到损失:0.9411 - 准确度:0.6514
训练损失:0.7796 - 准确度:0.7091
重启runtime colab后再次运行加载模型:
测试获得损失:0.7928 - 准确度:0.6999
训练损失:0.8189 - 准确度:0.6965
【问题讨论】:
标签: python tensorflow machine-learning neural-network