我正在实现WGAN,需要裁剪权重变量。
我目前正在使用带有Keras的Tensorflow作为高级API。因此,使用Keras构建层以避免手动创建和初始化变量。
问题是WGAN需要裁剪权重变量,一旦我得到了这些权重变量,就可以使用tf.clip_by_value(x, v0, v1)
来完成,但是我不知道如何安全地获得它们。
一种可能的解决方案可能是使用tf.get_collection()
获取所有可训练变量。但我不知道如何只得到权值变量,而没有偏差变量。
另一种解决方案是layer.get_weights()
,但它获得了numpy
数组,尽管我可以使用numpy
API对它们进行剪辑,并使用layer.set_weights()
设置它们,但这可能需要CPU-GPU公司,而且可能不是一个好的选择,因为需要在每个火车步骤上执行剪辑操作。
我知道的唯一方法是使用精确的变量名直接访问它们,这可以从TF低级API或TensorBoard获得,但这可能并不安全,因为Keras的命名规则并不一定是稳定的。
是否有任何干净的方法只在那些带有Tensorflow和Keras的clip_by_value
上执行W
?
发布于 2017-03-01 04:28:41
可以使用约束(这里)类对参数实现新的约束。
下面是如何轻松地实现权值剪辑并在模型中使用它的方法。
from keras.constraints import Constraint
from keras import backend as K
class WeightClip(Constraint):
'''Clips the weights incident to each hidden unit to be inside a range
'''
def __init__(self, c=2):
self.c = c
def __call__(self, p):
return K.clip(p, -self.c, self.c)
def get_config(self):
return {'name': self.__class__.__name__,
'c': self.c}
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(30, input_dim=100, W_constraint = WeightClip(2)))
model.add(Dense(1))
model.compile(loss='mse', optimizer='rmsprop')
X = np.random.random((1000,100))
Y = np.random.random((1000,1))
model.fit(X,Y)
我已经测试了上述代码的运行情况,但没有测试约束的有效性。您可以通过使用model.get_weights()
或model.layers[idx].get_weights()
获得模型权重并检查其是否符合约束来实现。
注意:约束不是添加到所有模型权重中。但是,仅对其使用的特定层的权重,以及W_constraint
对W
param和b_constraint添加到b
(偏置) param的约束。
https://stackoverflow.com/questions/42530216
复制