Keras:如何获取权重,使权重变为一维数组,然后使权重形状变为初始形状?

问题描述 投票:0回答:1

我想做一些实验。我需要获取Keras模型权重,使其成为1D数组,并使其形状像初始形状

import tensorflow as tf

from tensorflow import keras
from tensorflow.keras import layers
import numpy as np

model = tf.keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(layers.Dense( 4, input_dim = 5 ,activation='relu'))
# Add another:
model.add(layers.Dense(3, activation='relu'))
# Add an output layer with 10 output units:
model.add(layers.Dense(2))
# Configure a model for mean-squared error regression.
model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
              loss='mse',       # mean squared error
              metrics=['mae'])  # mean absolute error

weights = (model.get_weights())

#make weight  become 1D array

#maka 1D array become like inital shape

model.set_weights(weights)

如何执行此操作?

我们知道Keras模型权重的形状看起来像这样

[array([[-0.24053234,  0.4722855 ,  0.29863954,  0.22805429],
       [ 0.45101106, -0.00229341, -0.6142864 , -0.2751704 ],
       [ 0.159172  ,  0.43983865,  0.61577237,  0.24255097],
       [ 0.24160242,  0.422235  ,  0.8066592 , -0.2711717 ],
       [-0.30763668, -0.4841219 ,  0.767977  ,  0.23558974]],
      dtype=float32), array([0., 0., 0., 0.], dtype=float32), array([[ 0.24129152, -0.4890638 ,  0.18787515],
       [ 0.8663894 , -0.09163451, -0.86416066],
       [-0.01754427,  0.32654428, -0.78837514],
       [ 0.589849  ,  0.5886531 ,  0.27824092]], dtype=float32), array([0., 0., 0.], dtype=float32), array([[ 0.8456359 , -0.26292562],
       [-1.0447757 , -0.43539298],
       [ 1.0835328 , -0.43536085]], dtype=float32), array([0., 0.], dtype=float32)]
python numpy keras
1个回答
0
投票

我会那样做:

weights = model.get_weights()

weights = np.asarray(weights)

weights_shape = weights.shape

weights = np.ravel(weights) #make weight  become 1D array

weights = np.reshape(weights, weights_shape) #mak a 1D array become like inital shape

model.set_weights(weights)
© www.soinside.com 2019 - 2024. All rights reserved.