keras ValueError:输入到'Dense'的最后一个维度应该被定义,找到'None',如何处理?[duplicate]

jdzmm42g  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(338)

此问题在此处已有答案

Error: ValueError: The last dimension of the inputs to Dense should be defined. Found None(2个答案)
11小时前关门了。
下面是我的代码:

import numpy as np
import tensorflow as tf

X_train = np.random.random((10000, 100))
y_train = np.concatenate([np.ones(100,), np.zeros(9900,)])

X_valid = np.random.random((10000, 100))
y_valid = np.concatenate([np.ones(100,), np.zeros(9900,)])

input_layer = tf.keras.Input(shape = (None, 100))
latent_x = tf.keras.layers.Flatten()(input_layer)
hidden1 = tf.keras.layers.Dense(30, activation='relu')(latent_x)
hidden2 = tf.keras.layers.Dense(30, activation='relu')(hidden1)
output_layer = tf.keras.layers.Dense(2)(hidden2)

model = tf.keras.models.Model(inputs=[input_layer], outputs=[output_layer])

model.compile(
    loss = 'mean_squared_error',
    optimizer = 'SGD',
    metrics = ['mean_squared_error']
)

history = model.fit(X_train, y_train, 
    epochs=10, 
    validation_data = (X_valid, y_valid), 
    verbose=0)

我得到了错误。

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    hidden1 = tf.keras.layers.Dense(30, activation='relu')(latent_x)
  File "/mypath/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 897, in __call__
    self._maybe_build(inputs)
  File "/mypath/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 2416, in _maybe_build
    self.build(input_shapes)  # pylint:disable=not-callable
  File "/mypath/lib/python3.6/site-packages/tensorflow/python/keras/layers/core.py", line 1154, in build
    raise ValueError('The last dimension of the inputs to `Dense` '
ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.

我的代码有什么问题?我发现许多blog1blog2显示了完全相同的示例代码。但是我无法运行它。

nr9pn0ug

nr9pn0ug1#

input_shape中删除None

input_layer = tf.keras.Input(shape = (100))

相关问题