本文涉及到的是中国大学慕课《人工智能实践:Tensorflow笔记》第四讲第五节的内容,通过tensorflow实现神经网络参数的打印以及存入文本。
将神经网络的参数输出并且保存十分简单,从神经网络搭建的六步法来看,与DL with python(9)——TensorFlow实现神经网络模型的断点续训中实现断点续训的代码相比,这里的代码仅在第一步和第六步有所改动。 其中,第一步增加了numpy的调用,以及输出格式的设置(最多输出多少个数)。
np.set_printoptions(precision=小数点后按四舍五入保留几位,threshold=数组元素数量少于或等于门槛值,打印全部元素;否则打印门槛值+1 个元素,中间用省略号补充) 注:precision=np.inf 打印完整小数位;threshold=np.nan 打印全部数组元素。
示例如下:
>> np.set_printoptions(precision=5) >>> print(np.array([1.123456789])) [1.12346] >>> np.set_printoptions(threshold=5) >>> print(np.arange(10)) [0 1 2 … , 7 8 9]第六步增加了参数打印以及保存到txt文本中的代码。较为重要的函数是:
model.trainable_variables # 提取模型中可训练的参数具体代码如下:
# 第一步,导入相关模块,os模块用于判断文件是否存在 import tensorflow as tf import os import numpy as np tf.enable_eager_execution() # 设置输出格式,超过threshold个忽略显示,这里为无限大(全部显示) np.set_printoptions(threshold=np.inf) # 第二步,导入数据集 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.keras.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=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1, callbacks=[cp_callback]) # 第六步,打印网络结构和参数统计 model.summary() # 打印参数,并保存到txt文档中 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() # 关闭文本