gpt4 book ai didi

python - 如何使用Keras API提取权重 "from input layer to hidden layer"和 "from hidden layer to output layer"?

转载 作者:行者123 更新时间:2023-11-30 08:57:28 27 4
gpt4 key购买 nike

我是 Keras 新手,我正在尝试获取 Keras 中的权重。我知道如何在 Python 中的 Tensorflow 中执行此操作。

代码:

data = np.array(attributes, 'int64')
target = np.array(labels, 'int64')

feature_columns = [tf.contrib.layers.real_valued_column("", dimension=2, dtype=tf.float32)]
learningRate = 0.1
epoch = 10000

# https://www.tensorflow.org/api_docs/python/tf/metrics
validation_metrics = {
"accuracy": tf.contrib.learn.MetricSpec(metric_fn = tf.contrib.metrics.streaming_accuracy ,
prediction_key = tf.contrib.learn.PredictionKey.CLASSES),
"precision": tf.contrib.learn.MetricSpec(metric_fn = tf.contrib.metrics.streaming_precision ,
prediction_key = tf.contrib.learn.PredictionKey.CLASSES),
"recall": tf.contrib.learn.MetricSpec(metric_fn = tf.contrib.metrics.streaming_recall ,
prediction_key = tf.contrib.learn.PredictionKey.CLASSES),
"mean_absolute_error": tf.contrib.learn.MetricSpec(metric_fn = tf.contrib.metrics.streaming_mean_absolute_error ,
prediction_key = tf.contrib.learn.PredictionKey.CLASSES),
"false_negatives": tf.contrib.learn.MetricSpec(metric_fn = tf.contrib.metrics.streaming_false_negatives ,
prediction_key = tf.contrib.learn.PredictionKey.CLASSES),
"false_positives": tf.contrib.learn.MetricSpec(metric_fn = tf.contrib.metrics.streaming_false_positives ,
prediction_key = tf.contrib.learn.PredictionKey.CLASSES),
"true_positives": tf.contrib.learn.MetricSpec(metric_fn = tf.contrib.metrics.streaming_true_positives ,
prediction_key = tf.contrib.learn.PredictionKey.CLASSES)
}

# validation monitor
validation_monitor = tf.contrib.learn.monitors.ValidationMonitor(data, target, every_n_steps=500,
metrics = validation_metrics)

classifier = tf.contrib.learn.DNNClassifier(
feature_columns = feature_columns,
hidden_units = [3],
activation_fn = tf.nn.sigmoid,
optimizer = tf.train.GradientDescentOptimizer(learningRate),
model_dir = "model",
config = tf.contrib.learn.RunConfig(save_checkpoints_secs = 1)
)

classifier.fit(data, target, steps = epoch,
monitors = [validation_monitor])

# print('Params:', classifier.get_variable_names())
'''
Params: ['dnn/binary_logistic_head/dnn/learning_rate', 'dnn/hiddenlayer_0/biases', 'dnn/hiddenlayer_0/weights', 'dnn/logits/biases', 'dnn/logits/weights', 'global_step']
'''

print('total steps:', classifier.get_variable_value("global_step"))
print('weight from input layer to hidden layer: ', classifier.get_variable_value("dnn/hiddenlayer_0/weights"))
print('weight from hidden layer to output layer: ', classifier.get_variable_value("dnn/logits/weights"))

有没有办法像在 Tensorflow 中一样在 Keras 中获取权重:

  1. 输入层到隐藏层的权重
  2. 隐藏层到输出层的权重

这是我在 Keras 中的模型:

model = Sequential()
model.add(Flatten(input_shape=(224,224,3)))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))

最佳答案

您可以使用 get_weightsset_weights 方法访问和设置模型各层的权重或参数。来自 Keras documentation :

layer.get_weights(): returns the weights of the layer as a list of Numpy arrays. layer.set_weights(weights): sets the weights of the layer from a list of Numpy arrays (with the same shapes as the output of get_weights).

每个 Keras 模型都有一个layers 属性,它是模型中所有层的列表。例如,在您提供的示例模型中,您可以通过运行以下命令获取第一个 Dense 层的权重:

model.layers[1].get_weights()

它将返回两个 numpy 数组的列表:第一个是密集层的内核参数,第二个数组是偏差参数。

关于python - 如何使用Keras API提取权重 "from input layer to hidden layer"和 "from hidden layer to output layer"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54009036/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com