# 如何取出 tf.layers.dense 定义的全连接层的weight和bias参数值

TensorFlow版本：1.14.0
Python版本：3.6.8

This layer implements the operation: outputs = activation(inputs * kernel + bias) Where activation is the activation function passed as the activation argument (if not None), kernel is a weights matrix created by the layer, and bias is a bias vector created by the layer (only if use_bias is True).

• 创建了一个非常简单的2层全连接网络
• 训练网络
• 训练完成后把它保存成checkpoint格式的模型文件
• 从保存的checkpoint读取模型里第一层的 weight 和 bias 参数值，打印出来
import tensorflow as tf
import numpy as np
LAYER_1_NAME = 'layer1'  # 第一层的名字
LAYER_2_NAME = 'layer2'  # 第二层的名字

# 创建一个非常简单的神经网络，它有两层
x = tf.placeholder(shape=[None, 2], dtype=tf.float32)
layer1 = tf.layers.dense(x, 5, activation=tf.nn.sigmoid, name=LAYER_1_NAME)
layer2 = tf.layers.dense(layer1, 2, activation=tf.nn.sigmoid, name=LAYER_2_NAME)
loss = tf.reduce_mean((layer2 - x) ** 2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
x_values = np.random.normal(0, 1, (5000, 2))  # 生成用于输入的随机数
for step in range(1000):
_, loss_value = sess.run([optimizer, loss], feed_dict={x: x_values})
if step % 100 == 0:
print("step: %d, loss: %f" % (step, loss_value))
# 把模型保存成checkpoint
saver = tf.compat.v1.train.Saver()
save_path = saver.save(sess, './checkpoint/model.ckpt')
print("model saved in path: %s" % save_path, flush=True)
# 读取刚保存的checkpoint
weights = reader.get_tensor(LAYER_1_NAME + '/kernel')  # weight的名字，是由对应层的名字，加上默认的"kernel"组成的
bias = reader.get_tensor(LAYER_1_NAME + '/bias')  # bias的名字
print(weights)
print(bias)
# 如果想打印模型中的所有参数名和参数值的话，把下面几行取消注释
# for key in var_to_shape_map:
#     print("tensor name: ", key)


step: 0, loss: 1.166642
step: 100, loss: 0.764896
step: 200, loss: 0.659553
step: 300, loss: 0.622590
step: 400, loss: 0.604577
step: 500, loss: 0.595308
step: 600, loss: 0.590193
step: 700, loss: 0.587147
step: 800, loss: 0.585213
step: 900, loss: 0.583916
model saved in path: ./checkpoint/model.ckpt
[[-3.0937738   3.6378026   0.91563785 -1.2663897  -0.09645918]
[ 0.727915    0.22842272 -2.656725   -2.0831287  -3.4844823 ]]
[ 0.906906   -1.6009021   0.46897942  0.75946033  1.4348172 ]


weights = reader.get_tensor(LAYER_1_NAME + '/kernel')


©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试