훈련 된 네트워크에서 새 모델로 마지막 계층 (출력 계층)에 대한 가중치로드
Aug 18 2020
set_weights 및 get_weights 체계를 사용하여 훈련 된 네트워크에서 새 모델의 마지막 계층에 가중치를로드 할 수 있습니까? 요점은 Matlab에서 계산을 수행하기 위해 각 레이어의 가중치를 매트 파일 (학습 후)로 저장했으며 마지막 레이어의 수정 된 가중치 만 새 모델 및 다른 레이어의 마지막 레이어에로드되기를 원한다는 것입니다. 훈련 된 모델과 동일한 가중치를 얻습니다. 저장된 형식이 매트이기 때문에 약간 까다 롭습니다.
weights1 = lstm_model1.layers[0].get_weights()[0]
biases1 = lstm_model1.layers[0].get_weights()[1]
weights2 = lstm_model1.layers[2].get_weights()[0]
biases2 = lstm_model1.layers[2].get_weights()[1]
weights3 = lstm_model1.layers[4].get_weights()[0]
biases3 = lstm_model1.layers[4].get_weights()[1]
# Save the weights and biases for adaptation algorithm
savemat("weights1.mat", mdict={'weights1': weights1})
savemat("biases1.mat", mdict={'biases1': biases1})
savemat("weights2.mat", mdict={'weights2': weights2})
savemat("biases2.mat", mdict={'biases2': biases2})
savemat("weights3.mat", mdict={'weights3': weights3})
savemat("biases3.mat", mdict={'biases3': biases3})
다른 레이어의 이전 가중치 만 새 모델 (마지막 레이어 제외)에로드하고 마지막 레이어의 수정 된 가중치를 새 모델의 마지막 레이어에로드하려면 어떻게해야합니까?
답변
1 RyanRudes Aug 24 2020 at 13:41
.h5 파일 형식으로 저장된 경우 작동합니다. 그러나 .mat에 대해 잘 모르겠습니다.
간단히 말해서 get_weights
원하는 레이어 를 호출 하고 마찬가지로 set_weights
다른 모델의 해당 레이어 를 호출하면 됩니다 .
last_layer_weights = old_model.layers[-1].get_weights()
new_model.layers[-1].set_weights(last_layer_weights)
더 완전한 코드 샘플을 보려면 여기로 이동하십시오.
# Create an arbitrary model with some weights, for example
model = Sequential(layers = [
Dense(70, input_shape = (100,)),
Dense(60),
Dense(50),
Dense(5)])
# Save the weights of the model
model.save_weights(“model.h5”)
# Later, load in the model (we only really need the layer in question)
old_model = Sequential(layers = [
Dense(70, input_shape = (100,)),
Dense(60),
Dense(50),
Dense(5)])
old_model.load_weights(“model.h5”)
# Create a new model with slightly different architecture (except for the layer in question, at least)
new_model = Sequential(layers = [
Dense(80, input_shape = (100,)),
Dense(60),
Dense(50),
Dense(5)])
# Set the weights of the final layer of the new model to the weights of the final layer of the old model, but leaving other layers unchanged.
new_model.layers[-1].set_weights(old_model.layers[-1].get_weights())
# Assert that the weights of the final layer is the same, but other are not.
print (np.all(new_model.layers[-1].get_weights()[0] == old_model.layers[-1].get_weights()[0]))
>> True
print (np.all(new_model.layers[-2].get_weights()[0] == old_model.layers[-2].get_weights()[0]))
>> False