我在做一个小实验,目的是了解如何构建一个顺序模型。
我有一个形状为(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: 241Trainable params: 241Non-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
是一个形状为(10, 10, 5)的整数numpy数组。我是这样创建numpy数组的:
features_0 = np.random.randint(100, size=(10, 10, 5))
谢谢帮助。
回答:
我通过将'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()
它返回了预期的模型摘要。