生成模型的关键步骤

model.add()

model.summary()

model.summary() #打印神经网络结构,统计参数数目

model.compile()

在配置训练方法时,告知训练时用的优化器、损失函数和准确率评测标准

1
2
3
model.compile(optimizer = 优化器
loss = 损失函数,
metrics = ["准确率"])

model.fit()

The history object returned by model.fit() is a simple class with some fields, e.g. a reference to the model, a params dict and, most importantly, a history dict. It stores the values of loss and acc (or any other used metric) at the end of each epoch.

模型的保存

保存模型参数:model.to_json()

1
2
with open("model.json", "w") as json_file:
json_file.write(model_json)

保存 weights:model.save_weights()

1
model.save_weights("model.h5")

.h5 文件

保存某一层的输出:model.layers[index].output

1
2
inp = model.input
outputs = [layer.output for layer in model.layers]

outputs 里的元素的类型是:
<class 'tensorflow.python.framework.ops.Tensor'>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")

# later...

# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model.h5")
print("Loaded model from disk")

# evaluate loaded model on test data
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
score = loaded_model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))
1
2
3
weights_0_list = new_model.layers[0].get_weights()
for i in range(len(weights_0_list)):
print(weights_0_list[i].shape)