【问题标题】:How can I get the weights (kernel) of a Dense layer before Model in Keras?如何在 Keras 中的模型之前获得密集层的权重(内核)?
【发布时间】:2019-03-16 01:35:56
【问题描述】:
import numpy as np
from keras import backend as K
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Dense, Input
import matplotlib.pyplot as plt

# download the mnist to the path 
# X shape (60,000 28x28), y shape (10,000, )
(x_train, _), (x_test, y_test) = mnist.load_data()

# data pre-processing
x_train = x_train.astype('float32') / 255. - 0.5       # minmax_normalized
x_test = x_test.astype('float32') / 255. - 0.5         # minmax_normalized
x_train = x_train.reshape((x_train.shape[0], -1))
x_test = x_test.reshape((x_test.shape[0], -1))


# in order to plot in a 2D figure
encoding_dim = 2

# this is our input placeholder
input_img = Input(shape=(784,))


# encoder layers
encoder = Dense(2, activation='relu')(input_img)

# decoder layers
decoder = Dense(784, activation='relu')(encoder)`

我想知道如何在keras 中获得Model 之前的Dense 层的权重(例如Dense_2 的内核)?

如果我运行:autoencoder = Model(input=input_img,output=decoder),然后运行autoencoder.get_layer('dense_2').kernel,我可以获得内核。但是,我想将内核设置为输出之一。所以,我必须在Model 之前得到内核。

我想得到kernel,因为它将被设置为损失函数的一部分,例如loss2=tf.square(kernel' * kernel, axis=-1)。所以我必须在运行Model 之前获得kernel

我该怎么做?

谢谢!

【问题讨论】:

  • 请不要将 cmets 空间用于此类附加信息 - 改为编辑和更新您的帖子

标签: machine-learning keras autoencoder


【解决方案1】:

我认为您的意思是您需要将中间层之一作为输出之一。 在您的情况下,您可以通过以下方式更改模型创建:

autoencoder = Model(input=input_img,output=[encoder,decoder])

您甚至可以为这两个输出中的每一个定义不同的损失!

【讨论】:

  • 感谢您的帮助。其实我只是想拿到Dense_2的内核,即decoder。我想确保内核是正交的。于是我设计了一个惩罚函数,即loss2,并定义了loss2=tf.square(kernel' * kernel - I, axis=-1)。
猜你喜欢
  • 1970-01-01
  • 2017-10-07
  • 2017-07-31
  • 2019-11-18
  • 2021-10-02
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
相关资源
最近更新 更多