如何修复google-colab tensorflow ValueError?



这是我写的代码:

tf.random.set_seed(42)

model = tf.keras.Sequential([
tf.keras.layers.Dense(1)
])
model.compile(loss = tf.keras.losses.mae, 
optimizer = tf.keras.optimizers.SGD( ),
metrics = ["mae"]) 

model.fit(X, y, epochs=2)

我得到的错误是:

/usr/local/lib/python3.7/dist- packages/tensorflow/python/framework/func_graph.py in 
autograph_handler(*args, **kwargs)
1145           except Exception as e:  # pylint:disable=broad-except
1146             if hasattr(e, "ag_error_metadata"):
-> 1147               raise e.ag_error_metadata.to_exception(e)
1148             else:
1149               raise
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1021, in train_function  *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1010, in step_function  **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1000, in run_step  **
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 859, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 228, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" '
ValueError: Exception encountered when calling layer "sequential_5" (type Sequential).

Input 0 of layer "dense_4" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)

Call arguments received:
• inputs=tf.Tensor(shape=(None,), dtype=float32)
• training=True
• mask=None

我也面临同样的问题。如果你正在尝试遵循Daniel Bourke的深度学习代码,请查看他的github代码。

下面是代码中的修复:
# Fit the model
# model.fit(X, y, epochs=5) # this will break with TensorFlow 2.7.0+
model.fit(tf.expand_dims(X, axis=-1), y, epochs=5)

它对我有用。

相关内容

  • 没有找到相关文章

最新更新