Python Keras(Tensorflow后端)-将MLP中的所有梯度展平为秩1的张量(即1D数组)
假设以下Keras模型:Python Keras(Tensorflow后端)-将MLP中的所有梯度展平为秩1的张量(即1D数组),python,tensorflow,neural-network,keras,gradient,Python,Tensorflow,Neural Network,Keras,Gradient,假设以下Keras模型: model = Sequential() model.add(Dense(512, activation='sigmoid', input_shape=(784,))) model.add(Dense(10, activation='softmax')) 显然,我们可以通过以下方式计算梯度: grads = K.gradients(loss, params) 这就要求: tf.gradients(loss, variables, colocate_gradients
model = Sequential()
model.add(Dense(512, activation='sigmoid', input_shape=(784,)))
model.add(Dense(10, activation='softmax'))
显然,我们可以通过以下方式计算梯度:
grads = K.gradients(loss, params)
这就要求:
tf.gradients(loss, variables, colocate_gradients_with_ops=True)
这将返回一个包含以下内容的张量列表:
#flatten the tensors
flattenedList = [K.flatten(x) for x in grads]
#concatenate them
concatenated = K.concatenate(flattenedList)
好的:)--那你能把它标记为正确答案吗?是的,我刚刚做了