概述
我们有时候想看看保存的模型参数是多少,那我们应该如何提取参数并存入文本呢?
tensorflow提供了model.trainable_variables来返回模型中可训练的参数,那我们如果想看参数可以设置print打印出来,但是直接用print打印的话,会有很多的数据会被省略号替换掉。
设置print输出格式:
np.set_printoptionbs(threshold=超过多少省略显示)
如果下面这样设置就表示打印过程中不使用省略号。所有的都打印。
np.set_printoptinos(threshold=np.inf) # inf 表示无限大
print(model.trainable_variables)
也可以将训练的参数存入文本,如下所示:
file = open('./weights.txt','w')
for v in model.trainable_variables:
file.write(str(v.name)+'\n')
file.write(str(v,shape)+'\n')
file.write(str(v.numpy())+'\n')
file.close()
案例分析
import tensorflow as tf
import os
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss=tf.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
checkpoint_save_path = './checkpoint/mnist.ckpt'
if os.path.exists(checkpoint_save_path + '.index'):
print('------------------------load the model---------------------')
model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True)
history = model.fit(x_train, y_train, batch_size=10, epochs=5,
validation_data=(x_test, y_test),
validation_freq=1,
callbacks=[cp_callback])
model.summary()
print(model.trainable_variables)
file = open('./weights.txt', 'w')
for v in model.trainable_variables:
file.write(str(v.name) + '\n')
file.write(str(v.shape) + '\n')
file.write(str(v.numpy()) + '\n')
file.close()
这就把可训练的参数都打印出来了,而且也保存在了文件里