为了使我的问题更清楚,我在这里写了一段代码:
from keras.layers import Input, Dense
from keras.models import Model
import numpy as np
features = np.random.normal(0, 1, (1000, 3))
labels = np.sum(features, axis=1)
print(features.shape, labels.shape)
input_layer = Input(shape=(3,))
dense_layer_1 = Dense(units=10, activation='sigmoid')
dense_layer_1_output = dense_layer_1(input_layer)
dense_layer_2 = Dense(units=1, activation='linear')
dense_layer_2_output = dense_layer_2(dense_layer_1_output)
model = Model(input_layer, dense_layer_2_output)
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(features, labels, batch_size=32, epochs=20, verbose=2, validation_split=.2)
我的问题是:如何获取和打印这两个密集层的权重和偏差的值?
答案 0 :(得分:1)
您可以简单地使用以下代码来获取这两个密集层的权重和偏差:
for layer in model.layers:
print(layer.name)
w, b = layer.get_weights()
print(w, b)
代码:
input_layer = Input(shape=(3,))
dense_layer_1 = Dense(units=10, activation='sigmoid', name='dense_layer_1')
dense_layer_1_output = dense_layer_1(input_layer)
dense_layer_2 = Dense(units=1, activation='linear', name='dense_layer_2')
dense_layer_2_output = dense_layer_2(dense_layer_1_output)
model = Model(input_layer, dense_layer_2_output)
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(features, labels, batch_size=32, epochs=20, verbose=2, validation_split=.2)
for layer in model.layers[1:]:
print(layer.name)
w, b = layer.get_weights()
print(w, b)
答案 1 :(得分:0)
如上所述here
如果要获取所有图层的权重和偏差,则可以简单地使用:
for layer in model.layers: print(layer.get_config(), layer.get_weights())
如果您希望权重直接以numpy数组形式返回,则可以使用:
first_layer_weights = model.layers[0].get_weights()[0]
first_layer_biases = model.layers[0].get_weights()[1]
second_layer_weights = model.layers[1].get_weights()[0]
second_layer_biases = model.layers[1].get_weights()[1]