如何在Keras模型中实现一些可训练参数,如Pytorch中的nn.parameters()?
我只是想用Keras在我的模型中实现一些可训练的参数。在Pytorch中,我们可以使用torch.nn.Parameter()来实现这一点,如下所示:如何在Keras模型中实现一些可训练参数,如Pytorch中的nn.parameters()?,keras,parameters,pytorch,Keras,Parameters,Pytorch,我只是想用Keras在我的模型中实现一些可训练的参数。在Pytorch中,我们可以使用torch.nn.Parameter()来实现这一点,如下所示: self.a = nn.Parameter(torch.ones(8)) self.b = nn.Parameter(torch.zeros(16,8)) 我认为在pytorch中这样做可以在模型中添加一些可训练的参数。现在我想知道,如何在keras实现类似的操作 欢迎任何建议或建议 THX!:) p、 我只是在Keras中写了一个自定义层,如
self.a = nn.Parameter(torch.ones(8))
self.b = nn.Parameter(torch.zeros(16,8))
我认为在pytorch中这样做可以在模型中添加一些可训练的参数。现在我想知道,如何在keras实现类似的操作
欢迎任何建议或建议
THX!:)
p、 我只是在Keras中写了一个自定义层,如下所示:
class Mylayer(Layer):
def __init__(self,input_dim,output_dim,**kwargs):
self.input_dim = input_dim
self.output_dim = output_dim
super(Mylayer,self).__init__(**kwargs)
def build(self):
self.kernel = self.add_weight(name='pi',
shape=(self.input_dim,self.output_dim),
initializer='zeros',
trainable=True)
self.kernel_2 = self.add_weight(name='mean',
shape=(self.input_dim,self.output_dim),
initializer='ones',
trainable=True)
super(Mylayer,self).build()
def call(self,x):
return x,self.kernel,self.kernel_2
我想知道,如果我没有改变通过层的张量,我是否应该编写函数
def compute\u output\u shape()
,以备需要?您需要在自定义层中创建可训练权重:
class MyLayer(Layer):
def __init__(self, my_args, **kwargs):
#do whatever you need with my_args
super(MyLayer, self).__init__(**kwargs)
#you create the weights in build:
def build(self, input_shape):
#use the input_shape to infer the necessary shapes for weights
#use self.whatever_you_registered_in_init to help you, like units, etc.
self.kernel = self.add_weight(name='kernel',
shape=the_shape_you_calculated,
initializer='uniform',
trainable=True)
#create as many weights as necessary for this layer
#build the layer - equivalent to self.built=True
super(MyLayer, self).build(input_shape)
#create the layer operation here
def call(self, inputs):
#do whatever operations are needed
#example:
return inputs * self.kernel #make sure the shapes are compatible
#tell keras about the output shape of your layer
def compute_output_shape(self, input_shape):
#calculate the output shape based on the input shape and your layer's rules
return calculated_output_shape
现在在模型中使用图层
如果您在tensorflow上使用“急切执行”并创建自定义训练循环,则可以使用与PyTorch几乎相同的方法,并且可以使用
tf.Variable
在层外创建权重,将它们作为参数传递给渐变计算方法 谢谢大家!!我想也许我应该使用Keras中的自定义层来实现这一点。我仍然有两个问题:1)如果我希望自定义层在整个模型中不对张量进行任何操作,但创建一个新的可训练参数(例如张量/加权向量),我可以使用上述方法来实现吗?2)我认为使用tf.variable是清晰和紧凑的,但是,如果我的模型是Keras(使用TensorFlow后端),我可以使用这种方法直接构建一个可训练的模型吗。您可以对该层进行黑客攻击,使其返回输入,self.kernel(输入通过该层而不做任何更改,您也可以获得内核)。或者,您可以创建一个虚拟输入来传递到层,如dummy\u input=input(tensor=tf.Variable(1))
,只需在调用中丢弃此输入即可。如果您正在使用“渴望”模式,则可以使用tf.Variable
,并创建自定义训练循环。好的,我刚刚在上面加了一个新代码,你能帮我回答这个问题吗?