【问题标题】:Errors related to data type and input shape when building a sequential model构建顺序模型时与数据类型和输入形状相关的错误
【发布时间】:2020-06-24 15:59:24
【问题描述】:

我正在做一个小实验来了解如何构建顺序模型。

我有一个形状为 (10, 10, 5) 的 numpy 数组,称之为feature_0。我创建了如下顺序模型:

model = tf.keras.models.Sequential([
    layers.Dense(units=16, input_shape=(10, 5)),
    layers.Dense(units=8),
    layers.Dense(units=1)
])
model(features_0)
model.summary()

这会返回一个模型摘要给我,如下所示:

Model: "sequential_16"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_48 (Dense)             (None, 10, 16)            96        
_________________________________________________________________
dense_49 (Dense)             (None, 10, 8)             136       
_________________________________________________________________
dense_50 (Dense)             (None, 10, 1)             9         
=================================================================
Total params: 241
Trainable params: 241
Non-trainable params: 0
_________________________________________________________________

这是我所期望的。我知道我不需要将features_0 传递给我的模型来查看摘要,因为已经指定了输入形状。但是,当我尝试这个时,它给了我一个错误:

model = tf.keras.models.Sequential([
    layers.Dense(units=16),
    layers.Dense(units=8),
    layers.Dense(units=1)
])
model(features_0)
model.summary()

我只是删除了第一个隐藏层中的输入形状。我期望看到的是它会向我返回一个模型摘要,并且输出形状将只是multiple,因为没有给出输入形状。相反,我收到以下错误:

InvalidArgumentError: cannot compute MatMul as input #1(zero-based) was expected to be a int64 tensor 
but is a float tensor [Op:MatMul]

我构建模型的第一种和第二种方式有什么区别?我应该总是指定输入形状吗?它似乎与数据类型有关。正如错误提示的那样,模型需要integer 输入,但我的feature_0 是一个numpy 整数数组,形状为(10、10、5)。我创建了这样的 numpy 数组:

features_0 = np.random.randint(100, size=(10, 10, 5))

感谢您的帮助。

【问题讨论】:

  • 您是否尝试过将输入转换为浮点数?
  • 是的,我以前也遇到过这个问题,python 不太擅长指出转换错误

标签: python tensorflow machine-learning keras


【解决方案1】:

我已通过将'int64' 转换为'float64' 解决了这个问题,如下所示:

features_1 = features_0.astype('float32')

model = tf.keras.models.Sequential([
    layers.Dense(units=16),
    layers.Dense(units=8),
    layers.Dense(units=1)
])
model(features_1)
model.summary()

它按预期返回了模型摘要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多