Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras(Tensorflow后端)-将MLP中的所有梯度展平为秩1的张量(即1D数组)_Python_Tensorflow_Neural Network_Keras_Gradient - Fatal编程技术网

Python Keras(Tensorflow后端)-将MLP中的所有梯度展平为秩1的张量(即1D数组)

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

假设以下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_with_ops=True)
这将返回一个包含以下内容的张量列表:

  • 包含512x784个元素的张量(输入到隐藏连接的梯度)
  • 具有隐藏层中512个单位偏差梯度的张量
  • 具有10x512元素的张量(隐藏到输出连接的渐变)
  • 具有10个输出单位的偏置梯度的张量
  • 我想问一下,是否有一种简单的方法可以将所有梯度“展平”为一个秩为1的张量(即1D数组),使用(512x784)+512+(10x512)+10个元素,而不在层上循环和相应的偏差

    谢谢

    是的,使用这些功能

    #flatten the tensors
    flattenedList = [K.flatten(x) for x in grads]
    
    #concatenate them
    concatenated = K.concatenate(flattenedList)
    

    好的:)--那你能把它标记为正确答案吗?是的,我刚刚做了