【问题标题】:Tensorflow Keras dimensions not equal error for multiple labels多个标签的Tensorflow Keras尺寸不等于错误
【发布时间】:2019-12-10 23:15:38
【问题描述】:

我正在尝试使用 Tensorflow 2.0.0 的 Keras 和 Tensorflow Datasets API 从多维输入预测到多维输出。

我在python 3.6.9 上使用tensorflow 2.0.0tensorflow-datasets 1.3.0

以下是我的示例代码,我还在 [a Colab notebook] (https://colab.research.google.com/drive/1WMccCeLOrQU4k5D2noC4S_5rMe7-krEk) 上复制了它,您可以运行它:

import tensorflow as tf
data = [[1,2],[11,22]]
label = [[3,4,5], [33,44,55]]
dataset = tf.data.Dataset.from_tensor_slices((data,label))
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(3))
model.compile('adam','mse',metrics=['mse'])
model.fit(dataset, validation_data=dataset)

在这个示例代码中,我试图预测 [1,2]->[3,4,5][11,22]->[33,44,55]。但是我得到了错误:

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/tensorflow-2.0.0/python3.6/tensorflow_core/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1609   try:
-> 1610     c_op = c_api.TF_FinishOperation(op_desc)
   1611   except errors.InvalidArgumentError as e:

InvalidArgumentError: Dimensions must be equal, but are 2 and 3 for 'loss/output_1_loss/SquaredDifference' (op: 'SquaredDifference') with input shapes: [2,3], [3,1].

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
29 frames
/tensorflow-2.0.0/python3.6/tensorflow_core/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
   1611   except errors.InvalidArgumentError as e:
   1612     # Convert to ValueError for backwards compatibility.
-> 1613     raise ValueError(str(e))
   1614 
   1615   return c_op

ValueError: Dimensions must be equal, but are 2 and 3 for 'loss/output_1_loss/SquaredDifference' (op: 'SquaredDifference') with input shapes: [2,3], [3,1].

【问题讨论】:

  • 按以下方式使用您的数据集dataset = tf.data.Dataset.from_tensor_slices((np.array(data),np.array(label))).batch(2)
  • @thushv89 事实证明,使用.batch(n) 表示正整数n,例如数据集上的`.batch(2) 允许训练工作。 (你的回答有效)

标签: python tensorflow tensorflow-datasets tensorflow2.0


【解决方案1】:

根据thushv89's comment的问题, 在数据集上使用批处理修复了代码。 原始代码比这更复杂,但使用批处理修复它。

import tensorflow as tf
data = [[1,2],[11,22]]
label = [[3,4,5], [33,44,55]]
dataset = tf.data.Dataset.from_tensor_slices((data,label)).batch(2)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(3))
model.compile('adam','mse',metrics=['mse'])
model.fit(dataset, validation_data=dataset)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 2018-09-01
    • 2019-05-25
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    相关资源
    最近更新 更多