【问题标题】:Get gradient values in a CNN with keras/tf [duplicate]使用 keras/tf 在 CNN 中获取梯度值
【发布时间】:2019-06-26 01:44:29
【问题描述】:

我基本上有一个带有几层的 keras CNN,我想评估一个输入,然后获得反向传播算法的梯度。模型已建立并编译。但我只希望第一次只在一个输入/输出集上运行反向传播,我不关心其他任何事情。

这是我的代码的相关部分:

# Build the model.
model = Sequential()
model.add(Conv2D(16, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(digits, activation='softmax'))

# Prepare the model for training.
model.compile(loss = keras.losses.categorical_crossentropy,
              optimizer = keras.optimizers.Adadelta(),
              metrics=['accuracy'])

而我的一组数据输入输出在x_train和y_train中。那么我究竟如何运行一组数据并根据预期的输出运行反向传播,然后实际得到 keras 计算的梯度?

编辑:本质上,这是一项学术努力,我想做的是自己计算渐变的值,然后将这些值与 keras 得到的值进行比较。那么如何获得这些值呢?

【问题讨论】:

    标签: python tensorflow keras neural-network backpropagation


    【解决方案1】:

    您应该能够使用Keras backend 中的gradients 函数。

    # Gradients of output wrt input
    gradients = K.gradients(model.output, model.input)
    
    # Wrap the input tensor and the gradient tensor in a callable function
    f = K.function([model.input], gradients)
    
    # Random input image
    x = np.random.rand(1, 100,100,3)
    
    f([x])
    > gives an array of shape (1, 100, 100, 3)
    

    编辑:要获得模型权重的输出梯度,可以使用以下代码:

    # List all the weight tensors in the model
    weights_list = model.trainable_weights
    
    # Gradients of output wrt model weights
    gradients = K.gradients(model.output, weights_list)
    
    # Wrap the model input tensor and the gradient tensors in a callable function
    f = K.function([model.input], gradients)
    
    # Random input image
    x = np.random.rand(1,100,100,3)
    
    # Call the function to get the gradients of the model output produced by this image, wrt the model weights
    f([x])
    

    编辑:您的问题可能有答案here

    【讨论】:

    • 我确定我可以,只是我可能不太明白它是如何工作的。从理论的角度来看,我应该得到每个权重的一个梯度值。所以这就是我正在寻找的......或者甚至只有一层就足够了。
    • 所以我肯定以两种不同的方式获得了这些值,我只是不太确定它们代表什么。我在之前的评论中期望每个边缘权重有 1 个值,我错了吗?我现在得到的肯定不是那样的。
    • 更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多