npy文件是numpy专用的二进制文件,npy内容由一个字典组成,字典中的每一个键对应一层网络模型参数(包括权重w和偏置b)。
对于某些网络模型参数保存为.npy形式的文件,我们需要读取这些文件的参数,并fine tune到当前网络相应的变量。
def load_initial_weights(session):
# Load the weights into memory
weights_dict = np.load('C:\\Downloads\\bvlc_alexnet.npy', encoding = 'bytes').item()
# Loop over all layer names stored in the weights dict
for op_name in weights_dict:
# Check if the layer is one of the layers that should be reinitialized
if op_name not in ['fc6','fc7','fc8']:
with tf.variable_scope('shared/'+op_name,reuse = True):
# Loop over list of weights/biases and assign them to their corresponding tf variable
for data in weights_dict[op_name]:
# Biases
if len(data.shape) == 1:
var = tf.get_variable('biases', trainable = True)
print(var.name)
session.run(var.assign(data))
# Weights
else:
var = tf.get_variable('weights', trainable = True)
session.run(var.assign(data))