鉴于我在相同的数据上训练了多个不同的模型,并且我训练的所有神经网络都具有相同的架构,我想知道是否可以恢复这些模型,平均它们的权重并使用平均值初始化我的权重。
这是图表外观的示例。基本上我需要的是我要加载的重量的平均值。
import tensorflow as tf
import numpy as np
#init model1 weights
weights = {
'w1': tf.Variable(),
'w2': tf.Variable()
}
# init model1 biases
biases = {
'b1': tf.Variable(),
'b2': tf.Variable()
}
#init model2 weights
weights2 = {
'w1': tf.Variable(),
'w2': tf.Variable()
}
# init model2 biases
biases2 = {
'b1': tf.Variable(),
'b2': tf.Variable(),
}
# this the average I want to create
w = {
'w1': tf.Variable(
tf.add(weights["w1"], weights2["w1"])/2
),
'w2': tf.Variable(
tf.add(weights["w2"], weights2["w2"])/2
),
'w3': tf.Variable(
tf.add(weights["w3"], weights2["w3"])/2
)
}
# init biases
b = {
'b1': tf.Variable(
tf.add(biases["b1"], biases2["b1"])/2
),
'b2': tf.Variable(
tf.add(biases["b2"], biases2["b2"])/2
),
'b3': tf.Variable(
tf.add(biases["b3"], biases2["b3"])/2
)
}
weights_saver = tf.train.Saver({
'w1' : weights['w1'],
'w2' : weights['w2'],
'b1' : biases['b1'],
'b2' : biases['b2']
})
weights_saver2 = tf.train.Saver({
'w1' : weights2['w1'],
'w2' : weights2['w2'],
'b1' : biases2['b1'],
'b2' : biases2['b2']
})
这就是我运行 tf 会话时想要得到的。 c 包含我想要用于开始训练的权重。
# Create a session for running operations in the Graph.
init_op = tf.global_variables_initializer()
init_op2 = tf.local_variables_initializer()
with tf.Session() as sess:
coord = tf.train.Coordinator()
# Initialize the variables (like the epoch counter).
sess.run(init_op)
sess.run(init_op2)
weights_saver.restore(
sess,
'my_model1/model_weights.ckpt'
)
weights_saver2.restore(
sess,
'my_model2/model_weights.ckpt'
)
a = sess.run(weights)
b = sess.run(weights2)
c = sess.run(w)