【问题标题】:keras gradients computation fails "Invalid index from the dimension: 3, 0, C"keras 梯度计算失败“维度中的无效索引:3、0、C”
【发布时间】:2019-04-19 15:07:55
【问题描述】:

当我尝试在具有 conv1d 层的网络中计算 X w.r.t Y 的梯度(X 和 Y 是什么并不重要)时,我收到消息“来自维度的无效索引:3、0, C" 并且进程终止。

最小的工作示例:

import numpy as np

from tensorflow.python.keras import models
from tensorflow.python.keras import layers
from tensorflow.python.keras import backend as K

inp = layers.Input(shape=(10, 20,))
conv = layers.Conv1D(filters=10, kernel_size=2)(inp)
pool = layers.GlobalMaxPool1D()(conv)
output = layers.Dense(1, activation="sigmoid")(pool)

m = models.Model(inp, output)

m.summary()

m.compile(optimizer="adam", loss="binary_crossentropy")

似乎有效:

m.fit(x=np.random.randn(100, 10, 20), y=np.random.randn(100))

这会中断:

loss = K.mean(m.output)
grads = K.gradients(loss, m.input)[0]
f = K.function([m.input], [grads])
print(f([np.random.randn(10, 20)]))

我的 python、keras、tf 版本:

import tensorflow as tf
import sys
from tensorflow.python import keras

print(tf.__version__)
print(keras.__version__)
print(sys.version)

1.12.0
2.1.6-tf
3.6.7 |Anaconda, Inc.| (default, Oct 23 2018, 14:01:38) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]

我计算什么梯度并不重要。错误信息是

2019-04-19 17:00:58.249788: F ./tensorflow/core/util/tensor_format.h:420] Check failed: index >= 0 && index < dimension_attributes.size() Invalid index from the dimension: 3, 0, C

根据错误消息,我看到它与 conv 1d 层有关,但我不太明白我在这里缺少什么。感谢您的任何提示。

【问题讨论】:

  • 我无法重现您的问题。我的返回错误是Invalid argument: transpose expects a vector of size 3. But input(1) is a vector of size 4 上的tensorflow=1.12.0keras=2.1.6-tf

标签: python tensorflow keras


【解决方案1】:

简答:形状不兼容,将调用改为:f([np.random.randn(1, 10, 20)])

长答案:由于您将输入形状设置为(10, 20,),这意味着每个输入样本的形状为(10,20)。但是,您还必须注意,Keras 模型需要一批样本作为输入。因此,在这种情况下,它会期望一个具有 3 个维度的数组,其中第一个维度表示批处理维度。由于您想为模型提供一个样本,因此输入数组的形状必须为(1, 10, 20)。所以你必须相应地改变randn函数中的形状:

f([np.random.randn(1, 10, 20)])
                   ^
                   |
                   |
              batch dimension

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2017-12-06
    • 2021-11-30
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多